diff --git a/Game.Lua/LuaInterfaceImpl.cs b/Game.Lua/LuaInterfaceImpl.cs index 4ee7b79d0..b14bb0bfc 100644 --- a/Game.Lua/LuaInterfaceImpl.cs +++ b/Game.Lua/LuaInterfaceImpl.cs @@ -22,7 +22,7 @@ public unsafe class LuaInterfaceImpl : ILuaInterface delegate int NativeCFunction(nint L); [StructLayout(LayoutKind.Sequential)] - struct UserData + internal struct UserData { public nint Data; public byte Type; @@ -420,6 +420,8 @@ public int PCall(int args, int results, int errorFunc) { public bool Next(int stackPos) => Op(SN_NEXT, stackPos) != 0; + public bool TableToJSON(int stackPos, bool pretty, [NotNullWhen(false)] out string? error) => LuaJson.TableToJSON(this, state, stackPos, pretty, out error); + public nint NewUserdata(uint size) => lua_newuserdata(state, size); [DoesNotReturn] diff --git a/Game.Lua/LuaJIT.cs b/Game.Lua/LuaJIT.cs index e334c8cba..701436eaa 100644 --- a/Game.Lua/LuaJIT.cs +++ b/Game.Lua/LuaJIT.cs @@ -59,7 +59,7 @@ internal static unsafe partial class LuaApi [LibraryImport(Lib)] public static partial void lua_setstatef(nint L, delegate* unmanaged f, nint ud); [LibraryImport(Lib), SuppressGCTransition] public static partial int lua_gettop(nint L); - [LibraryImport(Lib)] public static partial void lua_settop(nint L, int idx); + [LibraryImport(Lib), SuppressGCTransition] public static partial void lua_settop(nint L, int idx); [LibraryImport(Lib)] public static partial void lua_pushvalue(nint L, int idx); [LibraryImport(Lib)] public static partial void lua_remove(nint L, int idx); [LibraryImport(Lib)] public static partial void lua_insert(nint L, int idx); @@ -75,9 +75,10 @@ internal static unsafe partial class LuaApi [LibraryImport(Lib), SuppressGCTransition] public static partial int lua_isstring(nint L, int idx); [LibraryImport(Lib), SuppressGCTransition] public static partial int lua_rawequal(nint L, int idx1, int idx2); [LibraryImport(Lib)] public static partial byte* lua_tolstring(nint L, int idx, nuint* len); + [LibraryImport(Lib), SuppressGCTransition] public static partial nint lua_topointer(nint L, int idx); [LibraryImport(Lib)] public static partial byte* lua_typename(nint L, int tp, int idx); - [LibraryImport(Lib)] public static partial void lua_pushnil(nint L); + [LibraryImport(Lib), SuppressGCTransition] public static partial void lua_pushnil(nint L); [LibraryImport(Lib)] public static partial void lua_pushnumber(nint L, double n); [LibraryImport(Lib)] public static partial void lua_pushlstring(nint L, byte* s, nuint len); [LibraryImport(Lib)] public static partial void lua_pushboolean(nint L, int b); @@ -86,10 +87,10 @@ internal static unsafe partial class LuaApi [LibraryImport(Lib)] public static partial void lua_createtable(nint L, int narr, int nrec); [LibraryImport(Lib)] public static partial nint lua_newuserdata(nint L, nuint sz); - [LibraryImport(Lib)] public static partial int lua_getmetatable(nint L, int idx); + [LibraryImport(Lib), SuppressGCTransition] public static partial int lua_getmetatable(nint L, int idx); [LibraryImport(Lib)] public static partial int lua_setmetatable(nint L, int idx); [LibraryImport(Lib)] public static partial void lua_rawget(nint L, int idx); - [LibraryImport(Lib)] public static partial void lua_rawgeti(nint L, int idx, int n); + [LibraryImport(Lib), SuppressGCTransition] public static partial void lua_rawgeti(nint L, int idx, int n); [LibraryImport(Lib)] public static partial void lua_rawseti(nint L, int idx, int n); [LibraryImport(Lib)] public static partial int lua_pcall(nint L, int nargs, int nresults, int errfunc); @@ -106,6 +107,10 @@ internal static unsafe partial class LuaApi [LibraryImport(Lib)] public static partial byte* lua_getlocal(nint L, lua_Debug* ar, int n); [LibraryImport(Lib)] public static partial byte* lua_getupvalue(nint L, int funcindex, int n); + // note: no GC transition, strings only and tables nothing writes to meanwhile + [LibraryImport(Lib, EntryPoint = "lua_tolstring"), SuppressGCTransition] public static partial byte* lua_tolstring_fast(nint L, int idx, nuint* len); + [LibraryImport(Lib, EntryPoint = "lua_next"), SuppressGCTransition] public static partial int lua_next_fast(nint L, int idx); + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void lua_pop(nint L, int n) => lua_settop(L, -n - 1); } diff --git a/Game.Lua/LuaJson.cs b/Game.Lua/LuaJson.cs new file mode 100644 index 000000000..484fa31c8 --- /dev/null +++ b/Game.Lua/LuaJson.cs @@ -0,0 +1,452 @@ +using Source.Common; +using Source.Common.GarrysMod.Lua; + +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Text; + +using static Game.Lua.LuaApi; + +namespace Game.Lua; + +// note: implementation of https://github.com/Facepunch/garrysmod-requests/issues/2822 +internal static unsafe class LuaJson +{ + enum Walk : byte + { + Start, + ArrayNext, + ArrayIndex, + ObjectNext + } + + struct Frame + { + public nint Table; + public int Index; + public int Position; + public int Total; + public int Open; + public int Count; + public Walk Mode; + public bool InArray; + public bool Named; + public bool HasMetaTable; + } + + const int MAX_DEPTH = 3001; + const int VISITED_THRESHOLD = 64; + const string CyclicReference = "attempt to serialize structure with cyclic reference"; + const string DepthTooHigh = "JSON Depth is too high! > 3000"; + + public static bool TableToJSON(LuaInterfaceImpl lua, nint L, int index, bool pretty, [NotNullWhen(false)] out string? error) { + int top = lua_gettop(L); + RapidJson.Writer writer = new(pretty); + try { + lua_pushvalue(L, index); + error = WalkTable(lua, L, top + 1, ref writer); + lua_settop(L, top); + if (error != null) + return false; + + fixed (byte* json = writer.WrittenSpan) + lua_pushlstring(L, json, (nuint)writer.Length); + return true; + } + finally { + writer.Dispose(); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static bool Next(LuaInterfaceImpl lua, nint L, int index, bool protect) => protect ? lua.Next(index) : lua_next_fast(L, index) != 0; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static bool IsIndex(nint L, int index, int expected) => lua_type(L, index) == TNUMBER && lua_tonumber(L, index) == expected; + + static bool HasMetaTable(nint L, int index) { + if (lua_getmetatable(L, index) == 0) + return false; + + lua_settop(L, -2); + return true; + } + + static bool IsVisited(ReadOnlySpan frames, int top, HashSet? visited, nint table) { + if (visited != null) + return visited.Contains(table); + + for (int i = 0; i <= top; i++) { + if (frames[i].Table == table) + return true; + } + + return false; + } + + static int FormatNumberKey(double key, Span target) { + if (key >= int.MinValue && key <= int.MaxValue && key == (int)key) { + ((int)key).TryFormat(target, out int written, default, CultureInfo.InvariantCulture); + return written; + } + + if (double.IsInfinity(key)) + return Encoding.ASCII.GetBytes(key > 0 ? "Infinity" : "-inf", target); + + return Encoding.ASCII.GetBytes(CFormatting.FormatG(key, 14), target); + } + + static float* GetVectorOrAngle(nint L, int index, out bool angle) { + angle = false; + LuaInterfaceImpl.UserData* ud = (LuaInterfaceImpl.UserData*)lua_touserdata(L, index); + if (ud == null || ud->Data == 0) + return null; + + if (ud->Type == (byte)LuaType.Angle) + angle = true; + else if (ud->Type != (byte)LuaType.Vector) + return null; + + return (float*)ud->Data; + } + + static bool HasNamedChild(LuaInterfaceImpl lua, nint L, int table, bool protect) { + int top = lua_gettop(L); + lua_pushnil(L); + while (Next(lua, L, table, protect)) { + bool named; + switch (lua_type(L, top + 1)) { + case TSTRING: + nuint length; + lua_tolstring_fast(L, top + 1, &length); + named = length != 0; + break; + case TNUMBER: + case TBOOLEAN: + named = true; + break; + default: + named = false; + break; + } + + if (named) { + switch (lua_type(L, top + 2)) { + case TBOOLEAN: + case TNUMBER: + case TSTRING: + case TTABLE: + break; + case TUSERDATA: + named = GetVectorOrAngle(L, top + 2, out _) != null; + break; + default: + named = false; + break; + } + } + + if (named) { + lua_settop(L, top); + return true; + } + + lua_settop(L, top + 1); + } + + return false; + } + + static void Decide(LuaInterfaceImpl lua, nint L, ref Frame frame, ref bool protect) { + int count = 0; + lua_pushnil(L); + while (Next(lua, L, frame.Index, protect)) { + count++; + lua_settop(L, frame.Index + 1); + } + + int run = 0; + while (true) { + if (frame.HasMetaTable) { + protect = true; + lua.PushLong(run + 1); + lua.GetTable(frame.Index); + } + else + lua_rawgeti(L, frame.Index, run + 1); + + bool nil = lua_type(L, frame.Index + 1) == TNIL; + lua_settop(L, frame.Index); + if (nil || ++run > count) + break; + } + + if (run == count) { + frame.Mode = Walk.ArrayIndex; + frame.Position = 0; + frame.Total = count; + frame.InArray = true; + } + else { + frame.Mode = Walk.ObjectNext; + frame.InArray = false; + lua_pushnil(L); + } + } + + static void Restart(LuaInterfaceImpl lua, nint L, ref Frame frame, ref RapidJson.Writer writer, ref bool protect) { + bool numbered = lua_type(L, frame.Index + 1) == TNUMBER; + lua_settop(L, frame.Index); + writer.Length = frame.Open + 1; + frame.Count = 0; + if (numbered) + Decide(lua, L, ref frame, ref protect); + else { + frame.Mode = Walk.ObjectNext; + frame.InArray = false; + lua_pushnil(L); + } + } + + static string? WalkTable(LuaInterfaceImpl lua, nint L, int root, ref RapidJson.Writer writer) { + Span frames = stackalloc Frame[32]; + Span scratch = stackalloc byte[192]; + HashSet? visited = null; + bool protect = false; + + int top = 0; + frames[0] = new() { Table = lua_topointer(L, root), Index = root, HasMetaTable = HasMetaTable(L, root) }; + writer.Put((byte)'['); + + while (top >= 0) { + ref Frame frame = ref frames[top]; + int level = top + 1; + bool pair = false; + + if (frame.Mode == Walk.Start) { + if (frame.HasMetaTable) { + Decide(lua, L, ref frame, ref protect); + continue; + } + + lua_pushnil(L); + if (!Next(lua, L, frame.Index, protect)) + frame.Mode = Walk.ArrayIndex; + else if (IsIndex(L, frame.Index + 1, 1)) { + frame.Mode = Walk.ArrayNext; + frame.Position = 1; + frame.InArray = true; + pair = true; + } + else { + lua_rawgeti(L, frame.Index, 1); + if (lua_type(L, frame.Index + 3) != TNIL) { + lua_settop(L, frame.Index); + Decide(lua, L, ref frame, ref protect); + continue; + } + + lua_settop(L, frame.Index + 2); + frame.Mode = Walk.ObjectNext; + pair = true; + } + } + + int value; + switch (frame.Mode) { + case Walk.ArrayNext: + if (!pair) { + if (!Next(lua, L, frame.Index, protect)) { + value = 0; + break; + } + + if (!IsIndex(L, frame.Index + 1, frame.Position + 1)) { + Restart(lua, L, ref frame, ref writer, ref protect); + continue; + } + + frame.Position++; + } + + value = frame.Index + 2; + break; + case Walk.ArrayIndex: + if (frame.Position == frame.Total) { + value = 0; + break; + } + + lua_rawgeti(L, frame.Index, ++frame.Position); + value = frame.Index + 1; + break; + default: + value = pair || Next(lua, L, frame.Index, protect) ? frame.Index + 2 : 0; + break; + } + + if (value == 0) { + bool array = frame.InArray || frame.Count == 0; + if (!array) + writer[frame.Open] = (byte)'{'; + writer.End(array ? (byte)']' : (byte)'}', frame.Count, top); + visited?.Remove(frame.Table); + if (top > 0) + lua_settop(L, frame.Index - 1); + top--; + continue; + } + + int type = lua_type(L, value); + if (type == TTABLE && frame.Mode == Walk.ArrayNext) { + int count = frame.Position; + bool sequential = true; + lua_settop(L, frame.Index + 1); + while (Next(lua, L, frame.Index, protect)) { + if (!IsIndex(L, frame.Index + 1, count + 1)) { + sequential = false; + break; + } + + count++; + lua_settop(L, frame.Index + 1); + } + + if (!sequential) { + Restart(lua, L, ref frame, ref writer, ref protect); + continue; + } + + lua_settop(L, frame.Index); + frame.Mode = Walk.ArrayIndex; + frame.Total = count; + frame.Position--; + continue; + } + + scoped ReadOnlySpan name = default; + if (frame.Mode == Walk.ObjectNext) { + int key = frame.Index + 1; + switch (lua_type(L, key)) { + case TSTRING: + nuint length; + byte* text = lua_tolstring_fast(L, key, &length); + name = new(text, (int)length); + break; + case TNUMBER: + name = scratch[..FormatNumberKey(lua_tonumber(L, key), scratch)]; + break; + case TBOOLEAN: + name = lua_toboolean(L, key) != 0 ? "true"u8 : "false"u8; + break; + default: + lua_settop(L, key); + continue; + } + } + + nint child = 0; + float* vector = null; + bool angle = false; + switch (type) { + case TBOOLEAN: + case TNUMBER: + case TSTRING: + break; + case TTABLE: + if (level >= MAX_DEPTH) + return DepthTooHigh; + + child = lua_topointer(L, value); + if (IsVisited(frames, top, visited, child)) + return CyclicReference; + break; + case TUSERDATA: + vector = GetVectorOrAngle(L, value, out angle); + if (vector == null) { + lua_settop(L, value - 1); + continue; + } + + break; + default: + lua_settop(L, value - 1); + continue; + } + + if (frame.Mode == Walk.ObjectNext) { + if (!name.IsEmpty) + frame.Named = true; + else if (frame.Named || HasNamedChild(lua, L, frame.Index, protect)) { + frame.Named = true; + name = "_1_"u8; + } + else + frame.InArray = true; + + if (!frame.InArray) { + writer.Prefix(ref frame.Count, false, level); + writer.String(name); + } + } + + writer.Prefix(ref frame.Count, frame.InArray, level); + switch (type) { + case TBOOLEAN: + writer.Bool(lua_toboolean(L, value) != 0); + break; + case TNUMBER: + double number = lua_tonumber(L, value); + if (double.IsSubnormal(number)) + number = 0; + if (number >= int.MinValue && number <= int.MaxValue && number == (int)number) + writer.Int((int)number); + else if (!double.IsFinite(number)) + writer.Null(); + else + writer.Double(number); + + break; + case TSTRING: + nuint size; + byte* bytes = lua_tolstring_fast(L, value, &size); + writer.String(new ReadOnlySpan(bytes, (int)size)); + break; + case TTABLE: + if (level == frames.Length) { + Span larger = new Frame[frames.Length * 4]; + frames.CopyTo(larger); + frames = larger; + } + + if (visited == null && level >= VISITED_THRESHOLD) { + visited = []; + for (int i = 0; i <= top; i++) + visited.Add(frames[i].Table); + } + + visited?.Add(child); + top++; + frames[top] = new() { Table = child, Index = value, Open = writer.Length, HasMetaTable = HasMetaTable(L, value) }; + writer.Put((byte)'['); + continue; + default: + int written = 0; + scratch[written++] = angle ? (byte)'{' : (byte)'['; + written += Bootil.String.Format.NiceFloat(vector[0], scratch[written..]); + scratch[written++] = (byte)' '; + written += Bootil.String.Format.NiceFloat(vector[1], scratch[written..]); + scratch[written++] = (byte)' '; + written += Bootil.String.Format.NiceFloat(vector[2], scratch[written..]); + scratch[written++] = angle ? (byte)'}' : (byte)']'; + writer.String(scratch[..written]); + break; + } + + lua_settop(L, value - 1); + } + + return null; + } +} diff --git a/Game.Shared/GarrysMod/LuaUtil.cs b/Game.Shared/GarrysMod/LuaUtil.cs index 1cb9936f5..5e2d8c47a 100644 --- a/Game.Shared/GarrysMod/LuaUtil.cs +++ b/Game.Shared/GarrysMod/LuaUtil.cs @@ -651,158 +651,16 @@ static int TimerCycle(ILuaInterface lua) { return 1; } - static string JSONNumber(double value) { - if (double.IsNaN(value) || double.IsInfinity(value)) - return "0"; - string str = value.ToString("R", System.Globalization.CultureInfo.InvariantCulture); - if (str.IndexOfAny(['.', 'E', 'e']) < 0) - str += ".0"; - return str; - } - - static string VectorNumber(float value) => value.ToString("0.######", System.Globalization.CultureInfo.InvariantCulture); - - static void JSONString(System.Text.StringBuilder output, string value) { - output.Append('"'); - foreach (char c in value) { - switch (c) { - case '"': output.Append("\\\""); break; - case '\\': output.Append("\\\\"); break; - case '\b': output.Append("\\b"); break; - case '\f': output.Append("\\f"); break; - case '\n': output.Append("\\n"); break; - case '\r': output.Append("\\r"); break; - case '\t': output.Append("\\t"); break; - default: - if (c < 0x20) - output.Append("\\u").Append(((int)c).ToString("X4")); - else - output.Append(c); - break; - } - } - output.Append('"'); - } - - static bool JSONValue(ILuaInterface lua, ILuaObject value, System.Text.StringBuilder output, bool pretty, int depth, HashSet visiting) { - switch (value.GetType()) { - case LuaType.Bool: - output.Append(value.GetBool() ? "true" : "false"); - return true; - case LuaType.Number: - output.Append(JSONNumber(value.GetDouble())); - return true; - case LuaType.String: - JSONString(output, value.GetString() ?? ""); - return true; - case LuaType.Vector: { - value.Push(); - System.Numerics.Vector3 vec = LuaVector.Get_Vector(-1); - lua.Pop(1); - JSONString(output, $"[{VectorNumber(vec.X)} {VectorNumber(vec.Y)} {VectorNumber(vec.Z)}]"); - return true; - } - case LuaType.Angle: { - value.Push(); - Source.Common.Mathematics.QAngle ang = LuaAngle.Get_Angle(-1); - lua.Pop(1); - JSONString(output, $"{{{VectorNumber(ang.X)} {VectorNumber(ang.Y)} {VectorNumber(ang.Z)}}}"); - return true; - } - case LuaType.Table: - return JSONTable(lua, value, output, pretty, depth + 1, visiting); - default: - return false; - } - } - - static bool JSONTable(ILuaInterface lua, ILuaObject table, System.Text.StringBuilder output, bool pretty, int depth, HashSet visiting) { - if (depth > 3000) { - lua.ErrorFromLua("JSON Depth is too high! > 3000"); - return false; - } - - - List<(LuaObject Key, LuaObject Value)> entries = []; - table.Push(); - lua.PushNil(); - while (lua.Next(-2)) { - LuaObject value = new(-1, LuaType.None); - LuaObject key = new(-2, LuaType.None); - lua.Pop(1); - entries.Add((key, value)); - } - lua.Pop(1); - - bool isArray = entries.Count > 0; - for (int i = 0; i < entries.Count && isArray; i++) { - if (entries[i].Key.GetType() != LuaType.Number) - isArray = false; - } - if (isArray) { - HashSet keys = [.. entries.Select(e => e.Key.GetDouble())]; - for (int i = 1; i <= entries.Count; i++) { - if (!keys.Contains(i)) { - isArray = false; - break; - } - } - if (isArray) - entries.Sort((a, b) => a.Key.GetDouble().CompareTo(b.Key.GetDouble())); - } - - output.Append(isArray ? '[' : '{'); - bool first = true; - foreach ((LuaObject key, LuaObject value) in entries) { - if (!isArray && key.GetType() != LuaType.String && key.GetType() != LuaType.Number) - continue; - int mark = output.Length; - if (!first) - output.Append(','); - if (pretty) - output.Append('\n').Append('\t', depth); - if (!isArray) { - JSONString(output, key.GetType() == LuaType.Number ? JSONKey(key.GetDouble()) : key.GetString() ?? ""); - output.Append(':'); - if (pretty) - output.Append(' '); - } - if (!JSONValue(lua, value, output, pretty, depth, visiting)) - output.Length = mark; - else - first = false; - } - if (pretty && !first) - output.Append('\n').Append('\t', depth - 1); - output.Append(isArray ? ']' : '}'); - - foreach ((LuaObject key, LuaObject value) in entries) { - key.UnReference(); - value.UnReference(); - } - return true; - } - - static string JSONKey(double key) { - if (key == Math.Floor(key) && Math.Abs(key) < 1e15) - return ((long)key).ToString(System.Globalization.CultureInfo.InvariantCulture); - return key.ToString("R", System.Globalization.CultureInfo.InvariantCulture); - } - [LuaFunction] static int TableToJSON(ILuaInterface lua) { - LuaObject table = new(1, LuaType.None); - if (!table.isTable()) { + if (lua.GetType(1) != LuaType.Table) { lua.TypeError("table", 1); - table.UnReference(); return 0; } - System.Text.StringBuilder output = new(); - bool ok = JSONTable(lua, table, output, lua.GetBool(2), 1, []); - table.UnReference(); - if (!ok) - return 0; - lua.PushString(output.ToString()); + + if (!lua.TableToJSON(1, lua.GetBool(2), out string? error)) + lua.Error(error); + return 1; } diff --git a/Source.Common.Tests/RapidJsonTests.cs b/Source.Common.Tests/RapidJsonTests.cs new file mode 100644 index 000000000..1eccb7d7b --- /dev/null +++ b/Source.Common.Tests/RapidJsonTests.cs @@ -0,0 +1,126 @@ +using System.Globalization; +using System.Text; + +namespace Source.Common.Tests; + +public class RapidJsonTests +{ + [Theory] + [InlineData(0.0, "0.0")] + [InlineData(-0.0, "-0.0")] + [InlineData(0.1, "0.1")] + [InlineData(0.5, "0.5")] + [InlineData(1.5, "1.5")] + [InlineData(-2.25, "-2.25")] + [InlineData(0.0001, "0.0001")] + [InlineData(-0.0001, "-0.0001")] + [InlineData(123456.789, "123456.789")] + [InlineData(3000000000.0, "3000000000.0")] + [InlineData(9007199254740992.0, "9007199254740992.0")] + [InlineData(1e21, "1e21")] + [InlineData(1e22, "1e22")] + [InlineData(1.2345e30, "1.2345e30")] + [InlineData(1e300, "1e300")] + [InlineData(5e-324, "5e-324")] + [InlineData(1.7976931348623157e308, "1.7976931348623157e308")] + [InlineData(0.3, "0.3")] + [InlineData(2.0002, "2.0002")] + [InlineData(1e-5, "0.00001")] + [InlineData(1.5e-7, "1.5e-7")] + [InlineData(1234567.1234, "1234567.1234")] + [InlineData(549755813887.9999, "549755813887.9999")] + [InlineData(0.3333, "0.3333")] + [InlineData(4.35, "4.35")] + [InlineData(1e15, "1000000000000000.0")] + [InlineData(123456789012345680.0, "123456789012345680.0")] + [InlineData(-1e-10, "-1e-10")] + public void DtoaMatchesRapidJson(double value, string expected) { + Span buffer = stackalloc byte[RapidJson.Dtoa.MaxLength]; + Assert.Equal(expected, Encoding.ASCII.GetString(buffer[..RapidJson.Dtoa.Write(value, buffer)])); + } + + static string Write(bool pretty) { + CultureInfo.CurrentCulture = new CultureInfo("fr-FR"); + RapidJson.Writer writer = new(pretty); + int root = 0; + int inner = 0; + writer.Put((byte)'{'); + writer.Prefix(ref root, false, 1); + writer.String("a\"\\\n\u0001"u8); + writer.Prefix(ref root, false, 1); + writer.Put((byte)'['); + writer.Prefix(ref inner, true, 2); + writer.Int(-5); + writer.Prefix(ref inner, true, 2); + writer.Double(1.5); + writer.Prefix(ref inner, true, 2); + writer.Bool(true); + writer.Prefix(ref inner, true, 2); + writer.Null(); + writer.End((byte)']', inner, 1); + writer.Prefix(ref root, false, 1); + writer.String("e"u8); + writer.Prefix(ref root, false, 1); + writer.Put((byte)'['); + writer.End((byte)']', 0, 1); + writer.End((byte)'}', root, 0); + string result = Encoding.UTF8.GetString(writer.WrittenSpan); + writer.Dispose(); + return result; + } + + [Fact] + public void WriterMatchesRapidJson() { + Assert.Equal("{\"a\\\"\\\\\\n\\u0001\":[-5,1.5,true,null],\"e\":[]}", Write(false)); + } + + [Fact] + public void PrettyWriterMatchesRapidJson() { + Assert.Equal("{\n\t\"a\\\"\\\\\\n\\u0001\": [\n\t\t-5,\n\t\t1.5,\n\t\ttrue,\n\t\tnull\n\t],\n\t\"e\": []\n}", Write(true)); + } + + [Fact] + public void WriterEscapesLikeRapidJson() { + RapidJson.Writer writer = new(false); + writer.String([8, 9, 10, 12, 13, 0, 31, (byte)'/', 127, 200]); + Assert.Equal("\"\\b\\t\\n\\f\\r\\u0000\\u001F/\u007FÈ\"", Encoding.Latin1.GetString(writer.WrittenSpan)); + writer.Dispose(); + } + + [Fact] + public void WriterSkipsNaN() { + RapidJson.Writer writer = new(false); + Assert.False(writer.Double(double.NaN)); + Assert.Equal(0, writer.Length); + writer.Dispose(); + } + + [Fact] + public void WriterGrowsPastThePool() { + RapidJson.Writer writer = new(false); + byte[] chunk = new byte[70000]; + Array.Fill(chunk, (byte)'x'); + for (int i = 0; i < 40; i++) + writer.String(chunk); + Assert.Equal(40 * 70002, writer.Length); + Assert.Equal((byte)'"', writer.WrittenSpan[^1]); + Assert.Equal((byte)'x', writer.WrittenSpan[^2]); + writer.Dispose(); + } + + [Theory] + [InlineData(1f, "1")] + [InlineData(2.5f, "2.5")] + [InlineData(-3f, "-3")] + [InlineData(0.00001f, "0")] + [InlineData(-0.00001f, "-0")] + [InlineData(0.33333334f, "0.3333")] + [InlineData(123456.789f, "123456.7891")] + [InlineData(1e10f, "10000000000")] + [InlineData(3.4028235e38f, "340282346638528859811704183484516925440")] + public void NiceFloatMatchesBootil(float value, string expected) { + CultureInfo.CurrentCulture = new CultureInfo("fr-FR"); + Span buffer = stackalloc byte[64]; + Assert.Equal(expected, Encoding.ASCII.GetString(buffer[..Bootil.String.Format.NiceFloat(value, buffer)])); + } +} diff --git a/Source.Common/Bootil/String.cs b/Source.Common/Bootil/String.cs index 6230a3171..48bde2e0c 100644 --- a/Source.Common/Bootil/String.cs +++ b/Source.Common/Bootil/String.cs @@ -23,6 +23,73 @@ public static string Memory(ulong bytes) { } public static string UInt64(ulong num) => num.ToString(System.Globalization.CultureInfo.InvariantCulture); + + const double ExactLimit = 549755813888.0; + + static ulong RoundTenThousandths(double magnitude) { + ulong bits = BitConverter.DoubleToUInt64Bits(magnitude); + int exponent = (int)(bits >> 52) & 0x7FF; + ulong mantissa = bits & 0xFFFFFFFFFFFFF; + if (exponent == 0) + exponent = 1; + else + mantissa |= 1UL << 52; + + int shift = 1071 - exponent; + if (shift > 63) + return 0; + + ulong scaled = mantissa * 625; + ulong quotient = scaled >> shift; + ulong rest = scaled & ((1UL << shift) - 1); + ulong half = 1UL << (shift - 1); + if (rest > half || (rest == half && (quotient & 1) != 0)) + quotient++; + + return quotient; + } + + public static int NiceFloat(float value, Span target) { + double number = value; + if (!double.IsFinite(number) || Math.Abs(number) >= ExactLimit) { + string text; + if (double.IsFinite(number)) + text = Source.Common.CFormatting.FormatFixed(number, 4).TrimEnd('0').TrimEnd('.'); + else { +#if WIN32 + text = Source.Common.CFormatting.FormatFixed(number, 4); +#elif LINUX + text = double.IsNaN(number) ? double.IsNegative(number) ? "-nan" : "nan" : number < 0 ? "-inf" : "inf"; +#else + text = double.IsNaN(number) ? "nan" : number < 0 ? "-inf" : "inf"; +#endif + } + + return System.Text.Encoding.ASCII.GetBytes(text, target); + } + + ulong scaled = RoundTenThousandths(Math.Abs(number)); + int length = 0; + if (double.IsNegative(number)) + target[length++] = (byte)'-'; + + (scaled / 10000).TryFormat(target[length..], out int written, default, System.Globalization.CultureInfo.InvariantCulture); + length += written; + + uint fraction = (uint)(scaled % 10000); + if (fraction != 0) { + target[length] = (byte)'.'; + target[length + 1] = (byte)('0' + fraction / 1000); + target[length + 2] = (byte)('0' + fraction / 100 % 10); + target[length + 3] = (byte)('0' + fraction / 10 % 10); + target[length + 4] = (byte)('0' + fraction % 10); + length += 5; + while (target[length - 1] == '0') + length--; + } + + return length; + } } public static class To diff --git a/Source.Common/GarrysMod/Lua/LuaInterface.cs b/Source.Common/GarrysMod/Lua/LuaInterface.cs index 7822d81d4..b95d02f2c 100644 --- a/Source.Common/GarrysMod/Lua/LuaInterface.cs +++ b/Source.Common/GarrysMod/Lua/LuaInterface.cs @@ -57,6 +57,7 @@ public interface ILuaInterface : ILuaBase bool RunString(ReadOnlySpan filename, ReadOnlySpan path, ReadOnlySpan stringToRun, bool run, bool showErrors); bool IsEqual(ILuaObject? objA, ILuaObject? objB); [DoesNotReturn] void Error(ReadOnlySpan err); + bool TableToJSON(int stackPos, bool pretty, [NotNullWhen(false)] out string? error); string GetStringOrError(int index); bool RunLuaModule(ReadOnlySpan name); bool FindAndRunScript(ReadOnlySpan filename, bool run, bool showErrors, ReadOnlySpan source, bool noReturns); diff --git a/Source.Common/GarrysMod/Lua/LuaNull.cs b/Source.Common/GarrysMod/Lua/LuaNull.cs index a2766b6be..fd3b41b61 100644 --- a/Source.Common/GarrysMod/Lua/LuaNull.cs +++ b/Source.Common/GarrysMod/Lua/LuaNull.cs @@ -256,6 +256,10 @@ public void SetMemberFast(ILuaObject table, int keyIndex, int valueIndex) { } public bool RunString(ReadOnlySpan filename, ReadOnlySpan path, ReadOnlySpan stringToRun, bool run, bool showErrors) => false; public bool IsEqual(ILuaObject? objA, ILuaObject? objB) => false; [DoesNotReturn] public void Error(ReadOnlySpan err) => throw new NotSupportedException(err.ToString()); + public bool TableToJSON(int stackPos, bool pretty, [NotNullWhen(false)] out string? error) { + error = ""; + return false; + } public string GetStringOrError(int index) => ""; public bool RunLuaModule(ReadOnlySpan name) => false; public bool FindAndRunScript(ReadOnlySpan filename, bool run, bool showErrors, ReadOnlySpan source, bool noReturns) => false; diff --git a/Source.Common/RapidJson/Dtoa.cs b/Source.Common/RapidJson/Dtoa.cs new file mode 100644 index 000000000..061d4bee7 --- /dev/null +++ b/Source.Common/RapidJson/Dtoa.cs @@ -0,0 +1,321 @@ +using System.Numerics; + +namespace RapidJson; + +public static unsafe class Dtoa +{ + const int kDiySignificandSize = 64; + const int kDpSignificandSize = 52; + const int kDpExponentBias = 0x3FF + kDpSignificandSize; + const int kDpMinExponent = -kDpExponentBias; + const ulong kDpExponentMask = 0x7FF0000000000000; + const ulong kDpSignificandMask = 0x000FFFFFFFFFFFFF; + const ulong kDpHiddenBit = 0x0010000000000000; + + public const int MaxLength = 25; + + struct DiyFp + { + public ulong F; + public int E; + + public DiyFp(ulong f, int e) { + F = f; + E = e; + } + + public DiyFp(double d) { + ulong u64 = BitConverter.DoubleToUInt64Bits(d); + int biasedE = (int)((u64 & kDpExponentMask) >> kDpSignificandSize); + ulong significand = u64 & kDpSignificandMask; + if (biasedE != 0) { + F = significand + kDpHiddenBit; + E = biasedE - kDpExponentBias; + } + else { + F = significand; + E = kDpMinExponent + 1; + } + } + + public static DiyFp operator -(DiyFp a, DiyFp b) => new(a.F - b.F, a.E); + + public static DiyFp operator *(DiyFp a, DiyFp b) { + ulong h = Math.BigMul(a.F, b.F, out ulong l); + if ((l & (1UL << 63)) != 0) + h++; + return new(h, a.E + b.E + 64); + } + + public readonly DiyFp Normalize() { + int s = BitOperations.LeadingZeroCount(F); + return new(F << s, E - s); + } + + public readonly DiyFp NormalizeBoundary() { + DiyFp res = this; + while ((res.F & (kDpHiddenBit << 1)) == 0) { + res.F <<= 1; + res.E--; + } + + res.F <<= kDiySignificandSize - kDpSignificandSize - 2; + res.E -= kDiySignificandSize - kDpSignificandSize - 2; + return res; + } + + public readonly void NormalizedBoundaries(out DiyFp minus, out DiyFp plus) { + DiyFp pl = new DiyFp((F << 1) + 1, E - 1).NormalizeBoundary(); + DiyFp mi = F == kDpHiddenBit ? new DiyFp((F << 2) - 1, E - 2) : new DiyFp((F << 1) - 1, E - 1); + mi.F <<= mi.E - pl.E; + mi.E = pl.E; + plus = pl; + minus = mi; + } + } + + static readonly ulong[] kCachedPowers_F = [ + 0xFA8FD5A0081C0288, 0xBAAEE17FA23EBF76, 0x8B16FB203055AC76, 0xCF42894A5DCE35EA, + 0x9A6BB0AA55653B2D, 0xE61ACF033D1A45DF, 0xAB70FE17C79AC6CA, 0xFF77B1FCBEBCDC4F, + 0xBE5691EF416BD60C, 0x8DD01FAD907FFC3C, 0xD3515C2831559A83, 0x9D71AC8FADA6C9B5, + 0xEA9C227723EE8BCB, 0xAECC49914078536D, 0x823C12795DB6CE57, 0xC21094364DFB5637, + 0x9096EA6F3848984F, 0xD77485CB25823AC7, 0xA086CFCD97BF97F4, 0xEF340A98172AACE5, + 0xB23867FB2A35B28E, 0x84C8D4DFD2C63F3B, 0xC5DD44271AD3CDBA, 0x936B9FCEBB25C996, + 0xDBAC6C247D62A584, 0xA3AB66580D5FDAF6, 0xF3E2F893DEC3F126, 0xB5B5ADA8AAFF80B8, + 0x87625F056C7C4A8B, 0xC9BCFF6034C13053, 0x964E858C91BA2655, 0xDFF9772470297EBD, + 0xA6DFBD9FB8E5B88F, 0xF8A95FCF88747D94, 0xB94470938FA89BCF, 0x8A08F0F8BF0F156B, + 0xCDB02555653131B6, 0x993FE2C6D07B7FAC, 0xE45C10C42A2B3B06, 0xAA242499697392D3, + 0xFD87B5F28300CA0E, 0xBCE5086492111AEB, 0x8CBCCC096F5088CC, 0xD1B71758E219652C, + 0x9C40000000000000, 0xE8D4A51000000000, 0xAD78EBC5AC620000, 0x813F3978F8940984, + 0xC097CE7BC90715B3, 0x8F7E32CE7BEA5C70, 0xD5D238A4ABE98068, 0x9F4F2726179A2245, + 0xED63A231D4C4FB27, 0xB0DE65388CC8ADA8, 0x83C7088E1AAB65DB, 0xC45D1DF942711D9A, + 0x924D692CA61BE758, 0xDA01EE641A708DEA, 0xA26DA3999AEF774A, 0xF209787BB47D6B85, + 0xB454E4A179DD1877, 0x865B86925B9BC5C2, 0xC83553C5C8965D3D, 0x952AB45CFA97A0B3, + 0xDE469FBD99A05FE3, 0xA59BC234DB398C25, 0xF6C69A72A3989F5C, 0xB7DCBF5354E9BECE, + 0x88FCF317F22241E2, 0xCC20CE9BD35C78A5, 0x98165AF37B2153DF, 0xE2A0B5DC971F303A, + 0xA8D9D1535CE3B396, 0xFB9B7CD9A4A7443C, 0xBB764C4CA7A44410, 0x8BAB8EEFB6409C1A, + 0xD01FEF10A657842C, 0x9B10A4E5E9913129, 0xE7109BFBA19C0C9D, 0xAC2820D9623BF429, + 0x80444B5E7AA7CF85, 0xBF21E44003ACDD2D, 0x8E679C2F5E44FF8F, 0xD433179D9C8CB841, + 0x9E19DB92B4E31BA9, 0xEB96BF6EBADF77D9, 0xAF87023B9BF0EE6B, + ]; + + static readonly short[] kCachedPowers_E = [ + -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, + -954, -927, -901, -874, -847, -821, -794, -768, -741, -715, + -688, -661, -635, -608, -582, -555, -529, -502, -475, -449, + -422, -396, -369, -343, -316, -289, -263, -236, -210, -183, + -157, -130, -103, -77, -50, -24, 3, 30, 56, 83, + 109, 136, 162, 189, 216, 242, 269, 295, 322, 348, + 375, 402, 428, 455, 481, 508, 534, 561, 588, 614, + 641, 667, 694, 720, 747, 774, 800, 827, 853, 880, + 907, 933, 960, 986, 1013, 1039, 1066, + ]; + + static readonly ulong[] kPow10 = [ + 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, + 10000000000, 100000000000, 1000000000000, 10000000000000, 100000000000000, 1000000000000000, + 10000000000000000, 100000000000000000, 1000000000000000000, 10000000000000000000, + ]; + + static DiyFp GetCachedPower(int e, out int K) { + double dk = (-61 - e) * 0.30102999566398114 + 347; + int k = (int)dk; + if (dk - k > 0.0) + k++; + + int index = (k >> 3) + 1; + K = -(-348 + (index << 3)); + return new(kCachedPowers_F[index], kCachedPowers_E[index]); + } + + static void GrisuRound(byte* buffer, int len, ulong delta, ulong rest, ulong ten_kappa, ulong wp_w) { + while (rest < wp_w && delta - rest >= ten_kappa && (rest + ten_kappa < wp_w || wp_w - rest > rest + ten_kappa - wp_w)) { + buffer[len - 1]--; + rest += ten_kappa; + } + } + + static int CountDecimalDigit32(uint n) { + if (n < 10) return 1; + if (n < 100) return 2; + if (n < 1000) return 3; + if (n < 10000) return 4; + if (n < 100000) return 5; + if (n < 1000000) return 6; + if (n < 10000000) return 7; + if (n < 100000000) return 8; + return 9; + } + + static void DigitGen(in DiyFp W, in DiyFp Mp, ulong delta, byte* buffer, out int len, ref int K) { + DiyFp one = new(1UL << -Mp.E, Mp.E); + DiyFp wp_w = Mp - W; + uint p1 = (uint)(Mp.F >> -one.E); + ulong p2 = Mp.F & (one.F - 1); + int kappa = CountDecimalDigit32(p1); + len = 0; + + while (kappa > 0) { + uint d = 0; + switch (kappa) { + case 9: d = p1 / 100000000; p1 %= 100000000; break; + case 8: d = p1 / 10000000; p1 %= 10000000; break; + case 7: d = p1 / 1000000; p1 %= 1000000; break; + case 6: d = p1 / 100000; p1 %= 100000; break; + case 5: d = p1 / 10000; p1 %= 10000; break; + case 4: d = p1 / 1000; p1 %= 1000; break; + case 3: d = p1 / 100; p1 %= 100; break; + case 2: d = p1 / 10; p1 %= 10; break; + case 1: d = p1; p1 = 0; break; + } + + if (d != 0 || len != 0) + buffer[len++] = (byte)('0' + d); + kappa--; + ulong tmp = ((ulong)p1 << -one.E) + p2; + if (tmp <= delta) { + K += kappa; + GrisuRound(buffer, len, delta, tmp, kPow10[kappa] << -one.E, wp_w.F); + return; + } + } + + for (; ; ) { + p2 *= 10; + delta *= 10; + byte d = (byte)(p2 >> -one.E); + if (d != 0 || len != 0) + buffer[len++] = (byte)('0' + d); + p2 &= one.F - 1; + kappa--; + if (p2 < delta) { + K += kappa; + int index = -kappa; + GrisuRound(buffer, len, delta, p2, one.F, wp_w.F * (index < 20 ? kPow10[index] : 0)); + return; + } + } + } + + static void Grisu2(double value, byte* buffer, out int length, out int K) { + DiyFp v = new(value); + v.NormalizedBoundaries(out DiyFp w_m, out DiyFp w_p); + + DiyFp c_mk = GetCachedPower(w_p.E, out K); + DiyFp W = v.Normalize() * c_mk; + DiyFp Wp = w_p * c_mk; + DiyFp Wm = w_m * c_mk; + Wm.F++; + Wp.F--; + DigitGen(in W, in Wp, Wp.F - Wm.F, buffer, out length, ref K); + } + + static int WriteExponent(int K, byte* buffer) { + int i = 0; + if (K < 0) { + buffer[i++] = (byte)'-'; + K = -K; + } + + if (K >= 100) { + buffer[i++] = (byte)('0' + K / 100); + K %= 100; + buffer[i++] = (byte)('0' + K / 10); + buffer[i++] = (byte)('0' + K % 10); + } + else if (K >= 10) { + buffer[i++] = (byte)('0' + K / 10); + buffer[i++] = (byte)('0' + K % 10); + } + else + buffer[i++] = (byte)('0' + K); + + return i; + } + + static int Prettify(byte* buffer, int length, int k, int maxDecimalPlaces) { + int kk = length + k; + + if (0 <= k && kk <= 21) { + for (int i = length; i < kk; i++) + buffer[i] = (byte)'0'; + buffer[kk] = (byte)'.'; + buffer[kk + 1] = (byte)'0'; + return kk + 2; + } + else if (0 < kk && kk <= 21) { + Buffer.MemoryCopy(buffer + kk, buffer + kk + 1, length - kk, length - kk); + buffer[kk] = (byte)'.'; + if (0 > k + maxDecimalPlaces) { + for (int i = kk + maxDecimalPlaces; i > kk + 1; i--) { + if (buffer[i] != '0') + return i + 1; + } + + return kk + 2; + } + else + return length + 1; + } + else if (-6 < kk && kk <= 0) { + int offset = 2 - kk; + Buffer.MemoryCopy(buffer, buffer + offset, length, length); + buffer[0] = (byte)'0'; + buffer[1] = (byte)'.'; + for (int i = 2; i < offset; i++) + buffer[i] = (byte)'0'; + if (length - kk > maxDecimalPlaces) { + for (int i = maxDecimalPlaces + 1; i > 2; i--) { + if (buffer[i] != '0') + return i + 1; + } + + return 3; + } + else + return length + offset; + } + else if (kk < -maxDecimalPlaces) { + buffer[0] = (byte)'0'; + buffer[1] = (byte)'.'; + buffer[2] = (byte)'0'; + return 3; + } + else if (length == 1) { + buffer[1] = (byte)'e'; + return 2 + WriteExponent(kk - 1, buffer + 2); + } + else { + Buffer.MemoryCopy(buffer + 1, buffer + 2, length - 1, length - 1); + buffer[1] = (byte)'.'; + buffer[length + 1] = (byte)'e'; + return length + 2 + WriteExponent(kk - 1, buffer + length + 2); + } + } + + public static int Write(double value, Span target, int maxDecimalPlaces = 324) { + ArgumentOutOfRangeException.ThrowIfLessThan(target.Length, MaxLength); + + fixed (byte* buffer = target) { + if (value == 0) { + int i = 0; + if (double.IsNegative(value)) + buffer[i++] = (byte)'-'; + buffer[i++] = (byte)'0'; + buffer[i++] = (byte)'.'; + buffer[i++] = (byte)'0'; + return i; + } + + int sign = 0; + if (value < 0) { + buffer[0] = (byte)'-'; + value = -value; + sign = 1; + } + + Grisu2(value, buffer + sign, out int length, out int K); + return sign + Prettify(buffer + sign, length, K, maxDecimalPlaces); + } + } +} diff --git a/Source.Common/RapidJson/Writer.cs b/Source.Common/RapidJson/Writer.cs new file mode 100644 index 000000000..dc633c0a0 --- /dev/null +++ b/Source.Common/RapidJson/Writer.cs @@ -0,0 +1,198 @@ +using System.Buffers; +using System.Globalization; +using System.Runtime.CompilerServices; + +namespace RapidJson; + +public struct Writer : IDisposable +{ + static ReadOnlySpan HexDigits => "0123456789ABCDEF"u8; + static readonly SearchValues Escaped = SearchValues.Create([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, (byte)'"', (byte)'\\' + ]); + + const int MaxPooled = 1 << 20; + + [ThreadStatic] static WeakReference? spare; + + byte[] buffer; + int length; + readonly bool pretty; + + public Writer(bool pretty) { + buffer = ArrayPool.Shared.Rent(4096); + this.pretty = pretty; + } + + public int Length { + readonly get => length; + set => length = value; + } + + public readonly ReadOnlySpan WrittenSpan => buffer.AsSpan(0, length); + public readonly ref byte this[int offset] => ref buffer[offset]; + + static byte[] Rent(int size) { + if (size <= MaxPooled) + return ArrayPool.Shared.Rent(size); + + if (spare != null && spare.TryGetTarget(out byte[]? cached) && cached.Length >= size) { + spare.SetTarget(null); + return cached; + } + + return GC.AllocateUninitializedArray(size); + } + + static void Return(byte[] array) { + if (array.Length <= MaxPooled) + ArrayPool.Shared.Return(array); + else if (spare == null) + spare = new(array); + else if (!spare.TryGetTarget(out byte[]? cached) || cached.Length < array.Length) + spare.SetTarget(array); + } + + public void Dispose() { + if (buffer.Length != 0) + Return(buffer); + buffer = []; + } + + void Grow(int count) { + long size = Math.Max((long)buffer.Length * 2, (long)length + count); + if (size > Array.MaxLength) + size = Math.Max(Array.MaxLength, (long)length + count); + + byte[] larger = Rent(checked((int)size)); + buffer.AsSpan(0, length).CopyTo(larger); + Return(buffer); + buffer = larger; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + void Ensure(int count) { + if (buffer.Length - length < count) + Grow(count); + } + + Span Reserve(int count) { + Ensure(count); + return buffer.AsSpan(length); + } + + public void Put(byte c) { + if (length == buffer.Length) + Grow(1); + buffer[length++] = c; + } + + void PutN(byte c, int count) { + Ensure(count); + buffer.AsSpan(length, count).Fill(c); + length += count; + } + + void Put(scoped ReadOnlySpan text) { + Ensure(text.Length); + text.CopyTo(buffer.AsSpan(length)); + length += text.Length; + } + + public void Prefix(ref int valueCount, bool inArray, int level) { + if (!pretty) { + if (valueCount > 0) + Put(inArray ? (byte)',' : valueCount % 2 == 0 ? (byte)',' : (byte)':'); + } + else if (inArray) { + if (valueCount > 0) + Put((byte)','); + Put((byte)'\n'); + PutN((byte)'\t', level); + } + else { + if (valueCount > 0) { + if (valueCount % 2 == 0) { + Put((byte)','); + Put((byte)'\n'); + } + else { + Put((byte)':'); + Put((byte)' '); + } + } + else + Put((byte)'\n'); + + if (valueCount % 2 == 0) + PutN((byte)'\t', level); + } + + valueCount++; + } + + public void End(byte bracket, int valueCount, int level) { + if (pretty && valueCount != 0) { + Put((byte)'\n'); + PutN((byte)'\t', level); + } + + Put(bracket); + } + + public void Int(int value) { + Span target = Reserve(11); + value.TryFormat(target, out int written, default, CultureInfo.InvariantCulture); + length += written; + } + + public bool Double(double value) { + if (!double.IsFinite(value)) + return false; + + length += Dtoa.Write(value, Reserve(Dtoa.MaxLength)); + return true; + } + + public void Null() => Put("null"u8); + + public void Bool(bool value) => Put(value ? "true"u8 : "false"u8); + + public void String(scoped ReadOnlySpan text) { + Ensure(text.Length + 2); + buffer[length++] = (byte)'"'; + while (true) { + int index = text.IndexOfAny(Escaped); + if (index < 0) { + Put(text); + break; + } + + Put(text[..index]); + byte c = text[index]; + Span target = Reserve(6); + target[0] = (byte)'\\'; + switch (c) { + case (byte)'"': target[1] = (byte)'"'; length += 2; break; + case (byte)'\\': target[1] = (byte)'\\'; length += 2; break; + case 8: target[1] = (byte)'b'; length += 2; break; + case 9: target[1] = (byte)'t'; length += 2; break; + case 10: target[1] = (byte)'n'; length += 2; break; + case 12: target[1] = (byte)'f'; length += 2; break; + case 13: target[1] = (byte)'r'; length += 2; break; + default: + target[1] = (byte)'u'; + target[2] = (byte)'0'; + target[3] = (byte)'0'; + target[4] = HexDigits[c >> 4]; + target[5] = HexDigits[c & 0xF]; + length += 6; + break; + } + + text = text[(index + 1)..]; + } + + Put((byte)'"'); + } +}