/* * Copyright (c) 2026 Winsider Seminars & Solutions, Inc. All rights reserved. * * Compile-time parsing for the phlib PH_FORMAT engine. C++20 only. * * Syntax: sequential {}, escaped {{ and }}, and {:spec}. A spec may contain * [fill][<|>][+][0][width][.precision][type]. Types are d/x/X/b for * integers, f/e/g for floating point, and s for wide strings/characters. * Width uses phlib alignment (< or >) or integer zero padding (0). Precision * applies only to floating point. Pointers and sizes require explicit wrappers. * * This is not the complete fmt language: positional/named fields, dynamic * widths, space sign, center alignment, alternate form, and integer precision * are rejected. Signed nondecimal integers use phlib's sign-and-magnitude * output. Floating g uses phlib's standard form and six-digit default. */ #ifndef _PH_FORMAT_COMPILED_HPP #define _PH_FORMAT_COMPILED_HPP #include #include #include #include #include #include #include template struct PH_COMPILED_FORMAT_POINTER { T* Value; }; template PH_COMPILED_FORMAT_POINTER PhFormatPointer(T* value) { return { value }; } struct PH_COMPILED_FORMAT_SIZE { ULONG64 Value; }; inline PH_COMPILED_FORMAT_SIZE PhFormatSizeValue(ULONG64 value) { return { value }; } template struct PhCompiledFormatString { WCHAR Text[N]; consteval PhCompiledFormatString(const WCHAR (&text)[N]) : Text{} { for (std::size_t i = 0; i < N; ++i) Text[i] = text[i]; } }; namespace PhCompiledFormatDetail { struct Fragment { std::size_t Offset; std::size_t Length; }; struct Specifier { WCHAR Type = 0; WCHAR Align = 0; WCHAR Fill = L' '; USHORT Width = 0; USHORT Precision = 0; bool HasWidth = false; bool HasPrecision = false; bool Sign = false; bool Zero = false; }; template struct ParsedFormat { std::array Text{}; std::array Fragments{}; std::array Specifiers{}; std::size_t Fields = 0; }; consteval bool IsDigit(WCHAR value) { return value >= L'0' && value <= L'9'; } template consteval auto Parse() { constexpr std::size_t length = std::size(format.Text) - 1; ParsedFormat result{}; std::size_t input = 0; std::size_t output = 0; std::size_t fragmentStart = 0; while (input < length) { if (format.Text[input] == L'{') { if (input + 1 < length && format.Text[input + 1] == L'{') { result.Text[output++] = L'{'; input += 2; continue; } result.Fragments[result.Fields] = { fragmentStart, output - fragmentStart }; ++input; Specifier spec{}; if (input < length && format.Text[input] == L':') { ++input; if (input + 1 < length && (format.Text[input + 1] == L'<' || format.Text[input + 1] == L'>')) { spec.Fill = format.Text[input++]; spec.Align = format.Text[input++]; if (spec.Fill == L'{' || spec.Fill == L'}') throw "Braces cannot be fill characters"; } else if (input < length && (format.Text[input] == L'<' || format.Text[input] == L'>')) { spec.Align = format.Text[input++]; } if (input < length && format.Text[input] == L'+') { spec.Sign = true; ++input; } if (input < length && format.Text[input] == L'0') { spec.Zero = true; ++input; } while (input < length && IsDigit(format.Text[input])) { spec.HasWidth = true; const unsigned digit = format.Text[input++] - L'0'; if (spec.Width > (std::numeric_limits::max)() / 10 || static_cast(spec.Width) * 10 + digit > (std::numeric_limits::max)()) throw "Format width exceeds USHORT"; spec.Width = static_cast(spec.Width * 10 + digit); } if (input < length && format.Text[input] == L'.') { ++input; if (input == length || !IsDigit(format.Text[input])) throw "Format precision requires digits"; while (input < length && IsDigit(format.Text[input])) { spec.HasPrecision = true; const unsigned digit = format.Text[input++] - L'0'; if (spec.Precision > (std::numeric_limits::max)() / 10 || static_cast(spec.Precision) * 10 + digit > (std::numeric_limits::max)()) throw "Format precision exceeds USHORT"; spec.Precision = static_cast(spec.Precision * 10 + digit); } } if (input < length && format.Text[input] != L'}') spec.Type = format.Text[input++]; } if (input == length || format.Text[input] != L'}') throw "Invalid compiled format field"; if (spec.Zero && (!spec.HasWidth || spec.Align || spec.Fill != L' ')) throw "Zero padding requires a width and no alignment"; result.Specifiers[result.Fields++] = spec; ++input; fragmentStart = output; } else if (format.Text[input] == L'}') { if (input + 1 == length || format.Text[input + 1] != L'}') throw "Unmatched closing brace"; result.Text[output++] = L'}'; input += 2; } else { result.Text[output++] = format.Text[input++]; } } result.Fragments[result.Fields] = { fragmentStart, output - fragmentStart }; return result; } template inline constexpr auto Parsed = Parse(); template inline constexpr bool IsWideString = std::is_convertible_v && !std::is_same_v, std::nullptr_t>; template inline constexpr bool IsPointerWrapper = false; template inline constexpr bool IsPointerWrapper> = true; template consteval bool Supports(Specifier spec) { using Value = std::remove_cvref_t; if constexpr (std::is_integral_v && !std::is_same_v && !std::is_same_v) return !spec.HasPrecision && (spec.Type == 0 || spec.Type == L'd' || spec.Type == L'x' || spec.Type == L'X' || spec.Type == L'b') && (!spec.Zero || spec.Type == 0 || spec.Type == L'd' || spec.Type == L'x' || spec.Type == L'X' || spec.Type == L'b'); else if constexpr (std::is_same_v || std::is_same_v) return !spec.Zero && (spec.Type == 0 || spec.Type == L'f' || spec.Type == L'e' || spec.Type == L'g'); else if constexpr (IsPointerWrapper) return !spec.Sign && !spec.Zero && !spec.HasPrecision && (spec.Type == 0 || spec.Type == L'x' || spec.Type == L'X'); else if constexpr (std::is_same_v) return !spec.Sign && !spec.Zero && !spec.HasPrecision && spec.Type == 0; else if constexpr (std::is_same_v || IsWideString || std::is_same_v) return !spec.Zero && !spec.Sign && !spec.HasPrecision && (spec.Type == 0 || spec.Type == L's'); else return false; } template inline void Bind(PPH_FORMAT element, T&& value) { using Value = std::remove_cvref_t; if constexpr (std::is_same_v) PhInitFormatC(element, value); else if constexpr (std::is_same_v) PhInitFormatSR(element, value); else if constexpr (IsWideString) PhInitFormatS(element, value); else if constexpr (IsPointerWrapper) PhInitFormatIX(element, reinterpret_cast(value.Value)); else if constexpr (std::is_same_v) PhInitFormatSize(element, value.Value); else if constexpr (std::is_floating_point_v) { if constexpr (std::is_same_v) { element->Type = SingleFormatType; element->u.Single = value; } else { element->Type = DoubleFormatType; element->u.Double = static_cast(value); } } else if constexpr (std::is_integral_v && std::is_signed_v && sizeof(Value) <= sizeof(LONG)) PhInitFormatD(element, static_cast(value)); else if constexpr (std::is_integral_v && std::is_unsigned_v && sizeof(Value) <= sizeof(ULONG)) PhInitFormatU(element, static_cast(value)); else if constexpr (std::is_integral_v && std::is_signed_v && sizeof(Value) <= sizeof(LONG64)) PhInitFormatI64D(element, static_cast(value)); else if constexpr (std::is_integral_v && std::is_unsigned_v && sizeof(Value) <= sizeof(ULONG64)) PhInitFormatI64U(element, static_cast(value)); } inline void Apply(PPH_FORMAT element, Specifier spec) { if (spec.Type == L'x' || spec.Type == L'X' || spec.Type == L'b') { element->Type |= FormatUseRadix; element->Radix = spec.Type == L'b' ? 2 : 16; if (spec.Type == L'X') element->Type |= FormatUpperCase; } else if (spec.Type == L'e' || spec.Type == L'g') element->Type |= FormatStandardForm; if (spec.Sign) element->Type |= FormatPrefixSign; if (spec.HasPrecision) { element->Type |= FormatUsePrecision; element->Precision = spec.Precision; } if (spec.Zero) { element->Type |= FormatPadZeros; element->Width = spec.Width; } if (spec.Align) { element->Type |= spec.Align == L'<' ? FormatLeftAlign : FormatRightAlign; element->Width = spec.Width; if (spec.Fill != L' ') { element->Type |= FormatUsePad; element->Pad = spec.Fill; } } } template inline void BindField(PPH_FORMAT element, T&& value) { constexpr auto spec = Parsed.Specifiers[index]; static_assert(Supports(spec), "Unsupported compiled format argument or specifier"); static_assert(!spec.HasWidth || spec.Align || spec.Zero, "Width requires alignment or zero padding"); static_assert(!spec.Align || spec.HasWidth, "Alignment requires a width"); Bind(element, std::forward(value)); Apply(element, spec); } template inline void BindFragment(PPH_FORMAT element) { constexpr auto fragment = Parsed.Fragments[index]; PH_STRINGREF string{ fragment.Length * sizeof(WCHAR), const_cast(Parsed.Text.data() + fragment.Offset) }; PhInitFormatSR(element, string); } template inline auto MakeArray(std::index_sequence, Args&&... args) { std::array elements{}; ((BindFragment(&elements[indices * 2]), BindField(&elements[indices * 2 + 1], std::forward(args))), ...); BindFragment(&elements[sizeof...(Args) * 2]); return elements; } } // BufferLength and ReturnLength are bytes, including the output terminator. template BOOLEAN PhFormatToBufferCompiled( _Out_writes_bytes_opt_(BufferLength) PWSTR Buffer, _In_ SIZE_T BufferLength, _Out_opt_ PSIZE_T ReturnLength, Args&&... args ) { static_assert(sizeof...(Args) == PhCompiledFormatDetail::Parsed.Fields, "Compiled format argument count mismatch"); static_assert(sizeof...(Args) * 2 + 1 <= (std::numeric_limits::max)(), "Too many format fields"); auto elements = PhCompiledFormatDetail::MakeArray(std::index_sequence_for{}, std::forward(args)...); return PhFormatToBuffer(elements.data(), static_cast(elements.size()), Buffer, BufferLength, ReturnLength); } template PPH_STRING PhFormatCompiled(Args&&... args) { static_assert(sizeof...(Args) == PhCompiledFormatDetail::Parsed.Fields, "Compiled format argument count mismatch"); static_assert(sizeof...(Args) * 2 + 1 <= (std::numeric_limits::max)(), "Too many format fields"); auto elements = PhCompiledFormatDetail::MakeArray(std::index_sequence_for{}, std::forward(args)...); return PhFormat(elements.data(), static_cast(elements.size()), 0); } #endif