From 1dca4d8bbf13b4d0da682ee709210c78f024218b Mon Sep 17 00:00:00 2001 From: Space V <40030799+spacevx@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:43:57 +0100 Subject: [PATCH 1/3] Make printf formatting follow C --- Source.Common.Tests/CFormattingTests.cs | 141 +++++ Source.Common/CFormatting.cs | 663 ++++++++++++++++++------ 2 files changed, 634 insertions(+), 170 deletions(-) create mode 100644 Source.Common.Tests/CFormattingTests.cs diff --git a/Source.Common.Tests/CFormattingTests.cs b/Source.Common.Tests/CFormattingTests.cs new file mode 100644 index 00000000..40dca1e7 --- /dev/null +++ b/Source.Common.Tests/CFormattingTests.cs @@ -0,0 +1,141 @@ +using System.Globalization; + +namespace Source.Common.Tests; + +public class CFormattingTests +{ + static string Format(string format, params object?[] args) { + CultureInfo.CurrentCulture = new CultureInfo("fr-FR"); + CFormatReader reader = new(format); + Span piece = stackalloc char[16]; + string result = ""; + while (!reader.Overflowed()) + result += new string(piece[..CFormatting.sprintf(piece, ref reader, args)]); + return result; + } + + [Theory] + [InlineData("%d", 42, "42")] + [InlineData("%i", -42, "-42")] + [InlineData("%5d", 42, " 42")] + [InlineData("%-5d|", 42, "42 |")] + [InlineData("%05d", -42, "-0042")] + [InlineData("%+d", 42, "+42")] + [InlineData("% d", 42, " 42")] + [InlineData("%.3d", 7, "007")] + [InlineData("%8.3d", -7, " -007")] + [InlineData("%.0d", 0, "")] + [InlineData("%u", -1, "4294967295")] + [InlineData("%x", 255, "ff")] + [InlineData("%X", 255, "FF")] + [InlineData("%#x", 255, "0xff")] + [InlineData("%#010x", 255, "0x000000ff")] + [InlineData("%o", 8, "10")] + [InlineData("%#o", 8, "010")] + [InlineData("%hd", 65537, "1")] + [InlineData("%hhu", 511, "255")] + [InlineData("%d", 4294967298L, "2")] + [InlineData("%lld", 4294967298L, "4294967298")] + [InlineData("%I64d", -5000000000L, "-5000000000")] + [InlineData("%llu", ulong.MaxValue, "18446744073709551615")] + [InlineData("%llx", long.MinValue, "8000000000000000")] + [InlineData("%d", 3000000000u, "-1294967296")] + [InlineData("%u", 3000000000u, "3000000000")] + [InlineData("%d", (short)-3, "-3")] + [InlineData("%d", (byte)200, "200")] + [InlineData("%d", true, "1")] + [InlineData("%d", DayOfWeek.Friday, "5")] + [InlineData("%c", 'x', "x")] + [InlineData("%c", 65, "A")] + [InlineData("%3c|", 'z', " z|")] + public void Integers(string format, object arg, string expected) => Assert.Equal(expected, Format(format, arg)); + + [Theory] + [InlineData("%f", 700.0, "700.000000")] + [InlineData("%f", 0.1, "0.100000")] + [InlineData("%.2f", 3.14159, "3.14")] + [InlineData("%.0f", 2.5, "2")] + [InlineData("%.0f", 3.5, "4")] + [InlineData("%.2f", 0.125, "0.12")] + [InlineData("%10.3f", -3.14159, " -3.142")] + [InlineData("%-10.3f|", 3.14159, "3.142 |")] + [InlineData("%010.3f", -3.14159, "-00003.142")] + [InlineData("%+.1f", 9.9999, "+10.0")] + [InlineData("%#.0f", 1.0, "1.")] + [InlineData("%3.0f", 7.25, " 7")] + [InlineData("%e", 12345.678, "1.234568e+04")] + [InlineData("%E", 0.000123456, "1.234560E-04")] + [InlineData("%.0e", 12345.678, "1e+04")] + [InlineData("%g", 0.0001, "0.0001")] + [InlineData("%g", 0.00001, "1e-05")] + [InlineData("%g", 100000.0, "100000")] + [InlineData("%g", 1000000.0, "1e+06")] + [InlineData("%.3g", 3.14159, "3.14")] + [InlineData("%#g", 0.5, "0.500000")] + [InlineData("%G", 1e-10, "1E-10")] + [InlineData("%f", double.PositiveInfinity, "inf")] + [InlineData("%F", double.NegativeInfinity, "-INF")] + [InlineData("%f", -0.0, "-0.000000")] + [InlineData("%.2a", 1.0, "0x1.00p+0")] + [InlineData("%.0a", 0.5, "0x1p-1")] + [InlineData("%f", 700f, "700.000000")] + [InlineData("%.2f", 3.14159f, "3.14")] + [InlineData("%g", 0.1f, "0.1")] + [InlineData("%f", 7, "7.000000")] + public void Floats(string format, object arg, string expected) => Assert.Equal(expected, Format(format, arg)); + + [Theory] + [InlineData("%s", "abc", "abc")] + [InlineData("%5s", "abc", " abc")] + [InlineData("%-5s|", "abc", "abc |")] + [InlineData("%.2s", "abc", "ab")] + [InlineData("%s", null, "(null)")] + [InlineData("%s", 1.5, "1.5")] + [InlineData("%s", DayOfWeek.Monday, "Monday")] + public void Strings(string format, object? arg, string expected) => Assert.Equal(expected, Format(format, arg)); + + [Fact] + public void SeveralArguments() { + Assert.Equal("sv_gravity = 700.000000\n", Format("%s = %f\n", "sv_gravity", 700f)); + Assert.Equal(" 42|42 |3.14", Format("%*d|%-*d|%.*f", 5, 42, 5, 42, 2, 3.14159)); + Assert.Equal("100% done 3%", Format("100%% done %d%%", 3)); + } + + [Fact] + public void MissingArgumentsStayVerbatim() { + Assert.Equal("50% done, 10 % of x, %d %5.2f", Format("50% done, 10 % of x, %d %5.2f")); + Assert.Equal("1 and %s", Format("%d and %s", 1)); + Assert.Equal("%y then 7", Format("%y then %d", 7)); + Assert.Equal("100%", Format("100%")); + } + + [Fact] + public void LongOutputSpansPieces() { + string big = new('x', 100); + Assert.Equal($"<{big}> 42 <{big}>", Format("<%s> %d <%s>", big, 42, big)); + Assert.Equal(new string(' ', 99) + "1|a" + new string(' ', 99) + "|", Format("%100d|%-100s|", 1, "a")); + } + + [Fact] + public void FluentPrintF() { + CultureInfo.CurrentCulture = new CultureInfo("fr-FR"); + Span buffer = stackalloc char[64]; + Assert.Equal("5:07", CFormatting.sprintf(buffer, "%d:%.2d").D(5).D(7).ToSpan()); + Assert.Equal("1.500 0.5", CFormatting.sprintf(buffer, "%.3f %g").F(1.5f).G(0.5).ToSpan()); + Assert.Equal("12.500000 -0.100000", CFormatting.sprintf(buffer, "%f %f").F(12.5f).F(-0.1f).ToSpan()); + Assert.Equal("007, 60 fps", CFormatting.sprintf(buffer, "%03d,%3i fps").D(7).I(60).ToSpan()); + Assert.Equal("STEAM_0:1:3000000000", CFormatting.sprintf(buffer, "STEAM_0:%u:%u").U(1).U(3000000000).ToSpan()); + Assert.Equal("ab | cd|ef", CFormatting.sprintf(buffer, "%-6s|%4s|%.2s").S("ab").S("cd").S("efgh").ToSpan()); + Assert.Equal("12.0M", CFormatting.sprintf(buffer, "%.1fM").D(12).ToSpan()); + Assert.Equal("a/b 50%", CFormatting.sprintf(buffer, "%s%c%s %d%%").S("a").C('/').S("b").D(50).ToSpan()); + Assert.Equal("4294967298", CFormatting.sprintf(buffer, "%d").D(4294967298L).ToSpan()); + } + + [Fact] + public void FluentPrintFClampsToTheBuffer() { + Span buffer = stackalloc char[6]; + PrintF result = CFormatting.sprintf(buffer, "%s-%d").S("abcdef").D(123456); + Assert.Equal("abcdef", result.ToSpan()); + Assert.True(result.Overflowed); + } +} diff --git a/Source.Common/CFormatting.cs b/Source.Common/CFormatting.cs index da654cdc..ec3c8205 100644 --- a/Source.Common/CFormatting.cs +++ b/Source.Common/CFormatting.cs @@ -55,6 +55,13 @@ public SpanWriter Write(scoped ReadOnlySpan span) { public readonly int Length => writePtr; public readonly bool Overflowed => overflowed; + public readonly Span Remaining => input[writePtr..]; + + public void Advance(int count, int wanted) { + if (writePtr + wanted >= input.Length) + overflowed = true; + writePtr += count; + } public Span ToSpan() => input[..writePtr]; public static implicit operator Span(SpanWriter self) => self.input[..self.writePtr]; @@ -94,80 +101,75 @@ private unsafe void WriteAnyLiterals() { public static implicit operator Span(PrintF self) => self.input; public static implicit operator int(PrintF self) => self.input.Length; - public PrintF D(int i) { + PrintF WriteInteger(long value, char natural, bool wide) { WriteAnyLiterals(); - reader.ReadVariable(out char t, out int varIdx); - Span buffer = stackalloc char[11]; - if (i.TryFormat(buffer, out int written)) -#pragma warning disable CS9080 // Use of variable in this context may expose referenced variables outside of their declaration scope - input.Write(buffer[..written]); -#pragma warning restore CS9080 // Use of variable in this context may expose referenced variables outside of their declaration scope + reader.ReadSpec(out CFormatSpec spec); + CFormatOutput output = new(input.Remaining); + if (CFormatUtils.IsFloatConversion(spec.Type)) + CFormatUtils.WriteFloat(ref output, in spec, value); + else if (spec.Type is 'c' or 'C') + CFormatUtils.WriteChar(ref output, in spec, (char)value); + else { + if (!CFormatUtils.IsIntegerConversion(spec.Type)) + spec.Type = natural; + if (wide && spec.Length == CFormatLength.None) + spec.Length = CFormatLength.LongLong; + CFormatUtils.WriteInteger(ref output, in spec, value); + } + input.Advance(output.Written, output.Total); WriteAnyLiterals(); return this; } - public PrintF F(float i) { + PrintF WriteFloat(double value, char natural) { WriteAnyLiterals(); - reader.ReadVariable(out char t, out int varIdx); - Span buffer = stackalloc char[11]; - if (i.TryFormat(buffer, out int written)) -#pragma warning disable CS9080 // Use of variable in this context may expose referenced variables outside of their declaration scope - input.Write(buffer[..written]); -#pragma warning restore CS9080 // Use of variable in this context may expose referenced variables outside of their declaration scope + reader.ReadSpec(out CFormatSpec spec); + CFormatOutput output = new(input.Remaining); + if (CFormatUtils.IsIntegerConversion(spec.Type)) + CFormatUtils.WriteInteger(ref output, in spec, (long)value); + else { + if (!CFormatUtils.IsFloatConversion(spec.Type)) + spec.Type = natural; + CFormatUtils.WriteFloat(ref output, in spec, value); + } + input.Advance(output.Written, output.Total); WriteAnyLiterals(); return this; } - public PrintF U(uint i) { - WriteAnyLiterals(); - reader.ReadVariable(out char t, out int varIdx); - Span buffer = stackalloc char[11]; - if (i.TryFormat(buffer, out int written)) -#pragma warning disable CS9080 // Use of variable in this context may expose referenced variables outside of their declaration scope - input.Write(buffer[..written]); -#pragma warning restore CS9080 // Use of variable in this context may expose referenced variables outside of their declaration scope + public PrintF D(int i) => WriteInteger(i, 'd', false); + public PrintF D(long i) => WriteInteger(i, 'd', true); + public PrintF I(int i) => WriteInteger(i, 'd', false); + public PrintF U(uint i) => WriteInteger(i, 'u', false); + public PrintF F(float i) => WriteFloat(i, 'f'); + public PrintF F(double i) => WriteFloat(i, 'f'); + public PrintF G(double i) => WriteFloat(i, 'g'); + public PrintF C(char c) { WriteAnyLiterals(); - return this; - } - public PrintF D(long i) { - WriteAnyLiterals(); - reader.ReadVariable(out char t, out int varIdx); - Span buffer = stackalloc char[19]; - if (i.TryFormat(buffer, out int written)) -#pragma warning disable CS9080 // Use of variable in this context may expose referenced variables outside of their declaration scope - input.Write(buffer[..written]); -#pragma warning restore CS9080 // Use of variable in this context may expose referenced variables outside of their declaration scope + reader.ReadSpec(out CFormatSpec spec); + CFormatOutput output = new(input.Remaining); + if (CFormatUtils.IsIntegerConversion(spec.Type)) + CFormatUtils.WriteInteger(ref output, in spec, c); + else + CFormatUtils.WriteChar(ref output, in spec, c); + input.Advance(output.Written, output.Total); WriteAnyLiterals(); return this; } - [MethodImpl(MethodImplOptions.AggressiveInlining)] public PrintF I(int i) => D(i); - public PrintF G(double i) { - WriteAnyLiterals(); - reader.ReadVariable(out char t, out int varIdx); - Span buffer = stackalloc char[32]; - if (i.TryFormat(buffer, out int written, t == 'f' ? "F6" : "G6", CultureInfo.InvariantCulture)) -#pragma warning disable CS9080 // Use of variable in this context may expose referenced variables outside of their declaration scope - input.Write(buffer[..written]); -#pragma warning restore CS9080 // Use of variable in this context may expose referenced variables outside of their declaration scope - WriteAnyLiterals(); - return this; - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] public PrintF F(double i) => G(i); - public PrintF C(char c) { - WriteAnyLiterals(); - reader.ReadVariable(out char t, out int varIdx); - input.Write([c]); - WriteAnyLiterals(); - return this; - } public PrintF S(scoped ReadOnlySpan str) { - if (reader.ReadVariable(out char type, out int variableIdx)) { - input.Write(str.SliceNullTerminatedString()); + if (reader.ReadSpec(out CFormatSpec spec)) { + CFormatOutput output = new(input.Remaining); + if (spec.Type is 's' or 'S') + CFormatUtils.WriteString(ref output, in spec, str); + else + output.Write(str.SliceNullTerminatedString()); + + input.Advance(output.Written, output.Total); WriteAnyLiterals(); } return this; @@ -278,50 +280,180 @@ public unsafe ScanF Read(out float i, int max = DEFAULT_SCANF_MAX) { } } +public enum CFormatLength +{ + None, + Char, + Short, + Long, + LongLong, + Size, + LongDouble +} + +public struct CFormatSpec +{ + public char Type; + public CFormatLength Length; + public int Width; + public int Precision; + public int WidthArg; + public int PrecisionArg; + public int ValueArg; + public int TextStart; + public int TextLength; + public bool LeftAlign; + public bool PlusSign; + public bool SpaceSign; + public bool AltForm; + public bool ZeroPad; +} + +public ref struct CFormatOutput +{ + readonly Span target; + readonly int skip; + int position; + int written; + + public CFormatOutput(Span target, int skip = 0) { + this.target = target; + this.skip = skip; + } + + public readonly int Written => written; + public readonly int Total => position; + + public void Write(char c) { + if (position >= skip && written < target.Length) + target[written++] = c; + position++; + } + + public void Write(scoped ReadOnlySpan text) { + for (int i = 0; i < text.Length; i++) + Write(text[i]); + } + + public void Fill(char c, int count) { + for (int i = 0; i < count; i++) + Write(c); + } +} + public ref struct CFormatReader { int formatReader = 0; bool haltedAtVariable; int variableIdx; readonly ReadOnlySpan format; + public int ResumeOffset; public CFormatReader(ReadOnlySpan format) { this.format = format; } public bool Overflowed() => formatReader >= format.Length || format[formatReader] == '\0'; + public readonly ReadOnlySpan GetText(in CFormatSpec spec) => format.Slice(spec.TextStart, spec.TextLength); /// /// Reads one literal into a read target buffer. /// /// A target buffer /// How much was written to the target. >0 if any literal was read at all. 0 if a halt break occured due to an incoming variable or end-of-stream. - public int ReadLiteral(Span readTarget) { + public int ReadLiteral(scoped Span readTarget) { if (haltedAtVariable) return 0; int chars = 0; - for (int i = 0; i < readTarget.Length; i++) { - if (Overflowed()) - return chars; - + while (chars < readTarget.Length && !Overflowed()) { char c = format[formatReader]; - if (c == '%') { - i++; - if (formatReader + 1 < format.Length && format[formatReader + 1] != '%' && format[formatReader + 1] != '\0') { - // We have to stop, a variable was reached - formatReader++; + if (c == '%' && formatReader + 1 < format.Length && format[formatReader + 1] != '\0') { + formatReader++; + if (format[formatReader] != '%') { haltedAtVariable = true; - break; // We wrote something if i > 0, even if we guarded here + break; } } - // Otherwise, write + readTarget[chars++] = c; formatReader++; } return chars; } + + bool ReadPrefix(ReadOnlySpan prefix) { + if (!format[formatReader..].StartsWith(prefix)) + return false; + + formatReader += prefix.Length; + return true; + } + + bool ReadNumber(out int value) { + int start = formatReader; + long number = 0; + while (!Overflowed() && char.IsAsciiDigit(format[formatReader])) + number = Math.Min(number * 10 + (format[formatReader++] - '0'), int.MaxValue); + + value = (int)number; + return formatReader > start; + } + + CFormatLength ReadLength() { + if (ReadPrefix("hh")) return CFormatLength.Char; + if (ReadPrefix("h")) return CFormatLength.Short; + if (ReadPrefix("ll") || ReadPrefix("I64") || ReadPrefix("j")) return CFormatLength.LongLong; + if (ReadPrefix("l")) return CFormatLength.Long; + if (ReadPrefix("I32") || ReadPrefix("w")) return CFormatLength.None; + if (ReadPrefix("z") || ReadPrefix("t") || ReadPrefix("I")) return CFormatLength.Size; + if (ReadPrefix("L")) return CFormatLength.LongDouble; + return CFormatLength.None; + } + + public bool ReadSpec(out CFormatSpec spec) { + spec = new() { Width = -1, Precision = -1, WidthArg = -1, PrecisionArg = -1, ValueArg = -1 }; + if (!haltedAtVariable) + return false; + + spec.TextStart = formatReader - 1; + for (; !Overflowed(); formatReader++) { + char flag = format[formatReader]; + if (flag == '-') spec.LeftAlign = true; + else if (flag == '+') spec.PlusSign = true; + else if (flag == ' ') spec.SpaceSign = true; + else if (flag == '#') spec.AltForm = true; + else if (flag == '0') spec.ZeroPad = true; + else break; + } + + if (ReadPrefix("*")) + spec.WidthArg = variableIdx++; + else if (ReadNumber(out int width)) + spec.Width = width; + + if (ReadPrefix(".")) { + if (ReadPrefix("*")) + spec.PrecisionArg = variableIdx++; + else { + ReadNumber(out int precision); + spec.Precision = precision; + } + } + + spec.Length = ReadLength(); + if (!Overflowed()) { + spec.Type = format[formatReader++]; + if (CFormatUtils.IsConversion(spec.Type)) + spec.ValueArg = variableIdx++; + } + + spec.TextLength = formatReader - spec.TextStart; + haltedAtVariable = false; + return true; + } + /// /// Tries to read one variable type. ReadLiteral must have triggered a halt before this function will return true. /// @@ -336,72 +468,221 @@ public bool ReadVariable(out char type, out int variableIdx) { if (Overflowed()) return false; - type = char.ToLowerInvariant(format[formatReader++]); - variableIdx = this.variableIdx; - this.variableIdx++; - haltedAtVariable = false; + ReadSpec(out CFormatSpec spec); + type = char.ToLowerInvariant(spec.Type); + variableIdx = spec.ValueArg >= 0 ? spec.ValueArg : this.variableIdx++; return true; } } public static class CFormatUtils { - public static int WriteFormattedObject(Span writeBuffer, char type, object? arg) { - int writeSize = 0; +#if WIN32 + const int LONG_BITS = 32; +#else + const int LONG_BITS = 64; +#endif + + public static bool IsIntegerConversion(char type) => type is 'd' or 'i' or 'u' or 'o' or 'x' or 'X' or 'D' or 'U' or 'O'; + public static bool IsFloatConversion(char type) => type is 'f' or 'F' or 'e' or 'E' or 'g' or 'G' or 'a' or 'A'; + public static bool IsConversion(char type) => IsIntegerConversion(type) || IsFloatConversion(type) || type is 'c' or 'C' or 's' or 'S' or 'p' or 'n'; + + static void WritePadded(ref CFormatOutput output, in CFormatSpec spec, scoped ReadOnlySpan prefix, int zeros, scoped ReadOnlySpan body, bool zeroPad) { + int padding = Math.Max(0, spec.Width - prefix.Length - zeros - body.Length); + if (spec.LeftAlign) { + output.Write(prefix); + output.Fill('0', zeros); + output.Write(body); + output.Fill(' ', padding); + return; + } + + if (!zeroPad) + output.Fill(' ', padding); + output.Write(prefix); + output.Fill('0', zeroPad ? zeros + padding : zeros); + output.Write(body); + } - VariableType varType; - if (type == 'd') - varType = VariableType.SignedDecimalInteger; + public static void WriteInteger(ref CFormatOutput output, in CFormatSpec spec, long value) { + int bits = spec.Length switch { + CFormatLength.Char => 8, + CFormatLength.Short => 16, + CFormatLength.Long => LONG_BITS, + CFormatLength.LongLong or CFormatLength.Size or CFormatLength.LongDouble => 64, + _ => 32 + }; + + bool signed = spec.Type is 'd' or 'i' or 'D'; + bool negative = false; + ulong magnitude; + if (signed) { + long narrowed = value << (64 - bits) >> (64 - bits); + negative = narrowed < 0; + magnitude = negative ? unchecked((ulong)-narrowed) : (ulong)narrowed; + } else - varType = (VariableType)type; + magnitude = bits == 64 ? unchecked((ulong)value) : unchecked((ulong)value) & ((1UL << bits) - 1); + + uint radix = spec.Type switch { + 'x' or 'X' => 16, + 'o' or 'O' => 8, + _ => 10 + }; + + ReadOnlySpan alphabet = spec.Type == 'X' ? "0123456789ABCDEF" : "0123456789abcdef"; + Span digits = stackalloc char[24]; + int start = digits.Length; + for (ulong rest = magnitude; rest != 0; rest /= radix) + digits[--start] = alphabet[(int)(rest % radix)]; + + int digitCount = digits.Length - start; + int minDigits = spec.Precision >= 0 ? spec.Precision : 1; + if (radix == 8 && spec.AltForm && minDigits <= digitCount) + minDigits = digitCount + 1; + + ReadOnlySpan prefix = ""; + if (signed) + prefix = negative ? "-" : spec.PlusSign ? "+" : spec.SpaceSign ? " " : ""; + else if (radix == 16 && spec.AltForm && magnitude != 0) + prefix = spec.Type == 'X' ? "0X" : "0x"; + + WritePadded(ref output, in spec, prefix, Math.Max(0, minDigits - digitCount), digits[start..], spec.ZeroPad && spec.Precision < 0); + } + + public static void WriteFloat(ref CFormatOutput output, in CFormatSpec spec, double value) { + char type = char.ToLowerInvariant(spec.Type); + bool upper = type != spec.Type; + bool finite = double.IsFinite(value); + string body; + if (!finite) + body = FormatFixed(value, 0); + else { + double magnitude = Math.Abs(value); + int precision = spec.Precision >= 0 ? spec.Precision : 6; + body = type switch { + 'e' => FormatExponent(magnitude, precision, spec.AltForm), + 'g' => FormatGeneral(magnitude, precision, spec.AltForm), + 'a' => FormatHex(magnitude, spec.Precision, spec.AltForm), + _ => spec.AltForm && precision == 0 ? FormatFixed(magnitude, precision) + "." : FormatFixed(magnitude, precision) + }; + } + + Span prefix = stackalloc char[3]; + int prefixLength = 0; + if (finite ? double.IsNegative(value) : body[0] == '-') + prefix[prefixLength++] = '-'; + else if (spec.PlusSign) + prefix[prefixLength++] = '+'; + else if (spec.SpaceSign) + prefix[prefixLength++] = ' '; + + if (finite && type == 'a') { + prefix[prefixLength++] = '0'; + prefix[prefixLength++] = upper ? 'X' : 'x'; + } + + if (upper) + body = body.ToUpperInvariant(); + + WritePadded(ref output, in spec, prefix[..prefixLength], 0, body.AsSpan(body[0] == '-' ? 1 : 0), finite && spec.ZeroPad); + } + + public static void WriteString(ref CFormatOutput output, in CFormatSpec spec, scoped ReadOnlySpan text) { + text = text.SliceNullTerminatedString(); + if (spec.Precision >= 0 && text.Length > spec.Precision) + text = text[..spec.Precision]; + WritePadded(ref output, in spec, "", 0, text, spec.ZeroPad); + } + + public static void WriteChar(ref CFormatOutput output, in CFormatSpec spec, char value) { + WritePadded(ref output, in spec, "", 0, new ReadOnlySpan(in value), spec.ZeroPad); + } + + static bool TryGetInteger(object? arg, out long value) { switch (arg) { - case int v when varType == VariableType.SignedDecimalInteger: - v.TryFormat(writeBuffer, out writeSize); - break; - case uint v when varType == VariableType.UnsignedDecimalInteger: - v.TryFormat(writeBuffer, out writeSize); - break; - case uint v when varType == VariableType.UnsignedOctal: - string uoctal = Convert.ToString(v, 8); // ugh - uoctal.CopyTo(writeBuffer); - writeSize = uoctal.Length; - break; - case uint v when varType == VariableType.UnsignedHexadecimalInteger: - v.TryFormat(writeBuffer, out writeSize, "x"); - break; - case double v when varType == VariableType.DecimalFloatingPoint: - v.TryFormat(writeBuffer, out writeSize, "F"); - break; - case double v when varType == VariableType.ScientificNotation: - v.TryFormat(writeBuffer, out writeSize, "E"); - break; - case double v when varType == VariableType.ShortestRepresentation: - v.TryFormat(writeBuffer, out writeSize, "G"); - break; - case double v when varType == VariableType.HexadecimalFloatingPoint: - var bits = BitConverter.DoubleToInt64Bits(v); - writeSize = bits.TryFormat(writeBuffer, out var written, "X") ? written : 0; - break; - case char v when varType == VariableType.Character: - writeBuffer[0] = v; - writeSize = 1; + case int v: value = v; return true; + case uint v: value = v; return true; + case long v: value = v; return true; + case ulong v: value = unchecked((long)v); return true; + case short v: value = v; return true; + case ushort v: value = v; return true; + case sbyte v: value = v; return true; + case byte v: value = v; return true; + case char v: value = v; return true; + case bool v: value = v ? 1 : 0; return true; + case nint v: value = v; return true; + case nuint v: value = unchecked((long)v); return true; + case float v: value = (long)v; return true; + case double v: value = (long)v; return true; + case Enum v: value = v.GetTypeCode() == TypeCode.UInt64 ? unchecked((long)Convert.ToUInt64(v)) : Convert.ToInt64(v); return true; + default: value = 0; return false; + } + } + + static bool TryGetFloat(object? arg, out double value) { + switch (arg) { + case double v: value = v; return true; + case float v: value = v; return true; + case ulong v: value = v; return true; + default: + bool converted = TryGetInteger(arg, out long integer); + value = integer; + return converted; + } + } + + public static void WriteObject(ref CFormatOutput output, in CFormatSpec spec, object? arg) { + switch (spec.Type) { + case 'c' or 'C': + if (TryGetInteger(arg, out long character)) + WriteChar(ref output, in spec, (char)character); break; - case string v when varType == VariableType.StringOfCharacters: - v.AsSpan().CopyTo(writeBuffer); - writeSize = v.Length; + case 's' or 'S': + switch (arg) { + case null: WriteString(ref output, in spec, "(null)"); break; + case string text: WriteString(ref output, in spec, text); break; + case char[] text: WriteString(ref output, in spec, text); break; + case ReadOnlyMemory text: WriteString(ref output, in spec, text.Span); break; + case Memory text: WriteString(ref output, in spec, text.Span); break; + case IFormattable text: WriteString(ref output, in spec, text.ToString(null, CultureInfo.InvariantCulture)); break; + default: WriteString(ref output, in spec, arg.ToString()); break; + } break; - case object v when varType == VariableType.PointerAddress: - var ptrStr = $"0x{v.GetHashCode():X}"; - ptrStr.AsSpan().CopyTo(writeBuffer); - writeSize = ptrStr.Length; + case 'p': + if (arg != null) + WritePadded(ref output, in spec, "", 0, $"0x{arg.GetHashCode():X}", false); break; - case object _ when varType == VariableType.Nothing: + case 'n': break; default: + if (IsFloatConversion(spec.Type)) { + if (TryGetFloat(arg, out double number)) + WriteFloat(ref output, in spec, number); + } + else if (TryGetInteger(arg, out long integer)) + WriteInteger(ref output, in spec, integer); break; } - return writeSize; + } + + public static void WriteArgument(ref CFormatOutput output, in CFormatSpec source, scoped ReadOnlySpan text, scoped ReadOnlySpan args) { + if (source.ValueArg < 0 || source.ValueArg >= args.Length) { + output.Write(text); + return; + } + + CFormatSpec spec = source; + if (spec.WidthArg >= 0 && TryGetInteger(args[spec.WidthArg], out long width)) { + spec.LeftAlign |= width < 0; + spec.Width = (int)Math.Abs(Math.Clamp(width, -int.MaxValue, int.MaxValue)); + } + + if (spec.PrecisionArg >= 0 && TryGetInteger(args[spec.PrecisionArg], out long precision)) + spec.Precision = precision < 0 ? -1 : (int)Math.Min(precision, int.MaxValue); + + WriteObject(ref output, in spec, args[spec.ValueArg]); } } @@ -562,20 +843,13 @@ public static string FormatFixed(double value, int precision) { return negative ? "-" + result : result; } - public static string FormatG(double value, int precision = 6) { + static string SignificantDigits(double value, int precision, out int exp10) { long bits = BitConverter.DoubleToInt64Bits(value); - bool negative = bits < 0; long fraction = bits & 0xFFFFFFFFFFFFFL; int exponent = (int)((bits >> 52) & 0x7FF); - - if (exponent == 0x7FF) - return FormatFixed(value, 0); - - if (precision == 0) - precision = 1; - + exp10 = 0; if (exponent == 0 && fraction == 0) - return negative ? "-0" : "0"; + return new string('0', precision); BigInteger num = exponent == 0 ? fraction : fraction | (1L << 52); BigInteger den = BigInteger.One; @@ -585,7 +859,7 @@ public static string FormatG(double value, int precision = 6) { else den <<= -shift; - int exp10 = (int)Math.Floor(BigInteger.Log10(num) - BigInteger.Log10(den)); + exp10 = (int)Math.Floor(BigInteger.Log10(num) - BigInteger.Log10(den)); if (exp10 >= 0 ? num < den * BigInteger.Pow(10, exp10) : num * BigInteger.Pow(10, -exp10) < den) exp10--; else if (exp10 + 1 >= 0 ? num >= den * BigInteger.Pow(10, exp10 + 1) : num * BigInteger.Pow(10, -(exp10 + 1)) >= den) @@ -605,24 +879,76 @@ public static string FormatG(double value, int precision = 6) { exp10++; } - string d = digits.ToString(CultureInfo.InvariantCulture); + return digits.ToString(CultureInfo.InvariantCulture); + } + + static string WithExponent(string mantissa, int exp10) { + int absExp = Math.Abs(exp10); + return $"{mantissa}e{(exp10 < 0 ? '-' : '+')}{(absExp < 10 ? "0" : "")}{absExp}"; + } + + internal static string FormatExponent(double value, int precision, bool forcePoint) { + string d = SignificantDigits(value, precision + 1, out int exp10); + return WithExponent(precision > 0 ? $"{d[0]}.{d[1..]}" : forcePoint ? $"{d}." : d, exp10); + } + + internal static string FormatGeneral(double value, int precision, bool keepZeros) { + if (!double.IsFinite(value)) + return FormatFixed(value, 0); + + if (precision == 0) + precision = 1; + + string d = SignificantDigits(Math.Abs(value), precision, out int exp10); + bool exponential = exp10 < -4 || exp10 >= precision; string result; - if (exp10 < -4 || exp10 >= precision) { - string mant = d.Length > 1 ? $"{d[0]}.{d[1..]}".TrimEnd('0').TrimEnd('.') : d; - int absExp = Math.Abs(exp10); - result = $"{mant}e{(exp10 < 0 ? '-' : '+')}{(absExp < 10 ? "0" : "")}{absExp}"; - } - else if (exp10 >= 0) { - string whole = d[..(exp10 + 1)]; - string frac = d[(exp10 + 1)..].TrimEnd('0'); - result = frac.Length > 0 ? $"{whole}.{frac}" : whole; - } - else { - string frac = (new string('0', -exp10 - 1) + d).TrimEnd('0'); - result = $"0.{frac}"; + if (exponential) + result = $"{d[0]}.{d[1..]}"; + else if (exp10 >= 0) + result = $"{d[..(exp10 + 1)]}.{d[(exp10 + 1)..]}"; + else + result = $"0.{new string('0', -exp10 - 1)}{d}"; + + if (!keepZeros) + result = result.TrimEnd('0').TrimEnd('.'); + if (exponential) + result = WithExponent(result, exp10); + + return double.IsNegative(value) ? $"-{result}" : result; + } + + public static string FormatG(double value, int precision = 6) => FormatGeneral(value, precision, false); + + internal static string FormatHex(double value, int precision, bool forcePoint) { + long bits = BitConverter.DoubleToInt64Bits(value); + int exponent = (int)((bits >> 52) & 0x7FF); + ulong mantissa = (ulong)bits & 0xFFFFFFFFFFFFFUL; + int exp2 = exponent - 1023; + if (exponent != 0) + mantissa |= 1UL << 52; + else + exp2 = mantissa == 0 ? 0 : -1022; + + int digits = 13; + if (precision >= 0 && precision < 13) { + int drop = (13 - precision) * 4; + ulong half = 1UL << (drop - 1); + ulong rest = mantissa & ((1UL << drop) - 1); + mantissa >>= drop; + if (rest > half || (rest == half && (mantissa & 1) != 0)) + mantissa++; + digits = precision; } - return negative ? $"-{result}" : result; + string fraction = digits > 0 ? (mantissa & ((1UL << (digits * 4)) - 1)).ToString($"x{digits}") : ""; + if (precision > 13) + fraction += new string('0', precision - 13); +#if !WIN32 + if (precision < 0) + fraction = fraction.TrimEnd('0'); +#endif + + return $"{mantissa >> (digits * 4):x}{(fraction.Length > 0 || forcePoint ? "." : "")}{fraction}p{(exp2 < 0 ? '-' : '+')}{Math.Abs(exp2)}"; } public static int ScanFloats(ReadOnlySpan str, Span values) { @@ -859,40 +1185,37 @@ public static int strcat(scoped Span target, scoped ReadOnlySpan str return len; } // This needs to go in the future, but Dbg currently relies on it. - public static unsafe int sprintf(scoped Span target, ref CFormatReader reader, params ReadOnlySpan args) { - int originalSize = target.Length; + public static int sprintf(scoped Span target, ref CFormatReader reader, params ReadOnlySpan args) { + int written = 0; + while (!reader.Overflowed() && written < target.Length) { + int literal = reader.ReadLiteral(target[written..]); + if (literal > 0) { + written += literal; + continue; + } - Span buffer = stackalloc char[256]; - while (!reader.Overflowed() && !target.IsEmpty) { - // Try reading literal + CFormatReader start = reader; + if (!reader.ReadSpec(out CFormatSpec spec)) + throw new FormatException("Unexpected non-overflow, non-variable, and non-literal condition met..."); -#pragma warning disable CS9080 // Use of variable in this context may expose referenced variables outside of their declaration scope - Span read = buffer[0..reader.ReadLiteral(buffer[..Math.Min(buffer.Length, target.Length)])]; -#pragma warning restore CS9080 // Use of variable in this context may expose referenced variables outside of their declaration scope - if (read.Length > 0) { - read.CopyTo(target); - target = target[read.Length..]; - } - // Try reading a variable? - else if (reader.ReadVariable(out char type, out int idx)) { - if (idx < args.Length) { - int writtenVar = CFormatUtils.WriteFormattedObject(target, type, args[idx]); - target = target[writtenVar..]; - } - else { - // Skip it - target[0] = '%'; - target[1] = type; - target = target[2..]; - } - } - else { - if (!reader.Overflowed()) - throw new FormatException("Unexpected non-overflow, non-variable, and non-literal condition met..."); + CFormatOutput output = new(target[written..], start.ResumeOffset); + CFormatUtils.WriteArgument(ref output, in spec, reader.GetText(in spec), args); + if (output.Total - start.ResumeOffset <= target.Length - written) { + written += output.Written; + reader.ResumeOffset = 0; + continue; } + + reader = start; + if (written > 0 && start.ResumeOffset == 0) + break; + + reader.ResumeOffset += output.Written; + written += output.Written; + break; } - return originalSize - target.Length; // Should return the delta length + return written; } public static PrintF sprintf(Span target, ReadOnlySpan format) => new(target, format); public static void binarytohex(ReadOnlySpan input, Span output) { From 9c0b471f9657dc73583663bcf5a0320db1a09ad1 Mon Sep 17 00:00:00 2001 From: Space V <40030799+spacevx@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:24:52 +0100 Subject: [PATCH 2/3] Make sscanf follow C --- Source.Common.Tests/CFormattingTests.cs | 32 +++ Source.Common/CFormatting.cs | 254 +++++++++++++++++------- 2 files changed, 214 insertions(+), 72 deletions(-) diff --git a/Source.Common.Tests/CFormattingTests.cs b/Source.Common.Tests/CFormattingTests.cs index 40dca1e7..85fbfd13 100644 --- a/Source.Common.Tests/CFormattingTests.cs +++ b/Source.Common.Tests/CFormattingTests.cs @@ -131,6 +131,38 @@ public void FluentPrintF() { Assert.Equal("4294967298", CFormatting.sprintf(buffer, "%d").D(4294967298L).ToSpan()); } + [Fact] + public void ScanFReadsNumbers() { + CultureInfo.CurrentCulture = new CultureInfo("fr-FR"); + Assert.Equal(3, new ScanF("[1.5 2.5 3.5]", "[%f %f %f]").Read(out float x).Read(out float y).Read(out float z).ReadArguments); + Assert.Equal((1.5f, 2.5f, 3.5f), (x, y, z)); + Assert.Equal(0, new ScanF("1 2 3", "[%f %f %f]").Read(out x).Read(out y).Read(out z).ReadArguments); + Assert.Equal(2, new ScanF("640x480", "%i x %i").Read(out int width).Read(out int height).ReadArguments); + Assert.Equal((640, 480), (width, height)); + Assert.Equal(2, new ScanF("ff 0x10", "%x %x").Read(out int first).Read(out int second).ReadArguments); + Assert.Equal((255, 16), (first, second)); + Assert.Equal(1, new ScanF("-1.5e+2x", "%f").Read(out x).ReadArguments); + Assert.Equal(-150f, x); + } + + [Fact] + public void ScanFLeavesUnreadValuesAlone() { + int red = 1, green = 2, blue = 3, alpha = 255; + Assert.Equal(3, new ScanF("10 20 30", "%d %d %d %d").Read(out red).Read(out green).Read(out blue).Read(out alpha).ReadArguments); + Assert.Equal((10, 20, 30, 255), (red, green, blue, alpha)); + Assert.Equal(-1, new ScanF("", "%d").Read(out red).ReadArguments); + Assert.Equal(0, new ScanF("abc", "%d").Read(out red).ReadArguments); + Assert.Equal(10, red); + } + + [Fact] + public void ScanFKeepsItsStateAcrossCalls() { + ScanF scan = new("1 2 3 4", "%d %d %d %d"); + scan.Read(out int a).Read(out int b).Read(out int c).Read(out int d); + Assert.Equal(4, scan.ReadArguments); + Assert.Equal((1, 2, 3, 4), (a, b, c, d)); + } + [Fact] public void FluentPrintFClampsToTheBuffer() { Span buffer = stackalloc char[6]; diff --git a/Source.Common/CFormatting.cs b/Source.Common/CFormatting.cs index ec3c8205..cb88d89c 100644 --- a/Source.Common/CFormatting.cs +++ b/Source.Common/CFormatting.cs @@ -6,6 +6,7 @@ This file is a bit of a mess. It was an attempt at implementing a C# version of for their arguments instead, along with not trying to reinvent the wheel and read actual C stdlib implementations. */ +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Numerics; using System.Runtime.CompilerServices; @@ -181,9 +182,12 @@ public ref struct ScanF { public CFormatReader Format; ReadOnlySpan input; - int readArguments = 0; - public readonly int ReadArguments => readArguments - invalidArguments; - public readonly bool ReadAny => readArguments > 0; + int assigned; + bool failed; + bool inputFailure; + + public readonly int ReadArguments => assigned == 0 && inputFailure ? -1 : assigned; + public readonly bool ReadAny => assigned > 0; public ScanF(ReadOnlySpan input, ReadOnlySpan format) { Format = new(format); @@ -191,92 +195,198 @@ public ScanF(ReadOnlySpan input, ReadOnlySpan format) { } public readonly bool Overflowed => Format.Overflowed(); - // NOTE: Only unsafe because C# can't tell we're never going to lose track of the stack allocated buffer target - // (which is needed to read out a literal) - private unsafe bool TryReadVariable(Span incoming, out char type, out int len) { - type = '\0'; - len = 0; - if (Format.Overflowed() || input.Length <= 0) + static bool IsSpace(char c) => c is ' ' or '\t' or '\n' or '\v' or '\f' or '\r'; + static int DigitValue(char c) => c is >= '0' and <= '9' ? c - '0' : c is >= 'a' and <= 'f' ? c - 'a' + 10 : c is >= 'A' and <= 'F' ? c - 'A' + 10 : 99; + + void SkipSpaces() { + while (!input.IsEmpty && IsSpace(input[0])) + input = input[1..]; + } + + bool Fail(bool atEnd) { + inputFailure = atEnd; + failed = true; + return false; + } + + bool NextConversion(out CFormatSpec spec) { + spec = default; + if (failed) return false; - // Read until a variable or overflow - Span literalBufferTarget = stackalloc char[64]; - while (!Format.Overflowed() && input.Length > 0) { -#pragma warning disable CS9080 // Use of variable in this context may expose referenced variables outside of their declaration scope - int read = Format.ReadLiteral(literalBufferTarget); -#pragma warning restore CS9080 // Use of variable in this context may expose referenced variables outside of their declaration scope - if (read > 0) { - input = input[read..]; // slice so we're aligned - continue; + Span literal = stackalloc char[64]; + while (true) { + for (int read = Format.ReadLiteral(literal); read > 0; read = Format.ReadLiteral(literal)) { + for (int i = 0; i < read; i++) { + if (IsSpace(literal[i])) { + SkipSpaces(); + continue; + } + + if (input.IsEmpty || input[0] != literal[i]) + return Fail(input.IsEmpty); + input = input[1..]; + } } - break; + if (!Format.ReadSpec(out spec)) + return Fail(false); + if (spec.WidthArg < 0) + return true; + + if (CFormatUtils.IsFloatConversion(spec.Type) ? !ScanFloat(in spec, out _) : !ScanInteger(in spec, out _)) + return false; } + } - if (Format.ReadVariable(out type, out int variableIdx)) { - readArguments = variableIdx + 1; - int writePtr = 0; - bool hasWarned = false; - while (input.Length > 0) { - char c = input[0]; - if (c == ' ') - break; - input = input[1..]; - if (writePtr < incoming.Length) // don't overflow but continue to read to not break further arguments - incoming[writePtr++] = c; - else if (!hasWarned) { - Warning($"Overflowed scanf (max: {incoming.Length}). Consider increasing max here! Truncated argument will be provided.\n"); - hasWarned = true; - } + ReadOnlySpan Window(in CFormatSpec spec) { + SkipSpaces(); + return spec.Width > 0 && spec.Width < input.Length ? input[..spec.Width] : input; + } + + bool Consume(bool valid, int length) { + if (!valid) + return Fail(length >= input.Length); + + input = input[length..]; + return true; + } + + bool ScanInteger(in CFormatSpec spec, out long value) { + ReadOnlySpan text = Window(in spec); + int i = 0; + bool negative = false; + if (i < text.Length && text[i] is '+' or '-') + negative = text[i++] == '-'; + + int radix = spec.Type switch { + 'x' or 'X' => 16, + 'o' or 'O' => 8, + 'i' => 0, + _ => 10 + }; + + if (radix is 0 or 16 && i + 1 < text.Length && text[i] == '0' && text[i + 1] is 'x' or 'X') { + radix = 16; + i += 2; + } + else if (radix == 0) + radix = i < text.Length && text[i] == '0' ? 8 : 10; + + int start = i; + ulong number = 0; + for (; i < text.Length && DigitValue(text[i]) < radix; i++) + number = unchecked(number * (ulong)radix + (ulong)DigitValue(text[i])); + + value = unchecked(negative ? -(long)number : (long)number); + return Consume(i > start, i); + } + + bool ScanFloat(in CFormatSpec spec, out float value) { + ReadOnlySpan text = Window(in spec); + int i = 0; + bool negative = false; + if (i < text.Length && text[i] is '+' or '-') + negative = text[i++] == '-'; + + bool valid; + value = 0; + if (text[i..].StartsWith("infinity", StringComparison.OrdinalIgnoreCase) || text[i..].StartsWith("inf", StringComparison.OrdinalIgnoreCase)) { + i += text[i..].StartsWith("infinity", StringComparison.OrdinalIgnoreCase) ? 8 : 3; + value = float.PositiveInfinity; + valid = true; + } + else if (text[i..].StartsWith("nan", StringComparison.OrdinalIgnoreCase)) { + i += 3; + value = float.NaN; + valid = true; + } + else if (i + 1 < text.Length && text[i] == '0' && text[i + 1] is 'x' or 'X') { + i += 2; + double mantissa = 0; + int digits = 0; + int exponent = 0; + for (; i < text.Length && DigitValue(text[i]) < 16; i++, digits++) + mantissa = mantissa * 16 + DigitValue(text[i]); + if (i < text.Length && text[i] == '.') { + for (i++; i < text.Length && DigitValue(text[i]) < 16; i++, digits++, exponent -= 4) + mantissa = mantissa * 16 + DigitValue(text[i]); } - len = writePtr; - return true; + + valid = digits > 0; + if (valid && i < text.Length && text[i] is 'p' or 'P') { + bool negativeExponent = ++i < text.Length && text[i] == '-'; + if (i < text.Length && text[i] is '+' or '-') + i++; + int exponentDigits = i; + int binaryExponent = 0; + for (; i < text.Length && char.IsAsciiDigit(text[i]); i++) + binaryExponent = Math.Min(binaryExponent * 10 + (text[i] - '0'), 100000); + valid = i > exponentDigits; + exponent += negativeExponent ? -binaryExponent : binaryExponent; + } + + value = (float)Math.ScaleB(mantissa, exponent); } + else { + int start = i; + int digits = 0; + for (; i < text.Length && char.IsAsciiDigit(text[i]); i++) + digits++; + if (i < text.Length && text[i] == '.') { + for (i++; i < text.Length && char.IsAsciiDigit(text[i]); i++) + digits++; + } - return false; + valid = digits > 0; + if (valid && i < text.Length && text[i] is 'e' or 'E') { + if (++i < text.Length && text[i] is '+' or '-') + i++; + int exponentDigits = i; + while (i < text.Length && char.IsAsciiDigit(text[i])) + i++; + valid = i > exponentDigits; + } + + if (valid) + value = float.Parse(text[start..i], NumberStyles.Float, CultureInfo.InvariantCulture); + } + + if (negative) + value = -value; + return Consume(valid, i); } - public const int DEFAULT_SCANF_MAX = 256; - public unsafe ScanF Read(out int i, int max = DEFAULT_SCANF_MAX) { - Span incoming = stackalloc char[max]; - i = default; - int iAttempt; -#pragma warning disable CS9080 // Use of variable in this context may expose referenced variables outside of their declaration scope - if (TryReadVariable(incoming, out char type, out int len)) -#pragma warning restore CS9080 // Use of variable in this context may expose referenced variables outside of their declaration scope - switch (type) { - case 'd': - case (char)VariableType.SignedDecimalInteger: - i = int.TryParse(incoming[..len], out iAttempt) ? iAttempt : default; - break; - case (char)VariableType.UnsignedHexadecimalInteger: - i = int.TryParse(incoming[..len], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out iAttempt) ? iAttempt : default; - break; - default: throw new NotImplementedException(); + [UnscopedRef] + public ref ScanF Read(out int i) { + Unsafe.SkipInit(out i); + if (NextConversion(out CFormatSpec spec)) { + if (!CFormatUtils.IsIntegerConversion(spec.Type)) + throw new NotImplementedException(); + + if (ScanInteger(in spec, out long value)) { + i = unchecked((int)value); + assigned++; } + } - return this; + return ref this; } - int invalidArguments = 0; - public unsafe ScanF Read(out float i, int max = DEFAULT_SCANF_MAX) { - Span incoming = stackalloc char[max]; - i = default; - float iAttempt; -#pragma warning disable CS9080 // Use of variable in this context may expose referenced variables outside of their declaration scope - if (TryReadVariable(incoming, out char type, out int len)) -#pragma warning restore CS9080 // Use of variable in this context may expose referenced variables outside of their declaration scope - switch (type) { - case (char)VariableType.DecimalFloatingPoint: - if (float.TryParse(incoming[..len], out iAttempt)) - i = iAttempt; - else - invalidArguments++; - break; - default: throw new NotImplementedException(); + [UnscopedRef] + public ref ScanF Read(out float i) { + Unsafe.SkipInit(out i); + if (NextConversion(out CFormatSpec spec)) { + if (!CFormatUtils.IsFloatConversion(spec.Type)) + throw new NotImplementedException(); + + if (ScanFloat(in spec, out float value)) { + i = value; + assigned++; } + } - return this; + return ref this; } } From f983d051c70c9d2a7466335a4270287498a7a7d3 Mon Sep 17 00:00:00 2001 From: Space V <40030799+spacevx@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:50:16 +0100 Subject: [PATCH 3/3] Address review on C formatting --- Game.Shared/Variant_t.cs | 6 ++-- Source.Common.Tests/CFormattingTests.cs | 38 ++++++++++++++++++---- Source.Common/CFormatting.cs | 16 +++++++-- Source.GUI.Controls/AnimationController.cs | 2 +- Source.GUI.Controls/ImagePanel.cs | 6 ++-- Source.GUI/Border.cs | 2 +- 6 files changed, 53 insertions(+), 17 deletions(-) diff --git a/Game.Shared/Variant_t.cs b/Game.Shared/Variant_t.cs index 8a4b5cd6..ae78e4a6 100644 --- a/Game.Shared/Variant_t.cs +++ b/Game.Shared/Variant_t.cs @@ -205,8 +205,8 @@ public bool Convert(FieldType newType) { case FT.Vector: Vector3 tmpVec = vec3_origin; - if (0 == new ScanF(StrVal, "[%f %f %f]").Read(out tmpVec.X).Read(out tmpVec.Y).Read(out tmpVec.Z).ReadArguments) - new ScanF(StrVal, "%f %f %f").Read(out tmpVec.X).Read(out tmpVec.Y).Read(out tmpVec.Z); + if (0 == new ScanF(StrVal, "[%f %f %f]").ReadOrKeep(ref tmpVec.X).ReadOrKeep(ref tmpVec.Y).ReadOrKeep(ref tmpVec.Z).ReadArguments) + new ScanF(StrVal, "%f %f %f").ReadOrKeep(ref tmpVec.X).ReadOrKeep(ref tmpVec.Y).ReadOrKeep(ref tmpVec.Z); SetVector3D(tmpVec); return true; @@ -216,7 +216,7 @@ public bool Convert(FieldType newType) { int blue = 0; int alpha = 255; - new ScanF(StrVal, "%d %d %d %d").Read(out red).Read(out green).Read(out blue).Read(out alpha); + new ScanF(StrVal, "%d %d %d %d").ReadOrKeep(ref red).ReadOrKeep(ref green).ReadOrKeep(ref blue).ReadOrKeep(ref alpha); SetColor32((byte)red, (byte)green, (byte)blue, (byte)alpha); return true; diff --git a/Source.Common.Tests/CFormattingTests.cs b/Source.Common.Tests/CFormattingTests.cs index 85fbfd13..488fe67f 100644 --- a/Source.Common.Tests/CFormattingTests.cs +++ b/Source.Common.Tests/CFormattingTests.cs @@ -5,7 +5,6 @@ namespace Source.Common.Tests; public class CFormattingTests { static string Format(string format, params object?[] args) { - CultureInfo.CurrentCulture = new CultureInfo("fr-FR"); CFormatReader reader = new(format); Span piece = stackalloc char[16]; string result = ""; @@ -118,7 +117,6 @@ public void LongOutputSpansPieces() { [Fact] public void FluentPrintF() { - CultureInfo.CurrentCulture = new CultureInfo("fr-FR"); Span buffer = stackalloc char[64]; Assert.Equal("5:07", CFormatting.sprintf(buffer, "%d:%.2d").D(5).D(7).ToSpan()); Assert.Equal("1.500 0.5", CFormatting.sprintf(buffer, "%.3f %g").F(1.5f).G(0.5).ToSpan()); @@ -133,7 +131,6 @@ public void FluentPrintF() { [Fact] public void ScanFReadsNumbers() { - CultureInfo.CurrentCulture = new CultureInfo("fr-FR"); Assert.Equal(3, new ScanF("[1.5 2.5 3.5]", "[%f %f %f]").Read(out float x).Read(out float y).Read(out float z).ReadArguments); Assert.Equal((1.5f, 2.5f, 3.5f), (x, y, z)); Assert.Equal(0, new ScanF("1 2 3", "[%f %f %f]").Read(out x).Read(out y).Read(out z).ReadArguments); @@ -146,13 +143,24 @@ public void ScanFReadsNumbers() { } [Fact] - public void ScanFLeavesUnreadValuesAlone() { + public void ScanFReadOrKeepLeavesUnreadValuesAlone() { int red = 1, green = 2, blue = 3, alpha = 255; - Assert.Equal(3, new ScanF("10 20 30", "%d %d %d %d").Read(out red).Read(out green).Read(out blue).Read(out alpha).ReadArguments); + Assert.Equal(3, new ScanF("10 20 30", "%d %d %d %d").ReadOrKeep(ref red).ReadOrKeep(ref green).ReadOrKeep(ref blue).ReadOrKeep(ref alpha).ReadArguments); Assert.Equal((10, 20, 30, 255), (red, green, blue, alpha)); - Assert.Equal(-1, new ScanF("", "%d").Read(out red).ReadArguments); - Assert.Equal(0, new ScanF("abc", "%d").Read(out red).ReadArguments); + Assert.Equal(-1, new ScanF("", "%d").ReadOrKeep(ref red).ReadArguments); + Assert.Equal(0, new ScanF("abc", "%d").ReadOrKeep(ref red).ReadArguments); Assert.Equal(10, red); + float scale = 0.5f; + Assert.Equal(0, new ScanF("x", "%f").ReadOrKeep(ref scale).ReadArguments); + Assert.Equal(0.5f, scale); + } + + [Fact] + public void ScanFReadZeroesUnreadValues() { + Assert.Equal(3, new ScanF("10 20 30", "%d %d %d %d").Read(out int red).Read(out int green).Read(out int blue).Read(out int alpha).ReadArguments); + Assert.Equal((10, 20, 30, 0), (red, green, blue, alpha)); + Assert.Equal(0, new ScanF("abc", "%f").Read(out float scale).ReadArguments); + Assert.Equal(0f, scale); } [Fact] @@ -163,6 +171,22 @@ public void ScanFKeepsItsStateAcrossCalls() { Assert.Equal((1, 2, 3, 4), (a, b, c, d)); } + [Fact] + public void IgnoresTheCurrentCulture() { + CultureInfo previous = CultureInfo.CurrentCulture; + try { + CultureInfo.CurrentCulture = new CultureInfo("fr-FR"); + Assert.Equal("1.500000 2.5 1.0e+00 3.14", Format("%f %g %.1e %s", 1.5, 2.5f, 1.0, 3.14)); + Span buffer = stackalloc char[16]; + Assert.Equal("1.500 0.5", CFormatting.sprintf(buffer, "%.3f %g").F(1.5f).G(0.5).ToSpan()); + Assert.Equal(2, new ScanF("1.5 2.5", "%f %f").Read(out float x).Read(out float y).ReadArguments); + Assert.Equal((1.5f, 2.5f), (x, y)); + } + finally { + CultureInfo.CurrentCulture = previous; + } + } + [Fact] public void FluentPrintFClampsToTheBuffer() { Span buffer = stackalloc char[6]; diff --git a/Source.Common/CFormatting.cs b/Source.Common/CFormatting.cs index cb88d89c..afbac258 100644 --- a/Source.Common/CFormatting.cs +++ b/Source.Common/CFormatting.cs @@ -359,7 +359,18 @@ bool ScanFloat(in CFormatSpec spec, out float value) { [UnscopedRef] public ref ScanF Read(out int i) { - Unsafe.SkipInit(out i); + i = 0; + return ref ReadOrKeep(ref i); + } + + [UnscopedRef] + public ref ScanF Read(out float i) { + i = 0; + return ref ReadOrKeep(ref i); + } + + [UnscopedRef] + public ref ScanF ReadOrKeep(ref int i) { if (NextConversion(out CFormatSpec spec)) { if (!CFormatUtils.IsIntegerConversion(spec.Type)) throw new NotImplementedException(); @@ -374,8 +385,7 @@ public ref ScanF Read(out int i) { } [UnscopedRef] - public ref ScanF Read(out float i) { - Unsafe.SkipInit(out i); + public ref ScanF ReadOrKeep(ref float i) { if (NextConversion(out CFormatSpec spec)) { if (!CFormatUtils.IsFloatConversion(spec.Type)) throw new NotImplementedException(); diff --git a/Source.GUI.Controls/AnimationController.cs b/Source.GUI.Controls/AnimationController.cs index 18ed220e..9e7b83bf 100644 --- a/Source.GUI.Controls/AnimationController.cs +++ b/Source.GUI.Controls/AnimationController.cs @@ -900,7 +900,7 @@ private bool _ParseScriptFile(ReadOnlySpan mem, Span token) { SetupPosition(ref cmdAnimate, ref cmdAnimate.Target.A, token, screenTall); } else { - var scanf = new ScanF(token, "%f %f %f %f").Read(out cmdAnimate.Target.A).Read(out cmdAnimate.Target.B).Read(out cmdAnimate.Target.C).Read(out cmdAnimate.Target.D); + var scanf = new ScanF(token, "%f %f %f %f").ReadOrKeep(ref cmdAnimate.Target.A).ReadOrKeep(ref cmdAnimate.Target.B).ReadOrKeep(ref cmdAnimate.Target.C).ReadOrKeep(ref cmdAnimate.Target.D); if (0 == scanf.ReadArguments) { Color default_invisible_black = new(0, 0, 0, 0); Color col = scheme.GetColor(token, default_invisible_black); diff --git a/Source.GUI.Controls/ImagePanel.cs b/Source.GUI.Controls/ImagePanel.cs index 9fb55097..76497165 100644 --- a/Source.GUI.Controls/ImagePanel.cs +++ b/Source.GUI.Controls/ImagePanel.cs @@ -173,8 +173,9 @@ public override void ApplySettings(KeyValues resourceData) { ReadOnlySpan fillColor = resourceData.GetString("fillcolor", ""); if (fillColor.Length > 0) { + int r = 0, g = 0, b = 0, a = 255; FillColorName = new(fillColor); - if (new ScanF(fillColor, "%d %d %d %d").Read(out int r).Read(out int g).Read(out int b).Read(out int a).ReadArguments >= 3) + if (new ScanF(fillColor, "%d %d %d %d").ReadOrKeep(ref r).ReadOrKeep(ref g).ReadOrKeep(ref b).ReadOrKeep(ref a).ReadArguments >= 3) FillColor = new(r, g, b, a); else FillColor = GetScheme()!.GetColor(fillColor, new(0, 0, 0, 0)); @@ -182,8 +183,9 @@ public override void ApplySettings(KeyValues resourceData) { ReadOnlySpan drawColor = resourceData.GetString("drawcolor", ""); if (drawColor.Length > 0) { + int r = 255, g = 255, b = 255, a = 255; DrawColorName = new(drawColor); - if (new ScanF(drawColor, "%d %d %d %d").Read(out int r).Read(out int g).Read(out int b).Read(out int a).ReadArguments >= 3) + if (new ScanF(drawColor, "%d %d %d %d").ReadOrKeep(ref r).ReadOrKeep(ref g).ReadOrKeep(ref b).ReadOrKeep(ref a).ReadArguments >= 3) DrawColor = new(r, g, b, a); else DrawColor = GetScheme()!.GetColor(drawColor, new(255, 255, 255, 255)); diff --git a/Source.GUI/Border.cs b/Source.GUI/Border.cs index 91a3fc93..d61d8cfb 100644 --- a/Source.GUI/Border.cs +++ b/Source.GUI/Border.cs @@ -67,7 +67,7 @@ public virtual void ApplySchemeSettings(IScheme? scheme, KeyValues inResourceDat ReadOnlySpan insetString = inResourceData.GetString("inset", "0 0 0 0"); GetInset(out int left, out int top, out int right, out int bottom); - new ScanF(insetString, "%d %d %d %d").Read(out left).Read(out top).Read(out right).Read(out bottom); + new ScanF(insetString, "%d %d %d %d").ReadOrKeep(ref left).ReadOrKeep(ref top).ReadOrKeep(ref right).ReadOrKeep(ref bottom); SetInset(left, top, right, bottom); // get the border information from the scheme