diff --git a/.claude/skills/benchmark/SKILL.md b/.claude/skills/benchmark/SKILL.md index 2bc89b855..5a2bb1454 100644 --- a/.claude/skills/benchmark/SKILL.md +++ b/.claude/skills/benchmark/SKILL.md @@ -136,9 +136,10 @@ runs in both, so its two results show how much the machine moved. Heavy runs go took 6 h 17 min (run 41364890698); a filter of 13 cases at 12 rounds took 2 hours (41399172268). - **Skip an A/B whose code is unchanged** (identical generated files or machine code prove it), and prove it per runtime before requesting the line: Go, `go test -c` the bench at both commits and diff `go tool objdump` with - paths and addresses stripped; TypeScript, runtime-ab runs the head's `bench.ts` on both sides, so the sides differ - only in `src/nino.ts`, what nino-gen writes for `bench/Bench.dll` and the data `Bench.dll` writes (diff all - three); Rust, `objdump -d` the bench binary each side builds with the line's + paths and addresses stripped; in TypeScript, diff each revision's benchmark harness, `src/nino.ts`, and the + codecs and data its `bench/generate.sh` writes. Since #374 the runtime A/B workflow runs each revision's own + harness and generates its fixtures from the .NET benchmark schema. In Rust, run `objdump -d` on each benchmark + binary built with the line's `RUSTFLAGS=-Cllvm-args=-align-all-functions=6`, addresses stripped (after items moved between modules, also the `::h` suffixes, the moved paths mapped and the `# ` comments; criterion's code and a bench's own setup can land in other codegen units of the bench crate, so compare every `nino::` function and timed diff --git a/.claude/skills/optimize-runtimes/references/inlining-gc.md b/.claude/skills/optimize-runtimes/references/inlining-gc.md index c8537d1bf..8b97434a4 100644 --- a/.claude/skills/optimize-runtimes/references/inlining-gc.md +++ b/.claude/skills/optimize-runtimes/references/inlining-gc.md @@ -8,6 +8,13 @@ Read it before growing a TypeScript or Rust hot helper, or when a TypeScript cas when a shape helps one target and hurts another, put it behind `cfg(target_arch)` and keep the generic loop for every other target (the map read taking one check per entry is x86/x86_64 only: on Arm64 it held the key/value pair in a SIMD register across the hash call and Neoverse-N2 ran 3 to 4 % slower). Test both paths (`platforms`). +- Flatten the TypeScript runtime modules into one lexical scope for npm and nino-gen. On Node 22.23.4, #247's + single-file output kept the bytecode lengths and TurboFan inlining of the monolith's string and Latin-1 paths, + numeric blocks, and generated IntArray, BoolArray and ByteArray readers, both with and without `Buffer`. + Compare `--print-bytecode` lengths and `--trace-turbo-inlining` call edges after warming both paths of each build. + The MixedStrings runner A/B and same-revision controls (44329792122) put the modular bundle within 5 % + by per-CPU median on every measured x64 CPU and Neoverse-N2. On Neoverse-N2 the medians moved −1.13 % for + serialize, −1.17 % for serializeInto and −0.11 % for deserialize. - TypeScript output is the bytes it writes: a slower serialize in a large heap is often GC, not the loop. Before changing a write loop for a case that got slower, run it with `--trace-gc` and read whose pauses land in its task. Every new `ArrayBuffer` counts as external memory, and Node 24 starts a full GC for each 64 MB of them that no scavenge diff --git a/.gitattributes b/.gitattributes index b53beda1c..a7ac86b26 100644 --- a/.gitattributes +++ b/.gitattributes @@ -27,6 +27,8 @@ runtimes/rust/tests/conformance/types.rs linguist-generated runtimes/go/internal/generated/**/nino_types.go linguist-generated runtimes/rust/tests/generated/*.rs linguist-generated runtimes/typescript/test/generated/*.ts linguist-generated +# npm run build:bundle +runtimes/typescript/src/nino.ts linguist-generated # Protocol Buffers code the runtimes' benchmarks compare against. *.pb.go linguist-generated *_pb.ts linguist-generated diff --git a/AGENTS.md b/AGENTS.md index 0322ade76..e96f0b226 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -41,7 +41,7 @@ one (CI runs `tools/agents.sh --check`, which also checks that every file is in | [`runtimes/csharp/tests/`](runtimes/csharp/tests/AGENTS.md) | adding or changing a test, or finding where a feature, a platform or hostile input is tested | | [`runtimes/go/`](runtimes/go/AGENTS.md) | reading or changing the Go runtime (runtimes/go, package nino), its string kernels, struct tags, sample codecs or Go benchmark | | [`runtimes/rust/`](runtimes/rust/AGENTS.md) | reading or changing the Rust runtime (runtimes/rust: crates nino-serialization and nino-serialization-derive), its SIMD kernels, tests or benchmarks | -| [`runtimes/typescript/`](runtimes/typescript/AGENTS.md) | reading or changing the TypeScript runtime (runtimes/typescript: src/nino.ts, its WebAssembly kernels, tests or benchmark) | +| [`runtimes/typescript/`](runtimes/typescript/AGENTS.md) | reading or changing the TypeScript runtime (runtimes/typescript: src/runtime/, its single-file bundle, WebAssembly kernels, tests or benchmark) | | [`tests/conformance/`](tests/conformance/AGENTS.md) | changing the wire format, a layout, a malicious-input check or a sample type, or making a runtime read the shared conformance corpus | diff --git a/docs/codegen.md b/docs/codegen.md index 5b10d0797..e01a1c3e0 100644 --- a/docs/codegen.md +++ b/docs/codegen.md @@ -61,11 +61,12 @@ directory, deleting what the list names but this run no longer writes. The generated API of each language is on the site; these are the decisions behind it. -- **TypeScript** (`TypeScriptTarget`): the module of an assembly, with `nino.ts` (embedded in the tool from - `runtimes/typescript/src/nino.ts`) written next to it unless `--runtime` names a module. The bodies of types without - members (`readBody$Empty`, `writeBody$Empty` and the version-tolerant ones) name their parameters `_r`, `_w` and +- **TypeScript** (`TypeScriptTarget`): the module of an assembly, with the embedded runtime bundle (`runtimes/typescript/src/nino.ts`) + written next to it unless `--runtime` names a module. The bodies of types without members (`readBody$Empty`, `writeBody$Empty` and the version-tolerant ones) name their parameters `_r`, `_w` and `_v`, so the code compiles under `noUnusedParameters`. With `--numeric-arrays typed`, - `TypeScriptTarget.NumberArrays` chooses the typed array of each fixed-size number. + `TypeScriptTarget.NumberArrays` chooses the typed array of each fixed-size number. Rectangular arrays of rank + 2 to 4 have a `NinoGrid` shape with `lengths` and flat row-major `data`. Numeric grids use typed storage + in either mode, and grids of raw nullable elements use `NullableSlot[]`. - **Go** (`GoTarget`): read and write functions in the shape of the hand-written codecs in `runtimes/go/internal/sample`: one `Take`/`Extend` per run of fixed-size members, no reflection, and a direct call for each class body and each element of a collection (no function values; `optimize-runtimes`). diff --git a/runtimes/csharp/src/Nino.Codegen/AGENTS.md b/runtimes/csharp/src/Nino.Codegen/AGENTS.md index 4c6354967..59aca46d0 100644 --- a/runtimes/csharp/src/Nino.Codegen/AGENTS.md +++ b/runtimes/csharp/src/Nino.Codegen/AGENTS.md @@ -9,7 +9,8 @@ dotnet tool `Nino.Codegen.Tool`. `audit-runtimes` audits it, `audit-generated-co ``` Nino.Codegen.csproj the exe (nino-gen.dll, no apphost) and the package: tools/ holds it and its assemblies, - build/ the targets; embeds Templates/**/*.sbn and runtimes/typescript/src/nino.ts + build/ the targets; embeds Templates/**/*.sbn and the single-file TypeScript bundle + runtimes/typescript/src/nino.ts (see runtimes/typescript/AGENTS.md) Program.cs the command line: --assembly --lang ts|go|rust --out [options]; writes a file only when its text changes, and deletes what its manifest (.nino-gen) lists but this run no longer writes diff --git a/runtimes/csharp/src/Nino.Codegen/Targets/TypeScript/TsShape.cs b/runtimes/csharp/src/Nino.Codegen/Targets/TypeScript/TsShape.cs index f7e73f058..7c44323b0 100644 --- a/runtimes/csharp/src/Nino.Codegen/Targets/TypeScript/TsShape.cs +++ b/runtimes/csharp/src/Nino.Codegen/Targets/TypeScript/TsShape.cs @@ -8,7 +8,7 @@ namespace Nino.Codegen.Targets /// /// How a value is written in TypeScript (: prim, enum, rawstruct, /// rawnullable, fixedtuple, tuple, string, utf8, object, - /// nullable, bytes, seq, map, type, param: a type parameter, + /// nullable, bytes, seq, map, grid, type, param: a type parameter, /// generic: a generic type with its arguments in ): the template turns it into a type, a /// default, and code reading and writing it, alone or at an offset. /// @@ -64,6 +64,9 @@ public sealed class TsShape /// A set (Set) rather than an array. public bool Set { get; internal set; } + /// The number of dimensions of a rectangular array. + public int Rank { get; internal set; } + /// /// How a set's element or a map's key of this shape passes through NinoKeyGuard (the runtime's bound on /// hash flooding for the keys V8 hashes without a seed): int (an int32 value), number, @@ -144,7 +147,7 @@ private IEnumerable Parts() yield return Struct?.FullName ?? ""; yield return Type?.FullName ?? ""; yield return Header ?? ""; - yield return Set ? "set" : ""; + yield return Set ? "set" : Rank == 0 ? "" : Rank.ToString(System.Globalization.CultureInfo.InvariantCulture); yield return ArrayType ?? ""; yield return FlagOffset + "/" + ValueOffset + (Clean ? "/clean" : ""); yield return string.Join("/", Offsets); diff --git a/runtimes/csharp/src/Nino.Codegen/Targets/TypeScript/TypeScriptTarget.Shapes.cs b/runtimes/csharp/src/Nino.Codegen/Targets/TypeScript/TypeScriptTarget.Shapes.cs index 7702d3f56..a05ec61ae 100644 --- a/runtimes/csharp/src/Nino.Codegen/Targets/TypeScript/TypeScriptTarget.Shapes.cs +++ b/runtimes/csharp/src/Nino.Codegen/Targets/TypeScript/TypeScriptTarget.Shapes.cs @@ -197,6 +197,21 @@ internal TsShape Shape(ValueModel value) var (key, mapValue) = (Shape(value.Key!), Shape(value.Value!)); return InContext(value, Holding(new TsShape("map") { Key = key, Value = mapValue }, key, mapValue)); } + case ValueKind.Grid: + { + if (value.Rank is < 2 or > 4) + throw new UnsupportedException($"{value.ClrName} has unsupported array rank {value.Rank}"); + var element = Shape(value.Element!); + element.SlotElement = element is { Kind: "rawnullable", Clean: false }; + string? array = null; + if (element.Kind == "prim") + NumberArrays.TryGetValue(element.Primitive!, out array); + return InContext(value, Holding(new TsShape("grid") + { + Element = element, Rank = value.Rank, ArrayType = array, + InlineLength = array == null ? 0 : 64 / element.Size, + }, element)); + } case ValueKind.Tuple: { // The items one after another: at fixed offsets when they all have a fixed size. @@ -215,7 +230,7 @@ internal TsShape Shape(ValueModel value) case ValueKind.Unsupported: throw new UnsupportedException(Problem(value)); default: - // grid, bigint, version, datetimeoffset. + // bigint, version, datetimeoffset. throw new UnsupportedException($"{value.ClrName} ({KindName(value)}) has no TypeScript form"); } } diff --git a/runtimes/csharp/src/Nino.Codegen/Targets/TypeScript/TypeScriptTarget.cs b/runtimes/csharp/src/Nino.Codegen/Targets/TypeScript/TypeScriptTarget.cs index c0bdc9435..89cabfb08 100644 --- a/runtimes/csharp/src/Nino.Codegen/Targets/TypeScript/TypeScriptTarget.cs +++ b/runtimes/csharp/src/Nino.Codegen/Targets/TypeScript/TypeScriptTarget.cs @@ -126,6 +126,12 @@ public string Render(string source) aliases.Add(alias); return alias + "<" + inner + ">"; })); + renderer.Function("grid_type", new Func(data => + { + // A .NET type may also be named NinoGrid. Its generated name never contains a dollar sign. + aliases.Add("NinoGrid as NinoGrid$"); + return "NinoGrid$<" + data + ">"; + })); string text = renderer.Render("types.sbn").TrimEnd('\n') + "\n"; return text.Replace(MoreImports, string.Concat(aliases.Select(a => ", type " + a))); } @@ -295,13 +301,15 @@ internal List Members(TypeModel type) /// private string Helper(TsShape shape, string mode) { + if (mode == "readinto" && (shape.Kind == "grid" || shape.ArrayType != null)) + mode = "read"; string key = mode + ":" + shape.Identity; if (_helperByKey.TryGetValue(key, out var helper)) return helper.Name; // The functions the value's code calls come first. switch (shape.Kind) { - case "seq" when !shape.Element!.Fixed: + case "seq" or "grid" when !shape.Element!.Fixed: Touch(shape.Element, mode); break; case "map" when !(shape.Key!.Fixed && shape.Value!.Fixed): @@ -334,6 +342,7 @@ private void Touch(TsShape shape, string mode) { case "seq": case "map": + case "grid": case "rawnullable": case "fixedtuple": Helper(shape, mode); diff --git a/runtimes/csharp/src/Nino.Codegen/Templates/typescript/shapes.sbn b/runtimes/csharp/src/Nino.Codegen/Templates/typescript/shapes.sbn index 3dfff0102..88e7259c6 100644 --- a/runtimes/csharp/src/Nino.Codegen/Templates/typescript/shapes.sbn +++ b/runtimes/csharp/src/Nino.Codegen/Templates/typescript/shapes.sbn @@ -76,6 +76,10 @@ func map_ts(s) ret "Map<" + ts(s.key) + ", " + ts(s.value) + ">" end +func grid_ts(s) + ret grid_type(seq_ts(s)) +end + func ts(s) case s.kind when "prim" @@ -109,6 +113,8 @@ func ts(s) ret seq_ts(s) + " | null" when "map" ret map_ts(s) + " | null" + when "grid" + ret grid_ts(s) + " | null" when "type" if s.header == "typeid" || s.header == "ref" || s.header == "union" ret name(s.type) + " | null" @@ -226,7 +232,7 @@ func read(s) ret read(s.inner) + " as " + name(s.enum) when "rawstruct" ret "read" + name(s.struct) + "(r, r.take(" + s.size + "))" - when "rawnullable", "fixedtuple", "seq", "map" + when "rawnullable", "fixedtuple", "seq", "map", "grid" ret helper(s, "read") + "(r" + s.codecs_argument + ")" when "tuple" $parts = [] @@ -263,6 +269,11 @@ end # none): the objects, arrays, maps and sets it holds are reused where they can be (`deserializeInto`), else a new value. func read_into(s, cur) case s.kind + when "grid" + if s.array_type + ret read(s) + end + ret helper(s, "read") + "(r" + s.codecs_argument + ", " + cur + ")" when "seq", "map" if s.array_type ret read(s) @@ -305,7 +316,7 @@ func write(s, v) ret write(s.inner, v) when "rawstruct" ret "write" + name(s.struct) + "(w, " + reserve(s.size, s.zeroed) + ", " + v + ")" - when "rawnullable", "fixedtuple", "seq", "map" + when "rawnullable", "fixedtuple", "seq", "map", "grid" ret helper(s, "write") + "(w, " + v + s.codecs_argument + ")" when "tuple" $parts = [] diff --git a/runtimes/csharp/src/Nino.Codegen/Templates/typescript/types.sbn b/runtimes/csharp/src/Nino.Codegen/Templates/typescript/types.sbn index d17dff304..490b0c2de 100644 --- a/runtimes/csharp/src/Nino.Codegen/Templates/typescript/types.sbn +++ b/runtimes/csharp/src/Nino.Codegen/Templates/typescript/types.sbn @@ -360,9 +360,51 @@ func guard_decl(shape) ret shape.guard ? " const guard = r.keyGuard(length);\n" : "" end +# The grid dimensions take the place of a sequence's count. The elements follow with the same stride. +func grid_helper(h) + $s = h.shape + $t = grid_ts($s) + $e = $s.element + if h.mode == "read" + $reuse = !$s.array_type ? ", cur?: " + $t + " | null" : "" + $min = $e.fixed ? $e.size : 1 + $o = "function " + h.name + h.type_params + "(r: NinoReader" + h.codecs + $reuse + "): " + $t + " | null {\n const shape = r.gridShape(" + $s.rank + ", " + $min + ");\n if (shape === null) return null;\n const { lengths, count } = shape;\n" + if $s.array_type + $o = $o + " if (count > " + $s.inline_length + ") return { lengths, data: r.numbers(" + $s.array_type + ", count)! };\n" + $o = $o + " const values = new " + $s.array_type + "(count);\n" + else + $o = $o + " const reuse = cur != null && lengths.length === cur.lengths.length && lengths.every((n, i) => n === cur.lengths[i]);\n const values = reuse ? cur.data : new Array<" + ts($e) + ">(r.capacity(count));\n" + end + if $e.fixed + $o = $o + " for (let i = 0, at = r.take(count * " + $e.size + "); i < count; i++, at += " + $e.size + ") values[i] = " + read_at($e, 0) + ";\n" + else + $o = $o + " for (let i = 0; i < count; i++) values[i] = " + read_into($e, "values[i]") + ";\n" + end + if !$s.array_type + $o = $o + " if (values.length !== count) values.length = count;\n if (reuse) return cur;\n" + end + ret $o + " return { lengths, data: values };\n}\n" + end + + $o = "function " + h.name + h.type_params + "(w: NinoWriter, grid: " + $t + " | null" + h.codecs + "): void {\n if (grid == null) { w.i32(-1); return; }\n const values = grid.data;\n w.gridShape(" + $s.rank + ", grid.lengths, values.length);\n" + if $s.array_type + $o = $o + " if (values.length > " + $s.inline_length + ") { w.numberBlock(values); return; }\n" + end + $loop = " for (let i = 0; i < values.length; i++) {\n const value = values[i];\n" + if $e.fixed + $o = $o + " let at = " + reserve("values.length * " + $e.size, $e.zeroed) + ";\n" + $loop + " " + stmt(write_at($e, 0, "value")) + "\n at += " + $e.size + ";\n }\n" + else + $o = $o + $loop + " " + stmt(write($e, "value")) + "\n }\n" + end + ret $o + "}\n" +end + # A function shared by every value of one shape. func helper_body(h) $s = h.shape + if $s.kind == "grid" + ret grid_helper(h) + end $n = h.name $o = "" if h.mode == "readinto" diff --git a/runtimes/csharp/tests/Nino.Codegen.Tests/Shapes.cs b/runtimes/csharp/tests/Nino.Codegen.Tests/Shapes.cs index 6f55671be..9b1ca0661 100644 --- a/runtimes/csharp/tests/Nino.Codegen.Tests/Shapes.cs +++ b/runtimes/csharp/tests/Nino.Codegen.Tests/Shapes.cs @@ -178,7 +178,7 @@ public sealed class NullableSlots public List<(int, int?)> Tuples; } - /// Raw nullables as the elements of arrays of two and three dimensions: slots too (TypeScript has no grids). + /// Raw nullables as the elements of arrays of two and three dimensions: slots too. [NinoType] public sealed class NullableGrids { diff --git a/runtimes/csharp/tests/Nino.Codegen.Tests/TargetTests.cs b/runtimes/csharp/tests/Nino.Codegen.Tests/TargetTests.cs index a007494fc..c615882a4 100644 --- a/runtimes/csharp/tests/Nino.Codegen.Tests/TargetTests.cs +++ b/runtimes/csharp/tests/Nino.Codegen.Tests/TargetTests.cs @@ -275,11 +275,13 @@ public void RawNullableSlotsAreGeneratedInEveryLanguage() StringAssert.Contains(ts, " sorted: Set> | null = null;"); StringAssert.Contains(ts, " boxedNested: Box<(Set> | null)[] | null> | null = null;"); StringAssert.Contains(ts, " tuples: ([number, number | null])[] | null = null;"); - StringAssert.Contains(ts, "import { NinoReader, NinoSubtypes, NinoWriter, type NinoCodec, type NinoNullable, type NullableSlot } from"); + StringAssert.Contains(ts, "import { NinoReader, NinoSubtypes, NinoWriter, type NinoCodec, type NinoGrid as NinoGrid$, type NinoNullable, type NullableSlot } from"); StringAssert.Contains(ts, " map: Map | null = null;"); // A set's slots are taken as one run, then each read at its offset. StringAssert.Contains(ts, "for (let i = 0, at = r.take(length * 8); i < length; i++, at += 8) values.add("); - StringAssert.Contains(tsOutput, "Shapes.NullableGrids is not written to TypeScript"); + StringAssert.Contains(ts, " grid: NinoGrid$[]> | null = null;"); + StringAssert.Contains(ts, " cube: NinoGrid$[]> | null = null;"); + Assert.IsFalse(tsOutput.Contains("NullableGrids", StringComparison.Ordinal), tsOutput); var (go, goOutput) = Run("go", "nino_types.go"); Assert.IsTrue(Regex.IsMatch(go, @"\n\tQueue +\[\]nino\.NullableSlot\[int32\] ")); Assert.IsTrue(Regex.IsMatch(go, @"\n\tSorted +\[\]nino\.NullableSlot\[int32\] ")); diff --git a/runtimes/typescript/AGENTS.md b/runtimes/typescript/AGENTS.md index 044480cb0..b33d4a75c 100644 --- a/runtimes/typescript/AGENTS.md +++ b/runtimes/typescript/AGENTS.md @@ -1,25 +1,38 @@ # TypeScript runtime: file map -> Read when: reading or changing the TypeScript runtime (runtimes/typescript: src/nino.ts, its WebAssembly kernels, tests or benchmark). +> Read when: reading or changing the TypeScript runtime (runtimes/typescript: src/runtime/, its single-file bundle, WebAssembly kernels, tests or benchmark). The npm package `nino-serialization` (ES module, Node 15+ for the published build; tests on Node 22.18+ type -stripping): `src/nino.ts` is the whole runtime, embedded in nino-gen (`runtimes/csharp/src/Nino.Codegen`) and written next to the -generated TypeScript. README.md documents it. `audit-runtimes` audits it, `audit-security` its reader. +stripping): edit the modules in `src/runtime/`. The checked-in bundle `src/nino.ts` is the file nino-gen embeds and +writes next to generated TypeScript. The npm package compiles that bundle to `dist/nino.js` and its declarations. +README.md documents it. `audit-runtimes` audits it, `audit-security` its reader. ``` -package.json the package (exports dist/nino.js + .d.ts) and scripts: build, build:wasm, typecheck, test +package.json the package (exports dist/nino.js + .d.ts) and scripts: build, build:bundle, build:wasm, typecheck, test (tsc, then the suite in Node, as a browser, and as a browser without WebAssembly) package-lock.json dev dependencies: typescript, @types/node, fast-check tsconfig.json type checks src, test and wasm (noEmit) tsconfig.build.json builds src/nino.ts into dist (npm run build) LICENSE MIT license text included in the npm package README.md usage, the API, guarantees, tests, benchmarks -src/nino.ts the runtime: reader and writer, strings, collections, depth and deferral, type ids, - reference tracking; embeds the WebAssembly text kernels between wasm:begin / wasm:end +src/ + nino.ts generated single-file bundle: embedded by nino-gen, compiled for npm (do not edit) + runtime/ authoritative modules; index.ts declares the bundle's public API via named re-exports + api.ts codecs, nullable types, serialize and deserialize entry points, ninoVersion + reader.ts, writer.ts wire I/O, collection and reference state, reader scratch buffer and writer slab + deferrals.ts shallow-stack reading and writing of nested bodies + error.ts shared NinoError + keys.ts hash-flooding guard + numbers.ts typed arrays, endianness, shared buffer for numeric blocks + grid.ts rectangular array shape and dimension limits + scalars.ts date and GUID constants + subtypes.ts registry by type id and by class + text.ts Node and JavaScript text paths, Wasm text kernels and loader +scripts/bundle.mjs npm run build:bundle: flattens the modules into src/nino.ts; build and test check it scripts/version.mjs after tsc: writes the package version over the placeholder in dist wasm/ text.wat the WebAssembly kernels (SIMD, GC, JS String Builtins) for text <-> Nino's string bytes - embed.ts npm run build:wasm: assembles text.wat with wasm-tools into src/nino.ts (base64 + SHA-256) + embed.ts npm run build:wasm: assembles text.wat with wasm-tools into src/runtime/text.ts (base64 + SHA-256) test/ primitives.test.ts every primitive's bytes and round trip strings.test.ts both string encodings, Node's and the browser's paths @@ -45,12 +58,13 @@ bench/ the .NET suite's cases (runtimes/csharp/benchmarks) ``` Generated files: `test/generated/*` is rewritten by `NINO_UPDATE_GENERATED=1 dotnet test runtimes/csharp/tests/Nino.Codegen.Tests`; -the embedded module in `src/nino.ts` by `npm run build:wasm`. +the embedded kernels in `src/runtime/text.ts` and the bundle by `npm run build:wasm`. ## TypeScript runtime (runtimes/typescript) -`src/nino.ts` is the runtime Nino.Codegen embeds and nino-gen writes next to the generated TypeScript. The -reader takes hostile input as the Go and Rust ones do: check bounds and lengths before allocating, count depth as .NET -does and defer past it, never build objects whose keys come from the data on a plain object (`__proto__`): use `Map`. +Run `npm run build:bundle` after editing a module. Commit the bundle alongside its source so building Nino.Codegen +requires only .NET. Keep internal imports relative and named. +The reader takes hostile input as the Go and Rust ones do: check bounds and lengths before allocating, count depth +as .NET does and defer past it, and use `Map` for keys from the data (`__proto__`). Before committing: `npm ci && npm test` (type check and the `node:test` suite) in `runtimes/typescript`, and the `Nino.Codegen.Integration.Tests` and `Nino.Codegen.Tests` .NET tests. diff --git a/runtimes/typescript/README.md b/runtimes/typescript/README.md index f68a224c1..9b86bf1bf 100644 --- a/runtimes/typescript/README.md +++ b/runtimes/typescript/README.md @@ -1,7 +1,7 @@ # Nino for TypeScript -`src/nino.ts` is the TypeScript runtime of Nino: it reads and writes the bytes Nino writes in .NET (the format is -[docs/spec/wire-format.md](../../docs/spec/wire-format.md)). nino-gen writes it next to the classes and codecs it +The TypeScript runtime of Nino reads and writes the bytes Nino writes in .NET (the format is +[docs/spec/wire-format.md](../../docs/spec/wire-format.md)). nino-gen writes the single file `nino.ts` next to the classes and codecs it generates for a project's `[NinoType]`s; each release also publishes it to npm as `nino-serialization`, with Nino's version, which generated code imports instead with `Runtime="nino-serialization"` (`npm install nino-serialization@4.0.0-rc.10`). How to generate the code and the options are in the guide's @@ -88,6 +88,16 @@ element. The reader copies from an aligned view of the data when the data is ali bytes. What it returns never refers to the data: typed arrays of 65 bytes to 8 KB are views of a shared 64 KB buffer (as Node's small `Buffer`s share a pool, since an `ArrayBuffer` for each costs more than the copy). +JavaScript engines may canonicalize a NaN held in a `number`, so a floating-point NaN can round-trip with a +different sign or payload when read into a plain array. + +## Rectangular arrays + +A .NET rectangular array of rank 2 to 4 is a `NinoGrid | null`. Its `lengths` hold the dimensions in order, +and its `data` is flat, with the last index varying fastest. An `int[,]` uses `NinoGrid`, and an +`int?[,]` uses `NinoGrid[]>`. Numeric grid elements use typed storage in either numeric-array +mode. The writer checks that the product of the dimensions equals the length of `data`. + ## Guarantees The reader takes untrusted input: what every runtime guarantees (bounds, depth, type ids, strict bytes, trailing bytes) @@ -119,18 +129,24 @@ The module is compiled synchronously the first time it is needed, and its paths JavaScript ones. `npm run build:wasm` assembles `wasm/text.wat` with [wasm-tools](https://github.com/bytecodealliance/wasm-tools) -(`wasm-tools parse`, then `strip --all`) and writes the module into `nino.ts`, with the SHA-256 of the `text.wat` it -came from (`wasm/embed.ts`). Install wasm-tools with `cargo install --locked wasm-tools`, or put the binary of a +(`wasm-tools parse`, then `strip --all`) and writes the module and the SHA-256 of its source into +`src/runtime/text.ts` (`wasm/embed.ts`), then rebuilds `src/nino.ts`. Install wasm-tools with `cargo install --locked wasm-tools`, or put the binary of a [release](https://github.com/bytecodealliance/wasm-tools/releases) on the `PATH`. Only a change to `text.wat` needs it: the tests check the hash, and rebuild and compare the module byte for byte where wasm-tools is installed. +## Runtime development + +Edit the modules under `src/runtime/`, then run `npm run build:bundle` to refresh the checked-in `src/nino.ts`. +The npm build compiles this bundle into `dist/nino.js` and `dist/nino.d.ts`. nino-gen embeds the same bundle, +so building the .NET tool needs only the .NET SDK. Keep the bundle and its source changes in the same commit. + ## Tests ```sh npm ci && npm test ``` -type-checks and runs the `node:test` suite in `test/` three times: in Node, then as a browser runs it (the runtime +checks the bundle, type-checks the source and runs the `node:test` suite in `test/` three times: in Node, then as a browser runs it (the runtime evaluated without `Buffer`, `NINO_TEST_RUNTIME=browser`, `test/runtime.ts`), with the WebAssembly module and without it (`NINO_WASM=0`). `test/flooding.test.ts` reads sets and maps of keys V8 puts in one bucket. `test/wasm.test.ts` compares the module's paths with the JavaScript ones for every length up to 256 and longer, with every kind of char at each position. `test/corpus.test.ts` runs the conformance corpus diff --git a/runtimes/typescript/package.json b/runtimes/typescript/package.json index 1545476e9..fa210efb0 100644 --- a/runtimes/typescript/package.json +++ b/runtimes/typescript/package.json @@ -35,10 +35,11 @@ "node": ">=15" }, "scripts": { - "build": "tsc -p tsconfig.build.json && node scripts/version.mjs", - "build:wasm": "node wasm/embed.ts", + "build": "node scripts/bundle.mjs --check && tsc -p tsconfig.build.json && node scripts/version.mjs", + "build:bundle": "node scripts/bundle.mjs", + "build:wasm": "node wasm/embed.ts && npm run build:bundle", "typecheck": "tsc -p .", - "test": "tsc -p . && npm run test:node && npm run test:browser && npm run test:no-wasm", + "test": "node scripts/bundle.mjs --check && tsc -p . && npm run test:node && npm run test:browser && npm run test:no-wasm", "test:node": "node --test \"test/**/*.test.ts\"", "test:browser": "NINO_TEST_RUNTIME=browser node --import ./test/runtime.ts --test \"test/**/*.test.ts\"", "test:no-wasm": "NINO_TEST_RUNTIME=browser NINO_WASM=0 node --import ./test/runtime.ts --test \"test/**/*.test.ts\"", diff --git a/runtimes/typescript/scripts/bundle.mjs b/runtimes/typescript/scripts/bundle.mjs new file mode 100644 index 000000000..f0295af97 --- /dev/null +++ b/runtimes/typescript/scripts/bundle.mjs @@ -0,0 +1,44 @@ +// Keep the runtime as one scope for V8 and one TypeScript file for nino-gen's embedded resource. +import { readFileSync, writeFileSync } from "node:fs"; + +const root = new URL("../src/", import.meta.url); +const readModule = (name) => readFileSync(new URL("runtime/" + name, root), "utf8"); +const entry = readModule("index.ts"); +const exports = new Map(); +for (const [, names, file] of entry.matchAll(/^export \{([^}]+)\} from "\.\/([\w-]+\.ts)";$/gm)) { + exports.set(file, new Set(names.split(",").map((name) => name.trim().replace(/^type /, "")))); +} + +const modules = new Set(); +const sections = []; +function append(file) { + if (modules.has(file)) return; + modules.add(file); + const source = readModule(file); + const imports = /^import (?:type )?\{[^}]+\} from "\.\/([\w-]+\.ts)";\n/gm; + for (const [, dependency] of source.matchAll(imports)) append(dependency); + + // Preserve the original declarations and doc comments. Only the index's exports are public in the bundle. + const body = source.replace(imports, "").replace( + /^export ((?:const|let|type|interface|class|function) (\w+))/gm, + (declaration, text, name) => exports.get(file)?.has(name) ? declaration : text, + ).trim(); + if (/^(?:import |export (?!const |let |type |interface |class |function ))/m.test(body)) { + throw new Error(`${file}: use named imports and declaration exports in the runtime bundle`); + } + sections.push(body); +} + +for (const file of exports.keys()) append(file); +const header = `// Nino runtime for TypeScript (5.7 or later, for the typed arrays' buffer types). +// Generated from src/runtime/ by npm run build:bundle. nino-gen writes this file next to the generated types.`; +const bundle = header + "\n\n" + sections.join("\n\n") + "\n"; +const path = new URL("nino.ts", root); + +if (process.argv.includes("--check")) { + if (readFileSync(path, "utf8") !== bundle) { + throw new Error("src/nino.ts is out of date: run npm run build:bundle"); + } +} else { + writeFileSync(path, bundle); +} diff --git a/runtimes/typescript/src/nino.ts b/runtimes/typescript/src/nino.ts index 632296f1c..85dba3299 100644 --- a/runtimes/typescript/src/nino.ts +++ b/runtimes/typescript/src/nino.ts @@ -1,226 +1,5 @@ -// Nino runtime for TypeScript (5.7 or later, for the typed arrays' buffer types), written by nino-gen (Nino.Codegen) next to the generated types: reads and writes the bytes -// Nino writes in .NET. Little-endian and unaligned; lengths are int32, -1 = null; string headers take 1, 3 or 5 bytes. Do not edit: it is overwritten on -// every build. - -/** - * The Nino version of this runtime: nino-gen's for the copy it writes next to the generated types (which expect the - * same one), the package's for the npm package (scripts/version.mjs). - */ -export const ninoVersion = "__NINO_VERSION__"; - -/** Reads and writes one type's values. Generated for every [NinoType]. */ -export interface NinoCodec { - read(reader: NinoReader): T; - write(writer: NinoWriter, value: T): void; - /** - * Reads a value into `value` where it can (see `deserializeInto`) and returns the value read: `value` itself when it - * was reused. Optional: a codec without it reads a new value. - */ - readInto?(reader: NinoReader, value: T): T; -} - -let shared: NinoWriter | null = null; -/** The smallest buffer `serialize` writes its results into (see `NinoWriter.next`). */ -const slabSize = 64 * 1024; - -/** - * Serializes `value` with `codec` (what `NinoSerializer.Serialize` writes in .NET) into a new array. Results are - * written one after another into a shared buffer and returned as views of it, never copied or overwritten (as - * msgpackr does, and as Node's `Buffer`s share a pool): a new `ArrayBuffer` for every result costs more than most - * serializations. Read a result by its `byteOffset` and `length`, not through `.buffer`. - */ -export function serialize(codec: NinoCodec, value: T): Uint8Array { - // A codec that serializes (a custom one) while this runs gets a writer of its own. - const writer = shared ?? new NinoWriter(); - shared = null; - try { - writer.next(); - codec.write(writer, value); - return writer.detach(); - } finally { - if (writer.capacity <= 1 << 20) shared = writer; - } -} - -/** The writer `serializeInto` writes a `Uint8Array`'s value with: null while it is in use, or before the first call. */ -let scratchWriter: NinoWriter | null = null; - -/** - * Serializes `value` with `codec` into memory the caller owns, and returns the value's size in bytes: - * - * - into a `NinoWriter`, after what it holds (what `NinoSerializer.Serialize(value, bufferWriter)` does in .NET), - * growing it as needed; `written()` views the bytes until the writer writes again. A writer reused with `reset` keeps - * its buffer, so once it is large enough writing allocates no memory at all: no new `ArrayBuffer` per value, which - * V8 counts toward a full garbage collection (about every 64 MB of them in Node 24) until a scavenge frees them. If - * `codec` throws, the writer is left as it was before the call. - * - into a `Uint8Array`, from its start, when the value fits. A size larger than `target.length` means it did not: - * `target` is then unchanged, and a call with that many bytes succeeds. - * - * Not for a writer that is writing a value (from a custom codec): references and depth are counted per call. - */ -export function serializeInto(codec: NinoCodec, value: T, target: NinoWriter | Uint8Array): number { - if (target instanceof NinoWriter) { - const start = target.pos; - target["begin"](); - try { - codec.write(target, value); - } catch (e) { - target.pos = start; - throw e; - } - return target.pos - start; - } - // A codec that serializes (a custom one) while this runs gets a writer of its own. - const writer = scratchWriter ?? new NinoWriter(); - scratchWriter = null; - try { - writer.reset(); - codec.write(writer, value); - const size = writer.pos; - if (size <= target.length) target.set(writer.written()); - return size; - } finally { - if (writer.capacity <= 1 << 20) scratchWriter = writer; - } -} - -/** - * Deserializes one value written by `NinoSerializer.Serialize` (or `serialize`). Nothing it returns refers to - * `data`, which it does not change. Bytes after the value are not read (see `deserializeExact`). - */ -export function deserialize(codec: NinoCodec, data: Uint8Array): T { - return readValue(codec, data, false); -} - -/** `deserialize` that also throws a `NinoError` when bytes follow the value. */ -export function deserializeExact(codec: NinoCodec, data: Uint8Array): T { - return readValue(codec, data, true); -} - -/** - * Deserializes one value into `value`, as `NinoDeserializer.Deserialize(data, ref value)` does in .NET, and returns - * the value read: the members of objects are read into the objects `value` holds (of the same class), arrays keep - * their storage and read their elements into the old ones by index, maps and sets are cleared and refilled, and a - * polymorphic member is read into only when the data holds the same class (tracked objects are read new). Bytes after - * the value are not read. If it throws, `value` holds what was read before the error, the rest as it was. - */ -export function deserializeInto(codec: NinoCodec, data: Uint8Array, value: T): T { - return readValue({ read: (r) => r.into(codec, value), write: codec.write }, data, false); -} - -function readValue(codec: NinoCodec, data: Uint8Array, exact: boolean): T { - let reader = scratchReader; - if (reader === null || data.length > scratchSize) { - if (reader !== null || scratchMade || data.length > scratchSize) { - return readAll(codec, new NinoReader(data), exact ? data.length : -1); - } - reader = makeScratch(); - } - // A codec that deserializes (a custom one) while this runs gets a reader of its own. - scratchReader = null; - try { - reader["load"](data); - return readAll(codec, reader, exact ? data.length : -1); - } finally { - scratchReader = reader; - } -} - -/** One value from `reader`, which must then be at `end` (the length of the data), unless `end` is -1. */ -function readAll(codec: NinoCodec, reader: NinoReader, end: number): T { - const value = codec.read(reader); - if (end >= 0 && reader.pos !== end) throw new NinoError(`${end - reader.pos} bytes after the value.`); - return value; -} - -/** - * Values up to this size are copied into the bytes of one reader that `deserialize` reuses: a copy costs less than - * the `DataView` a new reader makes (about 75 ns in Node 22, 50 in Chromium), which is most of the time of a small - * value. - */ -const scratchSize = 4096; -/** The reader `deserialize` reuses: null while it is in use, or before the first call made it. */ -let scratchReader: NinoReader | null = null; -let scratchMade = false; - -/** The reader `deserialize` reuses: its bytes are in the kernels' memory when they are used, so text needs no copy. */ -function makeScratch(): NinoReader { - scratchMade = true; - const k = nodeText === null ? wasm() : null; - return new NinoReader(k !== null ? new Uint8Array(k.memory.buffer, 0, scratchSize) : new Uint8Array(scratchSize)); -} - -/** - * A member that is .NET's `NinoNullable` (`Nino.Core`): the value or `null`, as a `T?` member is (`T | null`), under - * the name that says which bytes it has: its memory wherever it is, a presence and a value of a `T` each - * (`NinoReader.ninoNullableAt`), where a `T?` is a presence byte and the value, or a slot in a sequence - * (`NullableSlot`). An alias only: no wrapper object and nothing at run time. - */ -export type NinoNullable = T | null; - -/** - * A .NET `T?` of a fixed-size `T` (a number, a date, a raw struct) as the element of a sequence: the value or `null`, - * under the name that says which bytes it has: a slot of `T`'s alignment plus its size in every sequence, the presence - * byte first, zeros up to the alignment, then the value, zeros when absent. `NullableSlot[]` is an `int?[]`, a - * `List` or a `Queue`, `Set>` a `HashSet`. A single `T?` (a member, a map's - * key or value, a tuple's item) is not these bytes: it is a presence byte and the value only when present, declared - * `T | null`. An alias only: no wrapper object and nothing at run time. - */ -export type NullableSlot = T | null; - -/** - * A typed array of a fixed-size number type: how generated code holds an array or list of `sbyte`, `byte`, `short`, - * `ushort`, `int`, `uint`, `long`, `ulong`, `float` or `double` (`NinoReader.numbers`, `NinoWriter.numbers`). - */ -export type NinoNumbers = Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | - BigInt64Array | BigUint64Array | Float32Array | Float64Array; - -/** The constructor of a `NinoNumbers` type (`Int32Array`, ...). */ -export interface NinoNumbersType { - readonly BYTES_PER_ELEMENT: number; - new (length: number): T; - new (buffer: ArrayBuffer, byteOffset: number, length: number): T; -} - -/** Whether this host stores numbers little-endian, as Nino writes them: typed arrays are then copied as bytes. */ -const littleEndian = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; - -/** Reverses the bytes of each `size`-byte element in `bytes` from `at` to `end`: Nino's order and a big-endian host's. */ -function swapBytes(bytes: Uint8Array, at: number, end: number, size: number): void { - for (; at < end; at += size) { - for (let i = at, j = at + size - 1; i < j; i++, j--) { - const b = bytes[i]; - bytes[i] = bytes[j]; - bytes[j] = b; - } - } -} - -/** - * Typed arrays `NinoReader.numbers` reads up to this many bytes are views of a shared buffer (numbersSlab bytes), as - * Node's small `Buffer`s share a pool: one over 64 bytes has its memory outside V8's heap, and allocating that costs - * more than the copy (in Node 22 about 2 µs for 1,000 int32s against 0.6 µs for a pool view). Generated code reads - * those of up to 64 bytes one element at a time into a typed array of their own, which V8 keeps on its heap: viewing - * such an array's bytes (`.buffer`) allocates outside memory for it, which made reading 4 int64s 5 times slower than - * reading them into an array (test branch 97deeca). - */ -const numbersPooled = 8192; -const numbersSlab = 64 * 1024; -let numbersBuffer = new ArrayBuffer(0); -let numbersBytes = new Uint8Array(0); -let numbersPos = 0; - -/** Where `bytes` bytes start in the shared buffer (8-byte aligned, as a view must be aligned to its elements). */ -function poolNumbers(bytes: number): number { - let at = numbersPos; - if (bytes > numbersBytes.length - at) { - numbersBuffer = new ArrayBuffer(numbersSlab); - numbersBytes = new Uint8Array(numbersBuffer); - at = 0; - } - numbersPos = (at + bytes + 7) & ~7; - return at; -} +// Nino runtime for TypeScript (5.7 or later, for the typed arrays' buffer types). +// Generated from src/runtime/ by npm run build:bundle. nino-gen writes this file next to the generated types. /** Thrown for data that is not a valid value of the type read, or a value that cannot be written. */ export class NinoError extends Error { @@ -230,60 +9,6 @@ export class NinoError extends Error { } } -// ignoreBOM keeps a leading U+FEFF, which is text in Nino. -const utf8Decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); -const utf8Encoder = new TextEncoder(); - -/** - * The bytes a string header (below 2^32, wire-format spec §2.3.1) takes: 1 below 0x80 (the value itself), 3 up to - * 0xFFFF (0x80 and a uint16), else 5 (0x81 and a uint32). - */ -function headerSize(value: number): number { - return value < 0x80 ? 1 : value <= 0xffff ? 3 : 5; -} -/** Browsers decode "latin1" as windows-1252, which differs from Latin-1 in 0x80-0x9F (see `decodeLatin1`). */ -const latin1Decoder = new TextDecoder("latin1"); -/** Replaces unpaired surrogates with U+FFFD, which .NET keeps (see `decodeUtf16`). */ -const utf16Decoder = new TextDecoder("utf-16le", { ignoreBOM: true }); -/** A char wider than a byte. A string without one is one byte per char in Nino. */ -const wide = /[^\x00-\xff]/; -/** A char outside ASCII. */ -const nonAscii = /[^\x00-\x7f]/; -/** Milliseconds between 0001-01-01 and 1970-01-01. */ -const unixEpochMilliseconds = 62135596800000; -/** Milliseconds between 0001-01-01 and 10000-01-01: past `DateTime.MaxValue`. */ -const maxDateMilliseconds = 315537897600000; -/** The char codes of each byte's high and low hex digit. */ -const hexHigh = Uint8Array.from({ length: 256 }, (_, i) => "0123456789abcdef".charCodeAt(i >> 4)); -const hexLow = Uint8Array.from({ length: 256 }, (_, i) => "0123456789abcdef".charCodeAt(i & 15)); -/** The value of each hex digit by its char code, else -1. */ -const hexValues = Int8Array.from({ length: 128 }, (_, c) => - c >= 48 && c <= 57 ? c - 48 : (c | 32) >= 97 && (c | 32) <= 102 ? (c | 32) - 87 : -1); -/** Chars per `String.fromCharCode` call, well under any engine's argument limit. */ -const chunk = 4096; -/** - * With Node's methods, text longer than this is written by a native call (`latin1Write`, `ucs2Write`, after a regex - * for chars past U+00FF); shorter text is narrowed char by char in JavaScript, which costs less up to about 48 chars - * on x64 and Arm64 (32 and 64 measured the same, 8 took twice as long on short text). - */ -const shortText = 48; -/** Without Node's methods, the longest text read and written in JavaScript: TextDecoder and TextEncoder cost more. */ -const mediumText = 32; -/** - * Without Node's methods, the longest text written in JavaScript: a `TextEncoder.encodeInto` call costs about as - * much as writing 300 chars in Chromium. - */ -const loopText = 256; -/** - * With Node's methods, the longest text sliced from the reader's decoded window. V8 copies a substring this short - * into a plain string; a longer one would be a slice of the window, slower to write or test with a regex later. - */ -const textSlice = 12; -/** The window's largest size. */ -const textWindow = 4096; -/** The char codes of a text being read, passed to `String.fromCharCode` at once. */ -const codes: number[] = []; - /** * Open class bodies after which the next one is deferred, as `NinoDepth.Inline` in .NET: its slot gets the instance * now and its body is written and read later, from a shallow point (see "Deep nesting" in @@ -324,6 +49,20 @@ class NinoDeferrals { } } +function tooDeep(): NinoError { + return new NinoError(`data nested deeper than ${maxDepth} bodies.`); +} + +/** A rectangular array's dimensions and its flat data, with the last index varying fastest. */ +export interface NinoGrid> { + readonly lengths: readonly number[]; + data: T; +} + +// .NET's Array.MaxLength and the maximum product of the dimensions (wire-format spec §9.13). +const maxGridLength = 0x7fff_ffc7; +const maxGridElements = 0xffff_ffff; + /** * The most keys a key read from the data may find in its bucket of the `Map` or `Set` it goes into, as * `NinoSettings.MaxHashCollisions`'s default in .NET. See `NinoKeyGuard`. @@ -332,13 +71,6 @@ const maxHashCollisions = 100; /** Maps and sets of up to this many keys are not guarded: their keys cannot cost more than this many probes each. */ const guardedKeys = 128; -/** - * What the collections of one read may allocate ahead of their elements (`NinoReader.capacity`): 16 bytes per byte of - * data plus 16 KB, an element counted as 8 bytes (an array slot), as the Go and Rust readers budget a read. - */ -const presizePerByte = 16; -const presizeFloor = 16384; - /** * Bounds what keys read from the data cost a `Map` or `Set` (hash flooding), as `NinoSettings.MaxHashCollisions` * does in .NET. V8 hashes strings with a per-process seed, but numbers and bigints without one (its @@ -487,17 +219,130 @@ function longHash(hi: number, lo: number): number { return l & 0x3FFFFFFF; } -/** A key of a type known only at run time through `guard`: numbers, bigints and strings (see `NinoKeyGuard`). */ -function guardKey(guard: NinoKeyGuard, key: K): K { - if (typeof key === "number") guard.number(key); - else if (typeof key === "bigint") guard.bigint(key); - else if (typeof key === "string") guard.string(key); - return key; -} +/** A key of a type known only at run time through `guard`: numbers, bigints and strings (see `NinoKeyGuard`). */ +function guardKey(guard: NinoKeyGuard, key: K): K { + if (typeof key === "number") guard.number(key); + else if (typeof key === "bigint") guard.bigint(key); + else if (typeof key === "string") guard.string(key); + return key; +} + +/** + * A typed array of a fixed-size number type: how generated code holds an array or list of `sbyte`, `byte`, `short`, + * `ushort`, `int`, `uint`, `long`, `ulong`, `float` or `double` (`NinoReader.numbers`, `NinoWriter.numbers`). + */ +export type NinoNumbers = Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | + BigInt64Array | BigUint64Array | Float32Array | Float64Array; + +/** The constructor of a `NinoNumbers` type (`Int32Array`, ...). */ +export interface NinoNumbersType { + readonly BYTES_PER_ELEMENT: number; + new (length: number): T; + new (buffer: ArrayBuffer, byteOffset: number, length: number): T; +} + +/** Whether this host stores numbers little-endian, as Nino writes them: typed arrays are then copied as bytes. */ +const littleEndian = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; + +/** Reverses the bytes of each `size`-byte element in `bytes` from `at` to `end`: Nino's order and a big-endian host's. */ +function swapBytes(bytes: Uint8Array, at: number, end: number, size: number): void { + for (; at < end; at += size) { + for (let i = at, j = at + size - 1; i < j; i++, j--) { + const b = bytes[i]; + bytes[i] = bytes[j]; + bytes[j] = b; + } + } +} + +/** + * Typed arrays `NinoReader.numbers` reads up to this many bytes are views of a shared buffer (numbersSlab bytes), as + * Node's small `Buffer`s share a pool: one over 64 bytes has its memory outside V8's heap, and allocating that costs + * more than the copy (in Node 22 about 2 µs for 1,000 int32s against 0.6 µs for a pool view). Generated code reads + * those of up to 64 bytes one element at a time into a typed array of their own, which V8 keeps on its heap: viewing + * such an array's bytes (`.buffer`) allocates outside memory for it, which made reading 4 int64s 5 times slower than + * reading them into an array (test branch 97deeca). + */ +const numbersPooled = 8192; +const numbersSlab = 64 * 1024; +let numbersBuffer = new ArrayBuffer(0); +let numbersBytes = new Uint8Array(0); +let numbersPos = 0; + +/** Where `bytes` bytes start in the shared buffer (8-byte aligned, as a view must be aligned to its elements). */ +function poolNumbers(bytes: number): number { + let at = numbersPos; + if (bytes > numbersBytes.length - at) { + numbersBuffer = new ArrayBuffer(numbersSlab); + numbersBytes = new Uint8Array(numbersBuffer); + at = 0; + } + numbersPos = (at + bytes + 7) & ~7; + return at; +} + +/** Milliseconds between 0001-01-01 and 1970-01-01. */ +const unixEpochMilliseconds = 62135596800000; +/** Milliseconds between 0001-01-01 and 10000-01-01: past `DateTime.MaxValue`. */ +const maxDateMilliseconds = 315537897600000; +/** The char codes of each byte's high and low hex digit. */ +const hexHigh = Uint8Array.from({ length: 256 }, (_, i) => "0123456789abcdef".charCodeAt(i >> 4)); +const hexLow = Uint8Array.from({ length: 256 }, (_, i) => "0123456789abcdef".charCodeAt(i & 15)); +/** The value of each hex digit by its char code, else -1. */ +const hexValues = Int8Array.from({ length: 128 }, (_, c) => + c >= 48 && c <= 57 ? c - 48 : (c | 32) >= 97 && (c | 32) <= 102 ? (c | 32) - 87 : -1); -function tooDeep(): NinoError { - return new NinoError(`data nested deeper than ${maxDepth} bodies.`); +/** + * Values up to this size are copied into the bytes of one reader that `deserialize` reuses: a copy costs less than + * the `DataView` a new reader makes (about 75 ns in Node 22, 50 in Chromium), which is most of the time of a small + * value. + */ +const scratchSize = 4096; + +// ignoreBOM keeps a leading U+FEFF, which is text in Nino. +const utf8Decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); +const utf8Encoder = new TextEncoder(); + +/** + * The bytes a string header (below 2^32, wire-format spec §2.3.1) takes: 1 below 0x80 (the value itself), 3 up to + * 0xFFFF (0x80 and a uint16), else 5 (0x81 and a uint32). + */ +function headerSize(value: number): number { + return value < 0x80 ? 1 : value <= 0xffff ? 3 : 5; } +/** Browsers decode "latin1" as windows-1252, which differs from Latin-1 in 0x80-0x9F (see `decodeLatin1`). */ +const latin1Decoder = new TextDecoder("latin1"); +/** Replaces unpaired surrogates with U+FFFD, which .NET keeps (see `decodeUtf16`). */ +const utf16Decoder = new TextDecoder("utf-16le", { ignoreBOM: true }); +/** A char wider than a byte. A string without one is one byte per char in Nino. */ +const wide = /[^\x00-\xff]/; +/** A char outside ASCII. */ +const nonAscii = /[^\x00-\x7f]/; + +/** Chars per `String.fromCharCode` call, well under any engine's argument limit. */ +const chunk = 4096; +/** + * With Node's methods, text longer than this is written by a native call (`latin1Write`, `ucs2Write`, after a regex + * for chars past U+00FF); shorter text is narrowed char by char in JavaScript, which costs less up to about 48 chars + * on x64 and Arm64 (32 and 64 measured the same, 8 took twice as long on short text). + */ +const shortText = 48; +/** Without Node's methods, the longest text read and written in JavaScript: TextDecoder and TextEncoder cost more. */ +const mediumText = 32; +/** + * Without Node's methods, the longest text written in JavaScript: a `TextEncoder.encodeInto` call costs about as + * much as writing 300 chars in Chromium. + */ +const loopText = 256; +/** + * With Node's methods, the longest text sliced from the reader's decoded window. V8 copies a substring this short + * into a plain string; a longer one would be a slice of the window, slower to write or test with a regex later. + */ +const textSlice = 12; +/** The window's largest size. */ +const textWindow = 4096; +/** The char codes of a text being read, passed to `String.fromCharCode` at once. */ +const codes: number[] = []; /** The native Latin-1 and UTF-16 text methods of Node's `Buffer` (Bun's and Deno's too), called on a Uint8Array. */ interface NodeText { @@ -788,6 +633,49 @@ function decodeShortUtf16(v: DataView, at: number, length: number): string { } } +function readValue(codec: NinoCodec, data: Uint8Array, exact: boolean): T { + let reader = scratchReader; + if (reader === null || data.length > scratchSize) { + if (reader !== null || scratchMade || data.length > scratchSize) { + return readAll(codec, new NinoReader(data), exact ? data.length : -1); + } + reader = makeScratch(); + } + // A codec that deserializes (a custom one) while this runs gets a reader of its own. + scratchReader = null; + try { + reader["load"](data); + return readAll(codec, reader, exact ? data.length : -1); + } finally { + scratchReader = reader; + } +} + +/** One value from `reader`, which must then be at `end` (the length of the data), unless `end` is -1. */ +function readAll(codec: NinoCodec, reader: NinoReader, end: number): T { + const value = codec.read(reader); + if (end >= 0 && reader.pos !== end) throw new NinoError(`${end - reader.pos} bytes after the value.`); + return value; +} + +/** The reader `deserialize` reuses: null while it is in use, or before the first call made it. */ +let scratchReader: NinoReader | null = null; +let scratchMade = false; + +/** The reader `deserialize` reuses: its bytes are in the kernels' memory when they are used, so text needs no copy. */ +function makeScratch(): NinoReader { + scratchMade = true; + const k = nodeText === null ? wasm() : null; + return new NinoReader(k !== null ? new Uint8Array(k.memory.buffer, 0, scratchSize) : new Uint8Array(scratchSize)); +} + +/** + * What the collections of one read may allocate ahead of their elements (`NinoReader.capacity`): 16 bytes per byte of + * data plus 16 KB, an element counted as 8 bytes (an array slot), as the Go and Rust readers budget a read. + */ +const presizePerByte = 16; +const presizeFloor = 16384; + /** * Reads values from bytes written by Nino. Generated code reads a run of fixed-size values with one `take`, then * each value from `view` at its offset. @@ -945,6 +833,25 @@ export class NinoReader { return length; } + /** Reads a rectangular array's dimensions and checked element count. A first dimension of -1 is null. */ + gridShape(rank: number, minSize: number): { lengths: number[]; count: number } | null { + const first = this.i32(); + if (first === -1) return null; + if (first < 0 || first > maxGridLength) throw new NinoError(`invalid length ${first}.`); + const lengths = [first]; + let count = first; + for (let i = 1; i < rank; i++) { + const length = this.i32(); + if (length < 0 || length > maxGridLength) throw new NinoError(`invalid length ${length}.`); + lengths.push(length); + count *= length; + if (count > maxGridElements) throw new NinoError("invalid grid dimensions."); + } + // A later zero can make the grid empty. Check the remaining bytes once all dimensions are known. + if (count * Math.max(minSize, 1) > this.end - this.pos) throw new NinoError("invalid grid dimensions."); + return { lengths, count }; + } + /** * A string header (wire-format spec §2.3.1): its first byte gives its size, as MessagePack's string markers do: * the value itself below 0x80, else 0x80 and a uint16 or 0x81 and a uint32 (little-endian), minimal. One byte @@ -1442,6 +1349,9 @@ export class NinoReader { } } +/** The smallest buffer `serialize` writes its results into (see `NinoWriter.next`). */ +const slabSize = 64 * 1024; + /** * Writes values in Nino's format. Generated code writes a run of fixed-size values with one `reserve`, then each * value into `view` at its offset. @@ -1857,13 +1767,32 @@ export class NinoWriter { /** An array or list of a fixed-size number type (`int[]`, `List`...): length, then its bytes as one block. */ numbers(values: NinoNumbers | null): void { if (values === null || values === undefined) { this.i32(-1); return; } - const length = values.length, bytes = values.byteLength; - this.i32(length); + this.i32(values.length); + this.numberBlock(values); + } + + /** Writes a block of fixed-size numbers without a collection length. */ + numberBlock(values: NinoNumbers): void { + const bytes = values.byteLength; const at = this.reserve(bytes); this.buffer.set(new Uint8Array(values.buffer, values.byteOffset, bytes), at); if (!littleEndian) swapBytes(this.buffer, at, at + bytes, values.BYTES_PER_ELEMENT); } + /** Writes exactly `rank` dimensions whose product equals the size of the rectangular array's flat data. */ + gridShape(rank: number, lengths: readonly number[], count: number): void { + if (lengths.length !== rank) throw new NinoError("invalid grid rank."); + let total = 1; + for (const length of lengths) { + if (!Number.isInteger(length) || length < 0 || length > maxGridLength) + throw new NinoError(`invalid length ${length}.`); + total *= length; + if (total > maxGridElements) throw new NinoError("invalid grid dimensions."); + } + if (total !== count) throw new NinoError("grid dimensions do not match the data length."); + for (const length of lengths) this.i32(length); + } + array(values: readonly T[] | null, write: (writer: NinoWriter, value: T) => void): void { if (values === null || values === undefined) { this.i32(-1); return; } @@ -2022,6 +1951,128 @@ export class NinoWriter { } } +/** + * The Nino version of this runtime: nino-gen's for the copy it writes next to the generated types (which expect the + * same one), the package's for the npm package (scripts/version.mjs). + */ +export const ninoVersion = "__NINO_VERSION__"; + +/** Reads and writes one type's values. Generated for every [NinoType]. */ +export interface NinoCodec { + read(reader: NinoReader): T; + write(writer: NinoWriter, value: T): void; + /** + * Reads a value into `value` where it can (see `deserializeInto`) and returns the value read: `value` itself when it + * was reused. Optional: a codec without it reads a new value. + */ + readInto?(reader: NinoReader, value: T): T; +} + +let shared: NinoWriter | null = null; + +/** + * Serializes `value` with `codec` (what `NinoSerializer.Serialize` writes in .NET) into a new array. Results are + * written one after another into a shared buffer and returned as views of it, never copied or overwritten (as + * msgpackr does, and as Node's `Buffer`s share a pool): a new `ArrayBuffer` for every result costs more than most + * serializations. Read a result by its `byteOffset` and `length`, not through `.buffer`. + */ +export function serialize(codec: NinoCodec, value: T): Uint8Array { + // A codec that serializes (a custom one) while this runs gets a writer of its own. + const writer = shared ?? new NinoWriter(); + shared = null; + try { + writer.next(); + codec.write(writer, value); + return writer.detach(); + } finally { + if (writer.capacity <= 1 << 20) shared = writer; + } +} + +/** The writer `serializeInto` writes a `Uint8Array`'s value with: null while it is in use, or before the first call. */ +let scratchWriter: NinoWriter | null = null; + +/** + * Serializes `value` with `codec` into memory the caller owns, and returns the value's size in bytes: + * + * - into a `NinoWriter`, after what it holds (what `NinoSerializer.Serialize(value, bufferWriter)` does in .NET), + * growing it as needed; `written()` views the bytes until the writer writes again. A writer reused with `reset` keeps + * its buffer, so once it is large enough writing allocates no memory at all: no new `ArrayBuffer` per value, which + * V8 counts toward a full garbage collection (about every 64 MB of them in Node 24) until a scavenge frees them. If + * `codec` throws, the writer is left as it was before the call. + * - into a `Uint8Array`, from its start, when the value fits. A size larger than `target.length` means it did not: + * `target` is then unchanged, and a call with that many bytes succeeds. + * + * Not for a writer that is writing a value (from a custom codec): references and depth are counted per call. + */ +export function serializeInto(codec: NinoCodec, value: T, target: NinoWriter | Uint8Array): number { + if (target instanceof NinoWriter) { + const start = target.pos; + target["begin"](); + try { + codec.write(target, value); + } catch (e) { + target.pos = start; + throw e; + } + return target.pos - start; + } + // A codec that serializes (a custom one) while this runs gets a writer of its own. + const writer = scratchWriter ?? new NinoWriter(); + scratchWriter = null; + try { + writer.reset(); + codec.write(writer, value); + const size = writer.pos; + if (size <= target.length) target.set(writer.written()); + return size; + } finally { + if (writer.capacity <= 1 << 20) scratchWriter = writer; + } +} + +/** + * Deserializes one value written by `NinoSerializer.Serialize` (or `serialize`). Nothing it returns refers to + * `data`, which it does not change. Bytes after the value are not read (see `deserializeExact`). + */ +export function deserialize(codec: NinoCodec, data: Uint8Array): T { + return readValue(codec, data, false); +} + +/** `deserialize` that also throws a `NinoError` when bytes follow the value. */ +export function deserializeExact(codec: NinoCodec, data: Uint8Array): T { + return readValue(codec, data, true); +} + +/** + * Deserializes one value into `value`, as `NinoDeserializer.Deserialize(data, ref value)` does in .NET, and returns + * the value read: the members of objects are read into the objects `value` holds (of the same class), arrays keep + * their storage and read their elements into the old ones by index, maps and sets are cleared and refilled, and a + * polymorphic member is read into only when the data holds the same class (tracked objects are read new). Bytes after + * the value are not read. If it throws, `value` holds what was read before the error, the rest as it was. + */ +export function deserializeInto(codec: NinoCodec, data: Uint8Array, value: T): T { + return readValue({ read: (r) => r.into(codec, value), write: codec.write }, data, false); +} + +/** + * A member that is .NET's `NinoNullable` (`Nino.Core`): the value or `null`, as a `T?` member is (`T | null`), under + * the name that says which bytes it has: its memory wherever it is, a presence and a value of a `T` each + * (`NinoReader.ninoNullableAt`), where a `T?` is a presence byte and the value, or a slot in a sequence + * (`NullableSlot`). An alias only: no wrapper object and nothing at run time. + */ +export type NinoNullable = T | null; + +/** + * A .NET `T?` of a fixed-size `T` (a number, a date, a raw struct) as the element of a sequence: the value or `null`, + * under the name that says which bytes it has: a slot of `T`'s alignment plus its size in every sequence, the presence + * byte first, zeros up to the alignment, then the value, zeros when absent. `NullableSlot[]` is an `int?[]`, a + * `List` or a `Queue`, `Set>` a `HashSet`. A single `T?` (a member, a map's + * key or value, a tuple's item) is not these bytes: it is a presence byte and the value only when present, declared + * `T | null`. An alias only: no wrapper object and nothing at run time. + */ +export type NullableSlot = T | null; + interface NinoEntry { id: number; read(reader: NinoReader): unknown; @@ -2080,4 +2131,3 @@ export class NinoSubtypes { }; } } - diff --git a/runtimes/typescript/src/runtime/api.ts b/runtimes/typescript/src/runtime/api.ts new file mode 100644 index 000000000..4eb0be2e7 --- /dev/null +++ b/runtimes/typescript/src/runtime/api.ts @@ -0,0 +1,124 @@ +import { readValue, type NinoReader } from "./reader.ts"; +import { NinoWriter } from "./writer.ts"; + +/** + * The Nino version of this runtime: nino-gen's for the copy it writes next to the generated types (which expect the + * same one), the package's for the npm package (scripts/version.mjs). + */ +export const ninoVersion = "__NINO_VERSION__"; + +/** Reads and writes one type's values. Generated for every [NinoType]. */ +export interface NinoCodec { + read(reader: NinoReader): T; + write(writer: NinoWriter, value: T): void; + /** + * Reads a value into `value` where it can (see `deserializeInto`) and returns the value read: `value` itself when it + * was reused. Optional: a codec without it reads a new value. + */ + readInto?(reader: NinoReader, value: T): T; +} + +let shared: NinoWriter | null = null; + +/** + * Serializes `value` with `codec` (what `NinoSerializer.Serialize` writes in .NET) into a new array. Results are + * written one after another into a shared buffer and returned as views of it, never copied or overwritten (as + * msgpackr does, and as Node's `Buffer`s share a pool): a new `ArrayBuffer` for every result costs more than most + * serializations. Read a result by its `byteOffset` and `length`, not through `.buffer`. + */ +export function serialize(codec: NinoCodec, value: T): Uint8Array { + // A codec that serializes (a custom one) while this runs gets a writer of its own. + const writer = shared ?? new NinoWriter(); + shared = null; + try { + writer.next(); + codec.write(writer, value); + return writer.detach(); + } finally { + if (writer.capacity <= 1 << 20) shared = writer; + } +} + +/** The writer `serializeInto` writes a `Uint8Array`'s value with: null while it is in use, or before the first call. */ +let scratchWriter: NinoWriter | null = null; + +/** + * Serializes `value` with `codec` into memory the caller owns, and returns the value's size in bytes: + * + * - into a `NinoWriter`, after what it holds (what `NinoSerializer.Serialize(value, bufferWriter)` does in .NET), + * growing it as needed; `written()` views the bytes until the writer writes again. A writer reused with `reset` keeps + * its buffer, so once it is large enough writing allocates no memory at all: no new `ArrayBuffer` per value, which + * V8 counts toward a full garbage collection (about every 64 MB of them in Node 24) until a scavenge frees them. If + * `codec` throws, the writer is left as it was before the call. + * - into a `Uint8Array`, from its start, when the value fits. A size larger than `target.length` means it did not: + * `target` is then unchanged, and a call with that many bytes succeeds. + * + * Not for a writer that is writing a value (from a custom codec): references and depth are counted per call. + */ +export function serializeInto(codec: NinoCodec, value: T, target: NinoWriter | Uint8Array): number { + if (target instanceof NinoWriter) { + const start = target.pos; + target["begin"](); + try { + codec.write(target, value); + } catch (e) { + target.pos = start; + throw e; + } + return target.pos - start; + } + // A codec that serializes (a custom one) while this runs gets a writer of its own. + const writer = scratchWriter ?? new NinoWriter(); + scratchWriter = null; + try { + writer.reset(); + codec.write(writer, value); + const size = writer.pos; + if (size <= target.length) target.set(writer.written()); + return size; + } finally { + if (writer.capacity <= 1 << 20) scratchWriter = writer; + } +} + +/** + * Deserializes one value written by `NinoSerializer.Serialize` (or `serialize`). Nothing it returns refers to + * `data`, which it does not change. Bytes after the value are not read (see `deserializeExact`). + */ +export function deserialize(codec: NinoCodec, data: Uint8Array): T { + return readValue(codec, data, false); +} + +/** `deserialize` that also throws a `NinoError` when bytes follow the value. */ +export function deserializeExact(codec: NinoCodec, data: Uint8Array): T { + return readValue(codec, data, true); +} + +/** + * Deserializes one value into `value`, as `NinoDeserializer.Deserialize(data, ref value)` does in .NET, and returns + * the value read: the members of objects are read into the objects `value` holds (of the same class), arrays keep + * their storage and read their elements into the old ones by index, maps and sets are cleared and refilled, and a + * polymorphic member is read into only when the data holds the same class (tracked objects are read new). Bytes after + * the value are not read. If it throws, `value` holds what was read before the error, the rest as it was. + */ +export function deserializeInto(codec: NinoCodec, data: Uint8Array, value: T): T { + return readValue({ read: (r) => r.into(codec, value), write: codec.write }, data, false); +} + +/** + * A member that is .NET's `NinoNullable` (`Nino.Core`): the value or `null`, as a `T?` member is (`T | null`), under + * the name that says which bytes it has: its memory wherever it is, a presence and a value of a `T` each + * (`NinoReader.ninoNullableAt`), where a `T?` is a presence byte and the value, or a slot in a sequence + * (`NullableSlot`). An alias only: no wrapper object and nothing at run time. + */ +export type NinoNullable = T | null; + +/** + * A .NET `T?` of a fixed-size `T` (a number, a date, a raw struct) as the element of a sequence: the value or `null`, + * under the name that says which bytes it has: a slot of `T`'s alignment plus its size in every sequence, the presence + * byte first, zeros up to the alignment, then the value, zeros when absent. `NullableSlot[]` is an `int?[]`, a + * `List` or a `Queue`, `Set>` a `HashSet`. A single `T?` (a member, a map's + * key or value, a tuple's item) is not these bytes: it is a presence byte and the value only when present, declared + * `T | null`. An alias only: no wrapper object and nothing at run time. + */ +export type NullableSlot = T | null; diff --git a/runtimes/typescript/src/runtime/deferrals.ts b/runtimes/typescript/src/runtime/deferrals.ts new file mode 100644 index 000000000..cda06b1f8 --- /dev/null +++ b/runtimes/typescript/src/runtime/deferrals.ts @@ -0,0 +1,45 @@ +import { NinoError } from "./error.ts"; + +/** + * Open class bodies after which the next one is deferred, as `NinoDepth.Inline` in .NET: its slot gets the instance + * now and its body is written and read later, from a shallow point (see "Deep nesting" in + * docs/v4-design/binary-format.md), so a long list or deep tree, or data forged to nest deeply, costs a bounded stack. + */ +export const inlineDepth = 128; +/** Open bodies after which a body that cannot be deferred fails, as `NinoDepth.Max` in .NET. */ +export const maxDepth = 512; +/** Set in the length of a region followed by a section of the bodies deferred inside it. */ +export const sectionFlag = -0x80000000; + +/** A body deferred until the stack is shallow again. */ +export interface NinoDeferred { + value: unknown; + body: (state: S, value: never) => void; + /** Where it was deferred: keys its entry when it is in a region's section. */ + position: number; + // Writer only, to find cycles (see NinoWriter.defer). + anchor: unknown; + generation: number; +} + +/** The deferred bodies of one call: outside any region, and inside the outermost region open. */ +export class NinoDeferrals { + top: NinoDeferred[] = []; + topHead = 0; + region: NinoDeferred[] = []; + regionHead = 0; + /** Whether `top` is being written or read. */ + topActive = false; + // Writer only: the deferred object whose body is being written, for cycle detection. + current: unknown = null; + currentAnchor: unknown = null; + currentGeneration = 0; + + add(item: NinoDeferred, regions: number): void { + (regions === 0 ? this.top : this.region).push(item); + } +} + +export function tooDeep(): NinoError { + return new NinoError(`data nested deeper than ${maxDepth} bodies.`); +} diff --git a/runtimes/typescript/src/runtime/error.ts b/runtimes/typescript/src/runtime/error.ts new file mode 100644 index 000000000..dd016cde9 --- /dev/null +++ b/runtimes/typescript/src/runtime/error.ts @@ -0,0 +1,7 @@ +/** Thrown for data that is not a valid value of the type read, or a value that cannot be written. */ +export class NinoError extends Error { + constructor(message: string) { + super("Nino: " + message); + this.name = "NinoError"; + } +} diff --git a/runtimes/typescript/src/runtime/grid.ts b/runtimes/typescript/src/runtime/grid.ts new file mode 100644 index 000000000..e92e8018d --- /dev/null +++ b/runtimes/typescript/src/runtime/grid.ts @@ -0,0 +1,9 @@ +/** A rectangular array's dimensions and its flat data, with the last index varying fastest. */ +export interface NinoGrid> { + readonly lengths: readonly number[]; + data: T; +} + +// .NET's Array.MaxLength and the maximum product of the dimensions (wire-format spec §9.13). +export const maxGridLength = 0x7fff_ffc7; +export const maxGridElements = 0xffff_ffff; diff --git a/runtimes/typescript/src/runtime/index.ts b/runtimes/typescript/src/runtime/index.ts new file mode 100644 index 000000000..ae690b642 --- /dev/null +++ b/runtimes/typescript/src/runtime/index.ts @@ -0,0 +1,12 @@ +export { + deserialize, deserializeExact, deserializeInto, ninoVersion, serialize, serializeInto, + type NinoCodec, type NinoNullable, type NullableSlot +} from "./api.ts"; +export { type NinoNumbers, type NinoNumbersType } from "./numbers.ts"; +export { NinoError } from "./error.ts"; +export { useWasm } from "./text.ts"; +export { NinoKeyGuard } from "./keys.ts"; +export { NinoReader } from "./reader.ts"; +export { NinoWriter } from "./writer.ts"; +export { NinoSubtypes } from "./subtypes.ts"; +export { type NinoGrid } from "./grid.ts"; diff --git a/runtimes/typescript/src/runtime/keys.ts b/runtimes/typescript/src/runtime/keys.ts new file mode 100644 index 000000000..cb1c8d1e8 --- /dev/null +++ b/runtimes/typescript/src/runtime/keys.ts @@ -0,0 +1,165 @@ +import { NinoError } from "./error.ts"; + +/** + * The most keys a key read from the data may find in its bucket of the `Map` or `Set` it goes into, as + * `NinoSettings.MaxHashCollisions`'s default in .NET. See `NinoKeyGuard`. + */ +const maxHashCollisions = 100; +/** Maps and sets of up to this many keys are not guarded: their keys cannot cost more than this many probes each. */ +export const guardedKeys = 128; + +/** + * Bounds what keys read from the data cost a `Map` or `Set` (hash flooding), as `NinoSettings.MaxHashCollisions` + * does in .NET. V8 hashes strings with a per-process seed, but numbers and bigints without one (its + * `ComputeUnseededHash` and `ComputeLongHash`), and a string that is an array index ("0" to "4294967294") by its + * value (`MakeArrayIndexHash`), so data can choose keys that share a bucket, and each insert then scans every key + * before it: 8,000 such ints took 40 times as long as ordinary ones in Node 22, 4,000 such strings 117 times, and + * the read grows with the square of their count. The guard counts the keys of each bucket of the table V8 ends with + * (`OrderedHashTable`: a power of two from 4 that holds them all, half as many buckets, a bucket by the hash's low + * bits) and throws a `NinoError` when a key would find more than `maxHashCollisions` keys in its bucket. The smaller + * tables V8 fills on the way are not counted (that would cost twice as much per key): one of `b` buckets holds at most + * `2b` keys and its buckets gather those of the final one, so a key there scans at most the smaller of `2b` and + * `maxHashCollisions` times the ratio of the two tables' sizes, which keeps a read within O(n log n) probes. It is + * exact for V8 (Node, Chromium, Deno); other engines (JavaScriptCore in Safari and Bun, SpiderMonkey in Firefox) hash + * differently, and there it bounds V8's buckets, not theirs. Generated code makes one for a map or set of more than + * `guardedKeys` number, bigint or string keys (`NinoReader.keyGuard`) and passes each key through it before adding it. + */ +export class NinoKeyGuard { + // Keys per bucket of the final table. + private readonly counts: Int32Array; + private readonly mask: number; + + constructor(length: number) { + let capacity = 4; + while (capacity < length) capacity *= 2; + this.counts = new Int32Array(capacity >>> 1); + this.mask = (capacity >>> 1) - 1; + } + + /** An int32 key (of a type no wider than `int`), after checking its bucket. */ + int(key: number): number { + this.add(unseededHash(key)); + return key; + } + + /** A number key, after checking its bucket. */ + number(key: number): number { + this.add(numberHash(key)); + return key; + } + + /** A key of either kind or null (a nullable number or bigint), after checking its bucket. */ + key(key: K): K { + return guardKey(this, key); + } + + /** A bigint key, after checking its bucket. */ + bigint(key: bigint): bigint { + this.add(bigintHash(key)); + return key; + } + + /** A string key, after checking its bucket when V8 hashes it by its value (an array index, `arrayIndexHash`). */ + string(key: S): S { + if (key !== null && key.length <= 10) { + const first = key.charCodeAt(0); + if (first >= 0x30 && first <= 0x39) this.index(key, key.length); + } + return key; + } + + private index(key: string, length: number): void { + const hash = arrayIndexHash(key, length); + if (hash >= 0) this.add(hash); + } + + private add(hash: number): void { + if (this.counts[hash & this.mask]++ === maxHashCollisions + 1) throw flooded(); + } +} + +function flooded(): NinoError { + return new NinoError(`more than ${maxHashCollisions} keys of a map or set share a hash bucket (hash flooding).`); +} + +/** V8's hash of a number key (`Object::GetSimpleHash`): int32 values (and -0) by `ComputeUnseededHash`, others by bits. */ +function numberHash(key: number): number { + if ((key | 0) === key) return unseededHash(key | 0); + if (key !== key) return 0x3FFFFFFF; + keyBits[0] = key; + return longHash(keyWords[1], keyWords[0]); +} + +/** V8's hash of a bigint key (`BigInt::Hash`): the low 64 bits of its magnitude by `ComputeLongHash`, 0 for 0n. */ +function bigintHash(key: bigint): number { + const magnitude = BigInt.asUintN(64, key < 0n ? -key : key); + return magnitude === 0n ? 0 : longHash(Number(magnitude >> 32n), Number(magnitude & 0xFFFFFFFFn)); +} + +const keyBits = new Float64Array(1); +const keyWords = new Uint32Array(keyBits.buffer); + +/** + * V8's hash of a string that is an array index (`StringHasher::MakeArrayIndexHash`: its value and its length, no + * seed), or -1 for any other string of up to 10 chars starting with a digit (those V8 hashes with its seed). + */ +function arrayIndexHash(key: string, length: number): number { + if (length > 1 && key.charCodeAt(0) === 0x30) return -1; + let value = 0; + for (let i = 0; i < length; i++) { + const digit = key.charCodeAt(i) - 0x30; + if (digit < 0 || digit > 9) return -1; + value = value * 10 + digit; + } + if (value > 4294967294) return -1; + return (((value << 2) | (length << 26)) >>> 2) & 0x3FFFFFFF; +} + +/** V8's `ComputeUnseededHash`, of a 32-bit key (in int32 arithmetic, the same bits). */ +function unseededHash(key: number): number { + let h = key | 0; + h = (~h + (h << 15)) | 0; + h ^= h >>> 12; + h = (h + (h << 2)) | 0; + h ^= h >>> 4; + h = Math.imul(h, 2057); + h ^= h >>> 16; + return h & 0x3FFFFFFF; +} + +/** V8's `ComputeLongHash`, of the 64-bit key `hi:lo` (in 32-bit halves). */ +function longHash(hi: number, lo: number): number { + // h = ~h + (h << 18) + let nh = ~hi >>> 0, nl = ~lo >>> 0; + let sh = ((hi << 18) | (lo >>> 14)) >>> 0, sl = (lo << 18) >>> 0; + let l = (nl + sl) >>> 0, h = (nh + sh + (l < nl ? 1 : 0)) >>> 0; + // h ^= h >> 31 + l = (l ^ ((h << 1) | (l >>> 31))) >>> 0; + h = (h ^ (h >>> 31)) >>> 0; + // h *= 21: h + (h << 2) + (h << 4) + let ah = ((h << 2) | (l >>> 30)) >>> 0, al = (l << 2) >>> 0; + let bh = ((h << 4) | (l >>> 28)) >>> 0, bl = (l << 4) >>> 0; + let tl = (l + al) >>> 0, th = (h + ah + (tl < l ? 1 : 0)) >>> 0; + l = (tl + bl) >>> 0; + h = (th + bh + (l < tl ? 1 : 0)) >>> 0; + // h ^= h >> 11 + l = (l ^ ((h << 21) | (l >>> 11))) >>> 0; + h = (h ^ (h >>> 11)) >>> 0; + // h += h << 6 + sh = ((h << 6) | (l >>> 26)) >>> 0; + sl = (l << 6) >>> 0; + tl = (l + sl) >>> 0; + h = (h + sh + (tl < l ? 1 : 0)) >>> 0; + l = tl; + // h ^= h >> 22 + l = (l ^ ((h << 10) | (l >>> 22))) >>> 0; + return l & 0x3FFFFFFF; +} + +/** A key of a type known only at run time through `guard`: numbers, bigints and strings (see `NinoKeyGuard`). */ +export function guardKey(guard: NinoKeyGuard, key: K): K { + if (typeof key === "number") guard.number(key); + else if (typeof key === "bigint") guard.bigint(key); + else if (typeof key === "string") guard.string(key); + return key; +} diff --git a/runtimes/typescript/src/runtime/numbers.ts b/runtimes/typescript/src/runtime/numbers.ts new file mode 100644 index 000000000..4f0b94ae6 --- /dev/null +++ b/runtimes/typescript/src/runtime/numbers.ts @@ -0,0 +1,53 @@ +/** + * A typed array of a fixed-size number type: how generated code holds an array or list of `sbyte`, `byte`, `short`, + * `ushort`, `int`, `uint`, `long`, `ulong`, `float` or `double` (`NinoReader.numbers`, `NinoWriter.numbers`). + */ +export type NinoNumbers = Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | + BigInt64Array | BigUint64Array | Float32Array | Float64Array; + +/** The constructor of a `NinoNumbers` type (`Int32Array`, ...). */ +export interface NinoNumbersType { + readonly BYTES_PER_ELEMENT: number; + new (length: number): T; + new (buffer: ArrayBuffer, byteOffset: number, length: number): T; +} + +/** Whether this host stores numbers little-endian, as Nino writes them: typed arrays are then copied as bytes. */ +export const littleEndian = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; + +/** Reverses the bytes of each `size`-byte element in `bytes` from `at` to `end`: Nino's order and a big-endian host's. */ +export function swapBytes(bytes: Uint8Array, at: number, end: number, size: number): void { + for (; at < end; at += size) { + for (let i = at, j = at + size - 1; i < j; i++, j--) { + const b = bytes[i]; + bytes[i] = bytes[j]; + bytes[j] = b; + } + } +} + +/** + * Typed arrays `NinoReader.numbers` reads up to this many bytes are views of a shared buffer (numbersSlab bytes), as + * Node's small `Buffer`s share a pool: one over 64 bytes has its memory outside V8's heap, and allocating that costs + * more than the copy (in Node 22 about 2 µs for 1,000 int32s against 0.6 µs for a pool view). Generated code reads + * those of up to 64 bytes one element at a time into a typed array of their own, which V8 keeps on its heap: viewing + * such an array's bytes (`.buffer`) allocates outside memory for it, which made reading 4 int64s 5 times slower than + * reading them into an array (test branch 97deeca). + */ +export const numbersPooled = 8192; +const numbersSlab = 64 * 1024; +export let numbersBuffer = new ArrayBuffer(0); +export let numbersBytes = new Uint8Array(0); +let numbersPos = 0; + +/** Where `bytes` bytes start in the shared buffer (8-byte aligned, as a view must be aligned to its elements). */ +export function poolNumbers(bytes: number): number { + let at = numbersPos; + if (bytes > numbersBytes.length - at) { + numbersBuffer = new ArrayBuffer(numbersSlab); + numbersBytes = new Uint8Array(numbersBuffer); + at = 0; + } + numbersPos = (at + bytes + 7) & ~7; + return at; +} diff --git a/runtimes/typescript/src/runtime/reader.ts b/runtimes/typescript/src/runtime/reader.ts new file mode 100644 index 000000000..7f02e3566 --- /dev/null +++ b/runtimes/typescript/src/runtime/reader.ts @@ -0,0 +1,727 @@ +import type { NinoCodec } from "./api.ts"; +import { NinoDeferrals, inlineDepth, maxDepth, tooDeep } from "./deferrals.ts"; +import { NinoError } from "./error.ts"; +import { maxGridElements, maxGridLength } from "./grid.ts"; +import { NinoKeyGuard, guardKey, guardedKeys } from "./keys.ts"; +import { littleEndian, numbersBuffer, numbersBytes, numbersPooled, poolNumbers, swapBytes, type NinoNumbers, type NinoNumbersType } from "./numbers.ts"; +import { hexHigh, hexLow, maxDateMilliseconds, unixEpochMilliseconds } from "./scalars.ts"; +import { + codes, decodeLatin1, decodeShortUtf16, fromCodes, kernelLatin1, kernelText, kernelUtf16, kernels, mediumText, + nodeText, nonAscii, scratchSize, textSlice, textWindow, transfer, utf16Decoder, utf8Decoder, wasm, type Kernels, +} from "./text.ts"; + +export function readValue(codec: NinoCodec, data: Uint8Array, exact: boolean): T { + let reader = scratchReader; + if (reader === null || data.length > scratchSize) { + if (reader !== null || scratchMade || data.length > scratchSize) { + return readAll(codec, new NinoReader(data), exact ? data.length : -1); + } + reader = makeScratch(); + } + // A codec that deserializes (a custom one) while this runs gets a reader of its own. + scratchReader = null; + try { + reader["load"](data); + return readAll(codec, reader, exact ? data.length : -1); + } finally { + scratchReader = reader; + } +} + +/** One value from `reader`, which must then be at `end` (the length of the data), unless `end` is -1. */ +function readAll(codec: NinoCodec, reader: NinoReader, end: number): T { + const value = codec.read(reader); + if (end >= 0 && reader.pos !== end) throw new NinoError(`${end - reader.pos} bytes after the value.`); + return value; +} + +/** The reader `deserialize` reuses: null while it is in use, or before the first call made it. */ +let scratchReader: NinoReader | null = null; +let scratchMade = false; + +/** The reader `deserialize` reuses: its bytes are in the kernels' memory when they are used, so text needs no copy. */ +function makeScratch(): NinoReader { + scratchMade = true; + const k = nodeText === null ? wasm() : null; + return new NinoReader(k !== null ? new Uint8Array(k.memory.buffer, 0, scratchSize) : new Uint8Array(scratchSize)); +} + +/** + * What the collections of one read may allocate ahead of their elements (`NinoReader.capacity`): 16 bytes per byte of + * data plus 16 KB, an element counted as 8 bytes (an array slot), as the Go and Rust readers budget a read. + */ +const presizePerByte = 16; +const presizeFloor = 16384; + +/** + * Reads values from bytes written by Nino. Generated code reads a run of fixed-size values with one `take`, then + * each value from `view` at its offset. + */ +export class NinoReader { + /** + * The bytes read, up to the value's end. For a value `deserialize` reads, a copy in bytes the next call reuses + * (longer than the value): read it through the reader, during `read`. + */ + readonly data: Uint8Array; + /** `data` as a DataView. */ + readonly view: DataView; + /** The offset of the next byte. */ + pos = 0; + // data.length, as a field: a typed array's length costs more to read. A section's entry is read up to its end. + private end: number; + // With Node's methods: the data from textStart to textEnd as Latin-1 text, decoded in one native call. Short + // strings are sliced from it, which costs less than a call each (as msgpackr slices its strings from one decode). + // It grows to textWindow bytes, so a payload with few strings decodes little. + private text = ""; + private textStart = 0; + private textEnd = 0; + private textSize = 256; + /** Open class bodies, counted by generated code (see `defer`). */ + depth = 0; + // Open regions, open struct bodies that can hold themselves, and the deferred bodies (made on the first one). + private regions = 0; + private structs = 0; + private deferrals: NinoDeferrals | null = null; + // Where the outermost region ends when a section of deferred bodies follows its members (only the outermost region + // holds one), else 0. + private sectionEnd = 0; + // Reference tracking: the objects of tracked types read so far, in the order of their headers (made on the first). + private refs: unknown[] | null = null; + // The bytes the collections of this read may still allocate ahead of their elements (see `capacity`). + private budget: number; + + constructor(data: Uint8Array) { + this.data = data; + this.view = new DataView(data.buffer, data.byteOffset, data.byteLength); + this.end = data.length; + this.budget = data.length * presizePerByte + presizeFloor; + } + + // deserialize: copies `data` into this reader's own bytes (scratchSize of them), as a new reader would start. + private load(data: Uint8Array): void { + this.data.set(data); + this.end = data.length; + this.budget = data.length * presizePerByte + presizeFloor; + this.pos = this.depth = this.regions = this.structs = this.sectionEnd = this.textStart = this.textEnd = 0; + this.text = ""; + this.textSize = 256; + this.deferrals = null; + this.refs = null; + } + + /** Moves past `size` bytes: returns where they start. */ + take(size: number): number { + const at = this.pos; + if (size > this.end - at) throw new NinoError("unexpected end of data."); + this.pos = at + size; + return at; + } + + /** Skips a value copied as raw memory: returns where it starts. */ + raw(size: number): number { return this.take(size); } + bool(): boolean { return this.boolAt(this.take(1)); } + /** A `bool` at `at`: 0 or 1, as every writer writes it; any other byte is invalid data. */ + boolAt(at: number): boolean { + const b = this.view.getUint8(at); + if (b > 1) throw new NinoError(`invalid bool byte ${b}.`); + return b === 1; + } + /** The presence byte of a nullable at `at`: true when a value follows (0 or 1, as `boolAt`). */ + presentAt(at: number): boolean { + const b = this.view.getUint8(at); + if (b > 1) throw new NinoError(`invalid presence byte ${b}.`); + return b === 1; + } + /** + * The presence of a .NET `NinoNullable` at `at`, its memory: `size` bytes of presence (0 or 1 in the first, zeros + * above), then `size` bytes of value, zeros when absent. True when it has a value; any other presence, and a value + * that is not zeros where it has none, is invalid data (as .NET's untrusted mode has it). + */ + ninoNullableAt(at: number, size: number): boolean { + const data = this.data; + const present = this.presentAt(at); + let set = 0; + for (let i = at + 1, end = at + (present ? size : 2 * size); i < end; i++) set |= data[i]; + if (set !== 0) throw new NinoError("invalid NinoNullable: a byte set above its presence or in a value it does not have."); + return present; + } + u8(): number { return this.view.getUint8(this.take(1)); } + i8(): number { return this.view.getInt8(this.take(1)); } + u16(): number { return this.view.getUint16(this.take(2), true); } + i16(): number { return this.view.getInt16(this.take(2), true); } + u32(): number { return this.view.getUint32(this.take(4), true); } + i32(): number { return this.view.getInt32(this.take(4), true); } + u64(): bigint { return this.view.getBigUint64(this.take(8), true); } + i64(): bigint { return this.view.getBigInt64(this.take(8), true); } + f32(): number { return this.view.getFloat32(this.take(4), true); } + f64(): number { return this.view.getFloat64(this.take(8), true); } + char(): string { return String.fromCharCode(this.u16()); } + guid(): string { return this.guidAt(this.take(16)); } + dateTime(): Date { return this.dateTimeAt(this.take(8)); } + /** `System.TimeSpan`, in ticks (100 ns). */ + timeSpan(): bigint { return this.i64(); } + decimal(): string { return this.decimalAt(this.take(16)); } + + /** `System.Guid` at `at`, as its usual text form. */ + guidAt(at: number): string { + // Bytes 0-3, 4-5 and 6-7 are little-endian integers; 8-15 are bytes in order. One call makes the text flat, + // where concatenating it would leave a string to flatten on first use. + const d = this.data, h = hexHigh, l = hexLow; + return String.fromCharCode( + h[d[at + 3]], l[d[at + 3]], h[d[at + 2]], l[d[at + 2]], h[d[at + 1]], l[d[at + 1]], h[d[at]], l[d[at]], 45, + h[d[at + 5]], l[d[at + 5]], h[d[at + 4]], l[d[at + 4]], 45, + h[d[at + 7]], l[d[at + 7]], h[d[at + 6]], l[d[at + 6]], 45, + h[d[at + 8]], l[d[at + 8]], h[d[at + 9]], l[d[at + 9]], 45, + h[d[at + 10]], l[d[at + 10]], h[d[at + 11]], l[d[at + 11]], h[d[at + 12]], l[d[at + 12]], + h[d[at + 13]], l[d[at + 13]], h[d[at + 14]], l[d[at + 14]], h[d[at + 15]], l[d[at + 15]]); + } + + /** `System.DateTime` at `at`, as a `Date` (to the millisecond; the kind is not kept). */ + dateTimeAt(at: number): Date { + // ticks / 10000 in exact Number arithmetic (no BigInt): 2^32 = 429496 * 10000 + 7296. + const lo = this.view.getUint32(at, true), hi = this.view.getUint32(at + 4, true) & 0x3fffffff; + const ms = hi * 429496 + Math.floor((hi * 7296 + lo) / 10000); + // Ticks past DateTime.MaxValue's (§9.10), as the Go and Rust readers check and the writer requires. + if (ms >= maxDateMilliseconds) throw new NinoError("invalid DateTime."); + return new Date(ms - unixEpochMilliseconds); + } + + /** `System.Decimal` at `at`, as its exact decimal text. */ + decimalAt(at: number): string { + const view = this.view, flags = view.getInt32(at, true), hi = view.getUint32(at + 4, true); + // Only the sign and a scale of at most 28 (§9.10), as the Go and Rust readers check and the writer requires. + if ((flags & 0x7f00ffff) !== 0 || ((flags >> 16) & 0xff) > 28) throw new NinoError("invalid decimal."); + const lo = view.getUint32(at + 8, true), mid = view.getUint32(at + 12, true); + // The 96-bit integer: below 2^53 in exact Number arithmetic, else as a BigInt. + let digits = hi === 0 && mid < 0x200000 ? (mid * 4294967296 + lo).toString() + : ((BigInt(hi) << 64n) | (BigInt(mid) << 32n) | BigInt(lo)).toString(); + const scale = (flags >> 16) & 0xff; + if (scale > 0) { + digits = digits.padStart(scale + 1, "0"); + digits = digits.slice(0, digits.length - scale) + "." + digits.slice(digits.length - scale); + } + return flags < 0 ? "-" + digits : digits; + } + + /** A collection length: -1 for null. */ + length(): number { + const length = this.i32(); + if (length < -1 || length > this.end - this.pos) throw new NinoError(`invalid length ${length}.`); + return length; + } + + /** Reads a rectangular array's dimensions and checked element count. A first dimension of -1 is null. */ + gridShape(rank: number, minSize: number): { lengths: number[]; count: number } | null { + const first = this.i32(); + if (first === -1) return null; + if (first < 0 || first > maxGridLength) throw new NinoError(`invalid length ${first}.`); + const lengths = [first]; + let count = first; + for (let i = 1; i < rank; i++) { + const length = this.i32(); + if (length < 0 || length > maxGridLength) throw new NinoError(`invalid length ${length}.`); + lengths.push(length); + count *= length; + if (count > maxGridElements) throw new NinoError("invalid grid dimensions."); + } + // A later zero can make the grid empty. Check the remaining bytes once all dimensions are known. + if (count * Math.max(minSize, 1) > this.end - this.pos) throw new NinoError("invalid grid dimensions."); + return { lengths, count }; + } + + /** + * A string header (wire-format spec §2.3.1): its first byte gives its size, as MessagePack's string markers do: + * the value itself below 0x80, else 0x80 and a uint16 or 0x81 and a uint32 (little-endian), minimal. One byte + * inline (up to 63 chars), longer ones in `longHeader`. + */ + header(): number { + const pos = this.pos; + if (pos < this.end) { + const first = this.data[pos]; + if (first < 0x80) { + this.pos = pos + 1; + return first; + } + } + return this.longHeader(); + } + + /** + * A header of three or five bytes, or none: rejects one cut, one with another first byte or one that a shorter + * form holds (not minimal). + */ + private longHeader(): number { + const data = this.data, at = this.pos, left = this.end - at; + if (left <= 0) throw new NinoError("unexpected end of data."); + const first = data[at]; + if (first === 0x80) { + if (left < 3) throw new NinoError("unexpected end of data."); + const value = this.view.getUint16(at + 1, true); + if (value < 0x80) throw new NinoError("string header not minimal."); + this.pos = at + 3; + return value; + } + if (first !== 0x81) throw new NinoError("string header out of range."); + if (left < 5) throw new NinoError("unexpected end of data."); + const value = this.view.getUint32(at + 1, true); + if (value <= 0xffff) throw new NinoError("string header not minimal."); + this.pos = at + 5; + return value; + } + + /** A string (the default encoding): 0 null, 2n + 1 then n Latin-1 bytes, or 2n then n UTF-16 code units. */ + string(): string | null { + // Inline: text of up to 63 one-byte chars, whose one-byte header is odd and below 0x80, checked with its text. + const at = this.pos; + if (at < this.end) { + const first = this.data[at]; + if ((first & 0x81) === 1) { + const length = first >>> 1, start = at + 1; + if (length > this.end - start) throw new NinoError("unexpected end of data."); + this.pos = start + length; + return length === 0 ? "" : this.latin1(start, length); + } + } + return this.otherString(); + } + + /** + * `string` for every other header: null, UTF-16 text, or one-byte text of 64 chars or more. The header, the bounds + * checks and the UTF-16 decoding are written out here, not called, so the function stays well over V8's limit for + * inlining (460 bytes of bytecode; 574 in Node 24) and never competes with the short-text path for the inlining + * budget of the functions that read strings. + */ + private otherString(): string | null { + const data = this.data, view = this.view, pos = this.pos; + let header: number; + if (pos < this.end && data[pos] < 0x80) { + header = data[pos]; + this.pos = pos + 1; + } else { + header = this.longHeader(); + } + const length = header >>> 1, start = this.pos; + if ((header & 1) !== 0) { + if (length > this.end - start) throw new NinoError("unexpected end of data."); + this.pos = start + length; + return length === 0 ? "" : this.latin1(start, length); + } + if (header === 0) return null; + if (length > (this.end - start) >>> 1) throw new NinoError(`invalid length ${length}.`); + const at = start; + this.pos = at + 2 * length; + if (length <= 24) return decodeShortUtf16(view, at, length); + if (nodeText !== null) return nodeText.ucs2Slice.call(data, at, at + 2 * length); + if (length > kernelUtf16 && length <= kernelText) { + const k = kernels === undefined ? wasm() : kernels; + if (k !== null) return k.utf16(this.inKernels(k, at, length * 2), length); + } + if (length <= mediumText) { + codes.length = length; + for (let i = 0; i < length; i++) codes[i] = view.getUint16(at + 2 * i, true); + return String.fromCharCode.apply(null, codes); + } + // The decoder writes U+FFFD for an unpaired surrogate: text with one is read code by code instead. + const text = utf16Decoder.decode(new Uint8Array(data.buffer, data.byteOffset + at, 2 * length)); + if (!text.includes("\ufffd")) return text; + const units = new Uint16Array(length); + for (let i = 0; i < units.length; i++) units[i] = view.getUint16(at + 2 * i, true); + return fromCodes(units); + } + + /** Where the `size` bytes at `at` (taken, at most 2 * kernelText) are in the kernels' memory: copied if not there. */ + private inKernels(k: Kernels, at: number, size: number): number { + const data = this.data; + if (data.buffer === k.memory.buffer) return data.byteOffset + at; + k.bytes.set(data.subarray(at, at + size), transfer); + return transfer; + } + + /** The text of `length` Latin-1 bytes at `at`. */ + private latin1(at: number, length: number): string { + if (nodeText === null) { + if (length > mediumText && length <= kernelLatin1) { + const k = kernels === undefined ? wasm() : kernels; + if (k !== null) return k.latin1(this.inKernels(k, at, length), length); + } + return decodeLatin1(this.data, at, length); + } + if (length > textSlice) return decodeLatin1(this.data, at, length); + if (at < this.textStart || at + length > this.textEnd) { + const end = Math.min(this.end, at + this.textSize); + if (this.textSize < textWindow) this.textSize *= 2; + this.text = nodeText.latin1Slice.call(this.data, at, end); + this.textStart = at; + this.textEnd = end; + } + return this.text.substring(at - this.textStart, at - this.textStart + length); + } + + /** A string written as UTF-8 (`[NinoUtf8]`): char count plus one (0 null), then (if not empty) byte count and bytes. */ + utf8(): string | null { + const header = this.header(); + if (header === 0) return null; + if (header === 1) return ""; + const chars = header - 1; + if (chars > 0x7fffffff) throw new NinoError(`invalid length ${chars}.`); + const bytes = this.header(); + if (bytes < chars || bytes > 3 * chars) throw new NinoError(`invalid length ${bytes}.`); + const at = this.take(bytes); + // As many bytes as chars: ASCII, the same as Latin-1 (if it is valid UTF-8). + if (bytes === chars) { + const text = this.latin1(at, bytes); + if (!nonAscii.test(text)) return text; + } + let value: string; + try { + value = utf8Decoder.decode(new Uint8Array(this.data.buffer, this.data.byteOffset + at, bytes)); + } catch { + // The decoder is fatal: it throws a TypeError for bytes that are not UTF-8. + throw new NinoError("invalid UTF-8 string."); + } + if (value.length !== chars) throw new NinoError("invalid UTF-8 string."); + return value; + } + + /** A `byte[]`: length, then the bytes (a copy). */ + bytes(): Uint8Array | null { + const length = this.length(); + if (length < 0) return null; + const at = this.take(length); + // A copy, and a Uint8Array even when the data is a Node Buffer. + return new Uint8Array(this.data.subarray(at, at + length)); + } + + /** + * An array or list of a fixed-size number type (`int[]`, `List`...) as a typed array of `type`: its length + * (unless given, when the caller read it), then the elements copied in one block (from a view of the data when the + * data is aligned to the elements, else from its bytes). Those of up to 8 KB are views of a buffer they share: read + * one by its `byteOffset` and `length`. + */ + numbers(type: NinoNumbersType, length: number = this.length()): T | null { + if (length < 0) return null; + const size = type.BYTES_PER_ELEMENT, bytes = length * size, at = this.take(bytes), data = this.data; + if (bytes > numbersPooled) { + const values = new type(length), start = data.byteOffset + at; + if (start % size === 0) (values as Uint8Array).set(new type(data.buffer as ArrayBuffer, start, length) as Uint8Array); + else new Uint8Array(values.buffer).set(data.subarray(at, at + bytes)); + if (!littleEndian) swapBytes(new Uint8Array(values.buffer), 0, bytes, size); + return values; + } + const to = poolNumbers(bytes), pool = numbersBytes; + pool.set(data.subarray(at, at + bytes), to); + if (!littleEndian) swapBytes(pool, to, to + bytes, size); + return new type(numbersBuffer, to, length); + } + + + /** + * How many of `length` elements (a length checked against the bytes left) a collection allocates before reading + * them; it grows as it reads the rest. All the collections of one read share one budget of 16 bytes per byte of + * data plus 16 KB, an element counted as 8 bytes, so collections nested in collections that claim more elements than + * they hold cannot each allocate the bytes left (as Go's `SliceCap` and Rust's `capacity`). Data a read accepts never + * spends it all: each element starts at a byte of its own. + */ + capacity(length: number): number { + const size = length * 8, budget = this.budget; + if (size <= budget) { + this.budget = budget - size; + return length; + } + this.budget = 0; + return Math.floor(budget / 8); + } + + /** An array, list or other sequence: length, then each element. */ + array(read: (reader: NinoReader) => T): T[] | null { + const length = this.length(); + if (length < 0) return null; + const values = new Array(this.capacity(length)); + for (let i = 0; i < length; i++) values[i] = read(this); + return values; + } + + /** A set: length, then each element. An element read twice is invalid data, as in .NET (see `duplicateKey`). */ + set(read: (reader: NinoReader) => T): Set | null { + const length = this.length(); + if (length < 0) return null; + const values = new Set(), guard = this.keyGuard(length); + for (let i = 0; i < length; i++) values.add(guard === null ? read(this) : guardKey(guard, read(this))); + if (values.size !== length) throw this.duplicateKey(); + return values; + } + + /** + * The guard against hash flooding (`NinoKeyGuard`) for a map or set of `length` number, bigint or string keys read + * from the data, or null for one of up to 128 keys, which cannot be flooded far. Its table spends the read's presize + * budget (`capacity`): past it (data that claims more than it holds) it counts fewer, fuller buckets, so it is only + * stricter. + */ + keyGuard(length: number): NinoKeyGuard | null { + return length > guardedKeys ? new NinoKeyGuard(this.capacity(length)) : null; + } + + /** A dictionary: length, then each key and value. A key read twice is invalid data, as in .NET (see `duplicateKey`). */ + map(readKey: (reader: NinoReader) => K, readValue: (reader: NinoReader) => V): Map | null { + const length = this.length(); + if (length < 0) return null; + const map = new Map(), guard = this.keyGuard(length); + for (let i = 0; i < length; i++) { + const key = readKey(this); + map.set(guard === null ? key : guardKey(guard, key), readValue(this)); + } + if (map.size !== length) throw this.duplicateKey(); + return map; + } + + /** + * The error for a map or set read with fewer entries than its length: a key or element came twice, which .NET's + * dictionaries and sets reject (Nino writes none). Generated code checks the size once, after the loop. Keys are + * compared as `Map` and `Set` compare them: numbers, bigints, strings, booleans and null by value; keys read as + * objects (`Date`, structs, tuples) by identity, so those are not checked. + */ + duplicateKey(): NinoError { + return new NinoError("a key or element is repeated in a map or set."); + } + + /** + * The error for a C# union (wire-format spec §7.12) holding a type id that is not one of its cases, or a case's id + * with a null value: .NET writes the empty union (type id 0) for a case given null. + */ + invalidCase(id: number): NinoError { + return new NinoError(`type id 0x${(id >>> 0).toString(16)} with this value is not a case of the union.`); + } + + /** A nullable value, `Tuple` or sealed class: a presence byte, then the value if present. */ + nullable(read: (reader: NinoReader) => T): T | null { + return this.present() ? read(this) : null; + } + + /** Reads a value with `codec` into `value` when the codec can (`NinoCodec.readInto`), else a new one. */ + into(codec: NinoCodec, value: T): T { + return codec.readInto === undefined ? codec.read(this) : codec.readInto(this, value); + } + + /** The presence byte of a nullable, `Tuple` or sealed class: true when a value follows (0 or 1). */ + present(): boolean { + const flag = this.u8(); + if (flag > 1) throw new NinoError(`invalid presence byte ${flag}.`); + return flag === 1; + } + + /** + * A version tolerant or keyed body (or a keyed member): its byte length. Returns the offset where its members end + * (a section of deferred bodies may follow them). + */ + beginRegion(): number { + const length = this.i32(); + this.regions++; + if (length >= 0 && length <= this.end - this.pos) return this.pos + length; + return this.sectionedRegion(length); + } + + /** + * A region whose length has `sectionFlag` set: where its members end, before the section and its offset. Checks the + * section as .NET, Go and Rust do, before any member is read: only the outermost region holds one (`beginRegion` has + * counted it already), and its entries `(int32 key, int32 length, body)` fill it exactly, at least one, keyed in + * increasing order by positions no later than the entry itself (where the body deferred to it would have begun: in + * the members, at most at their end, or in the body of an earlier entry). + */ + private sectionedRegion(length: number): number { + const total = length & 0x7fffffff, at = this.pos; + if (length >= 0 || total < 4 || total > this.end - at) throw new NinoError(`invalid length ${length}.`); + if (this.regions !== 1) throw new NinoError("deferred bodies in a region inside another region."); + const view = this.view, end = total - 4, members = view.getInt32(at + end, true); + // At least one entry: a writer flags a region only when it holds a deferred body. + if (members < 0 || members >= end) throw new NinoError("invalid offset of deferred bodies."); + let last = -1; + for (let p = members; p !== end;) { + if (end - p < 8) throw new NinoError("invalid section of deferred bodies."); + const key = view.getInt32(at + p, true), size = view.getInt32(at + p + 4, true); + if (key <= last || key > p || size < 0 || size > end - p - 8) + throw new NinoError("invalid section of deferred bodies."); + last = key; + p += 8 + size; + } + this.sectionEnd = at + total; + return at + members; + } + + /** + * Moves to the end of a region, checking that its members stayed inside it. At the end of the outermost region, + * moves past its section, if any, and reads the bodies deferred inside it from there. + */ + endRegion(end: number): void { + if (this.pos > end) throw new NinoError("a member runs past the end of its object."); + if (--this.regions === 0) { + const after = this.sectionEnd; + this.sectionEnd = 0; + this.pos = after === 0 ? end : after; + if (this.deferrals !== null) this.readSection(end); + } else { + this.pos = end; + } + } + + /** + * Generated code: `endRegion` for a keyed member that was read, whose value must fill its entry exactly. Bytes left + * over are invalid data, as in .NET, Go and Rust (no writer leaves any); entries of unknown keys are skipped whole + * by `endRegion`. + */ + endMember(end: number): void { + if (this.pos !== end) throw this.memberSize(end); + this.endRegion(end); + } + + private memberSize(end: number): NinoError { + return new NinoError(this.pos > end ? "a member runs past the end of its object." + : "bytes left over at the end of a keyed member."); + } + + /** + * Generated code, for a class body opened when `depth` bodies are open already (128, `NinoDepth.Inline`): queues + * `value`, whose body `body` reads later. Returns `value`. + */ + defer(value: T, body: (reader: NinoReader, value: T) => void): T { + (this.deferrals ??= new NinoDeferrals()).add( + { value, body: body as (reader: NinoReader, value: never) => void, position: this.pos, anchor: null, generation: 0 }, + this.regions); + return value; + } + + /** Generated code: the body of a class that cannot be deferred (built by its constructor in .NET), read in place. */ + deep(value: T, body: (reader: NinoReader, value: T) => void): T { + const depth = this.depth; + if (depth + this.structs >= maxDepth) throw tooDeep(); + this.depth = depth + 1; + body(this, value); + this.depth = depth; + return value; + } + + /** Generated code: closes a class body opened when `depth` bodies were open; at 0, reads the deferred bodies. */ + exitBody(depth: number): void { + this.depth = depth; + if (depth === 0 && this.deferrals !== null) this.readTop(); + } + + /** Generated code: opens the body of a struct that can hold itself, which no class body counts. */ + enterStruct(): void { + if (++this.structs + this.depth > maxDepth) throw tooDeep(); + } + + /** Generated code: closes a body opened by `enterStruct`. */ + exitStruct(): void { this.structs--; } + + /** + * Generated code: a reference header (wire-format spec §7.9): -1 for a new object, which the caller reads (and + * records with `track` as soon as it exists), 0 for null, or n > 0 for the n-th object read before. + */ + ref(): number { + const header = this.i32(); + if (header < -1 || header > (this.refs?.length ?? 0)) throw new NinoError(`invalid object reference ${header}.`); + return header; + } + + /** Generated code: the n-th object read (`ref`), which must be a `type`. */ + backRef(index: number, type: abstract new (...args: never[]) => T): T { + const value = this.refs![index - 1]; + if (!(value instanceof type)) throw new NinoError(`object reference ${index} is not a ${type.name}.`); + return value; + } + + /** Generated code: the n-th object read (`ref`), which must be one of `types` (those an interface allows). */ + backRefOf(index: number, types: readonly (abstract new (...args: never[]) => unknown)[]): T { + const value = this.refs![index - 1]; + if (!types.some((type) => value instanceof type)) throw new NinoError(`object reference ${index} is not a type allowed here.`); + return value as T; + } + + /** + * Generated code: the elements of a [NinoType] collection, which are never null (the collection is the object + * holding them). + */ + elements(value: T | null): T { + if (value === null) throw new NinoError("a [NinoType] collection's elements are null."); + return value; + } + + /** + * Generated code: records a new object of a tracked type when it is created, before its members are read: later + * references to it (from inside it, too) are back references. + */ + track(value: unknown): void { + (this.refs ??= []).push(value); + } + + /** Generated code: a tracked sealed class, its reference header then its body when new; null, or an earlier object. */ + tracked(type: abstract new (...args: never[]) => T, read: (reader: NinoReader) => T): T | null { + const header = this.ref(); + return header === -1 ? read(this) : header === 0 ? null : this.backRef(header, type); + } + + /** + * Generated code: a tracked object behind a type id its declared type (`object`, a base or interface not tracked) + * does not track: its reference header, then its body when new. A null object is a type id of 0, never a header + * of 0 here. + */ + trackedOf(type: abstract new (...args: never[]) => T, read: (reader: NinoReader) => T): T { + const header = this.ref(); + if (header === 0) throw new NinoError("a null object reference after a type id."); + return header === -1 ? read(this) : this.backRef(header, type); + } + + /** Every body is closed: reads the bodies deferred outside regions, in order, each from depth 1. */ + private readTop(): void { + const d = this.deferrals!; + if (d.topActive || d.topHead === d.top.length) return; + d.topActive = true; + while (d.topHead < d.top.length) { + const item = d.top[d.topHead++]; + this.depth = 1; + item.body(this, item.value as never); + } + this.depth = 0; + d.top.length = d.topHead = 0; + d.topActive = false; + } + + /** + * After the outermost region (its members end at `regionEnd`; the reader is past its section and the section's + * offset): reads each body deferred inside it from its entry, `(int32 key, int32 length, body)`, matched in order by + * the key (where it was deferred, relative to the region's start). Entries of objects this reader skipped (members + * it does not know) are skipped. Bodies deferred while reading them are appended. + */ + private readSection(regionEnd: number): void { + const d = this.deferrals!, queue = d.region; + if (d.regionHead === queue.length) return; + const after = this.pos, sectionEnd = after - 4; + if (sectionEnd <= regionEnd) throw new NinoError("missing deferred bodies."); + const view = this.view, start = regionEnd - view.getInt32(sectionEnd, true); + const end = this.end, depth = this.depth, entryDepth = Math.min(depth, inlineDepth - 1) + 1; + let at = regionEnd; + this.regions = 1; + while (d.regionHead < queue.length) { + const item = queue[d.regionHead++]; + for (;;) { + if (sectionEnd - at < 8) throw new NinoError("unexpected end of data."); + const key = view.getInt32(at, true), length = view.getInt32(at + 4, true); + at += 8; + if (length < 0 || length > sectionEnd - at) throw new NinoError(`invalid length ${length}.`); + const entry = at; + at += length; + if (start + key !== item.position) continue; + this.pos = entry; + this.end = entry + length; + this.depth = entryDepth; + item.body(this, item.value as never); + break; + } + } + this.regions = 0; + this.end = end; + this.depth = depth; + this.pos = after; + queue.length = d.regionHead = 0; + } +} diff --git a/runtimes/typescript/src/runtime/scalars.ts b/runtimes/typescript/src/runtime/scalars.ts new file mode 100644 index 000000000..584b23e0b --- /dev/null +++ b/runtimes/typescript/src/runtime/scalars.ts @@ -0,0 +1,10 @@ +/** Milliseconds between 0001-01-01 and 1970-01-01. */ +export const unixEpochMilliseconds = 62135596800000; +/** Milliseconds between 0001-01-01 and 10000-01-01: past `DateTime.MaxValue`. */ +export const maxDateMilliseconds = 315537897600000; +/** The char codes of each byte's high and low hex digit. */ +export const hexHigh = Uint8Array.from({ length: 256 }, (_, i) => "0123456789abcdef".charCodeAt(i >> 4)); +export const hexLow = Uint8Array.from({ length: 256 }, (_, i) => "0123456789abcdef".charCodeAt(i & 15)); +/** The value of each hex digit by its char code, else -1. */ +export const hexValues = Int8Array.from({ length: 128 }, (_, c) => + c >= 48 && c <= 57 ? c - 48 : (c | 32) >= 97 && (c | 32) <= 102 ? (c | 32) - 87 : -1); diff --git a/runtimes/typescript/src/runtime/subtypes.ts b/runtimes/typescript/src/runtime/subtypes.ts new file mode 100644 index 000000000..f6b280782 --- /dev/null +++ b/runtimes/typescript/src/runtime/subtypes.ts @@ -0,0 +1,63 @@ +import type { NinoCodec } from "./api.ts"; +import { NinoError } from "./error.ts"; +import { NinoReader } from "./reader.ts"; +import { NinoWriter } from "./writer.ts"; + +interface NinoEntry { + id: number; + read(reader: NinoReader): unknown; + write(writer: NinoWriter, value: unknown): void; +} + +/** + * The [NinoType]s written behind a type id (non-sealed classes, interfaces, `object`): the generated code adds every + * type it declares, by its `NinoTypeId`. + */ +export class NinoSubtypes { + private readonly byId = new Map(); + private readonly byType = new Map(); + + /** Adds a type: its id, its class and how its body is read and written. */ + add(id: number, type: Function, read: (reader: NinoReader) => T, + write: (writer: NinoWriter, value: T) => void): void { + const entry: NinoEntry = { id, read, write: write as (writer: NinoWriter, value: unknown) => void }; + this.byId.set(id, entry); + this.byType.set(type, entry); + } + + /** Reads a type id (0 for null) and the body of that type, which must be one of `ids` (any type when null). */ + read(reader: NinoReader, ids: readonly number[] | null): unknown { + const id = reader.i32(); + if (id === 0) return null; + const entry = this.byId.get(id); + if (entry === undefined || (ids !== null && !ids.includes(id))) throw this.unreadable(id); + return entry.read(reader); + } + + /** Writes the type id of `value`'s class (0 for null), which must be one of `ids` (any type when null), and its body. */ + write(writer: NinoWriter, value: unknown, ids: readonly number[] | null): void { + if (value === null || value === undefined) { writer.i32(0); return; } + const entry = this.byType.get((value as object).constructor); + if (entry === undefined || (ids !== null && !ids.includes(entry.id))) throw this.unwritable(value as object); + writer.i32(entry.id); + entry.write(writer, value); + } + + /** The error for a type id that is not a type that can be read where it was read. */ + unreadable(id: number): NinoError { + return new NinoError(`type id 0x${(id >>> 0).toString(16)} is not a type that can be read here.`); + } + + /** The error for a value whose class is not a type that can be written where it was written. */ + unwritable(value: object): NinoError { + return new NinoError(`${value.constructor.name} is not a type that can be written here.`); + } + + /** The codec of a type written behind a type id: any of `ids`, the ids of the types assignable to it. */ + codec(ids: readonly number[]): NinoCodec { + return { + read: (reader) => this.read(reader, ids) as T | null, + write: (writer, value) => this.write(writer, value, ids), + }; + } +} diff --git a/runtimes/typescript/src/runtime/text.ts b/runtimes/typescript/src/runtime/text.ts new file mode 100644 index 000000000..6e9a17477 --- /dev/null +++ b/runtimes/typescript/src/runtime/text.ts @@ -0,0 +1,340 @@ +/** + * Values up to this size are copied into the bytes of one reader that `deserialize` reuses: a copy costs less than + * the `DataView` a new reader makes (about 75 ns in Node 22, 50 in Chromium), which is most of the time of a small + * value. + */ +export const scratchSize = 4096; + +// ignoreBOM keeps a leading U+FEFF, which is text in Nino. +export const utf8Decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); +export const utf8Encoder = new TextEncoder(); + +/** + * The bytes a string header (below 2^32, wire-format spec §2.3.1) takes: 1 below 0x80 (the value itself), 3 up to + * 0xFFFF (0x80 and a uint16), else 5 (0x81 and a uint32). + */ +export function headerSize(value: number): number { + return value < 0x80 ? 1 : value <= 0xffff ? 3 : 5; +} +/** Browsers decode "latin1" as windows-1252, which differs from Latin-1 in 0x80-0x9F (see `decodeLatin1`). */ +const latin1Decoder = new TextDecoder("latin1"); +/** Replaces unpaired surrogates with U+FFFD, which .NET keeps (see `decodeUtf16`). */ +export const utf16Decoder = new TextDecoder("utf-16le", { ignoreBOM: true }); +/** A char wider than a byte. A string without one is one byte per char in Nino. */ +export const wide = /[^\x00-\xff]/; +/** A char outside ASCII. */ +export const nonAscii = /[^\x00-\x7f]/; + +/** Chars per `String.fromCharCode` call, well under any engine's argument limit. */ +const chunk = 4096; +/** + * With Node's methods, text longer than this is written by a native call (`latin1Write`, `ucs2Write`, after a regex + * for chars past U+00FF); shorter text is narrowed char by char in JavaScript, which costs less up to about 48 chars + * on x64 and Arm64 (32 and 64 measured the same, 8 took twice as long on short text). + */ +export const shortText = 48; +/** Without Node's methods, the longest text read and written in JavaScript: TextDecoder and TextEncoder cost more. */ +export const mediumText = 32; +/** + * Without Node's methods, the longest text written in JavaScript: a `TextEncoder.encodeInto` call costs about as + * much as writing 300 chars in Chromium. + */ +export const loopText = 256; +/** + * With Node's methods, the longest text sliced from the reader's decoded window. V8 copies a substring this short + * into a plain string; a longer one would be a slice of the window, slower to write or test with a regex later. + */ +export const textSlice = 12; +/** The window's largest size. */ +export const textWindow = 4096; +/** The char codes of a text being read, passed to `String.fromCharCode` at once. */ +export const codes: number[] = []; + +/** The native Latin-1 and UTF-16 text methods of Node's `Buffer` (Bun's and Deno's too), called on a Uint8Array. */ +interface NodeText { + latin1Slice(this: Uint8Array, start: number, end: number): string; + ucs2Slice(this: Uint8Array, start: number, end: number): string; + latin1Write(this: Uint8Array, text: string, offset: number, length: number): number; + ucs2Write(this: Uint8Array, text: string, offset: number, length: number): number; +} + +/** `Buffer.prototype` when it reads and writes Latin-1 and UTF-16 (unpaired surrogates included) as Nino does. */ +export const nodeText = ((): NodeText | null => { + try { + const text = (globalThis as { Buffer?: { prototype: NodeText } }).Buffer?.prototype; + if (text === undefined) return null; + const probe = new Uint8Array(5); + text.latin1Write.call(probe, "\u00e9", 0, 1); + text.ucs2Write.call(probe, "\ud800\u0101", 1, 4); + return text.latin1Slice.call(probe, 0, 1) === "\u00e9" && text.ucs2Slice.call(probe, 1, 5) === "\ud800\u0101" && + probe[1] === 0x00 && probe[2] === 0xd8 ? text : null; + } catch { + return null; + } +})(); + +/** + * The WebAssembly kernels (wasm/text.wat, built by `npm run build:wasm`): text between JavaScript strings and the + * bytes of Nino's string encodings, where no native method does it (browsers and Deno; Node, Bun and Deno with Node's + * `Buffer` keep `nodeText`). They take the strings through the JS String Builtins and move their chars in SIMD + * registers. An engine without WebAssembly, its SIMD, GC or the builtins, or a page whose CSP forbids compiling it, + * keeps the JavaScript paths, which write and read the same bytes. + */ +export interface Kernels { + /** The module's one page of memory: the buffer of `deserialize`'s reader, then `transfer`. */ + memory: { readonly buffer: ArrayBuffer }; + latin1(at: number, length: number): string; + utf16(at: number, length: number): string; + narrow(text: string, length: number, out: number): number; + widen(length: number, out: number): void; + /** `memory` as bytes (it never grows, so this view stays valid). */ + bytes: Uint8Array; +} + +/** The module (wasm/text.wat), base64. Generated: `npm run build:wasm` writes it. */ +const kernelModule = + // wasm:begin + // wasm:source sha256:8236fe8bc177570b7fe91f090e92de136a666423240cdcc8af50573fdc337719 + "AGFzbQEAAAABJwZedwFgA29jAH8Bf2ADYwB/fwFkb2ACf38Bb2ADb39/AX9gAn9/AAJHAg53YXNtOmpzLXN0cmluZxFpbnRvQ2hhckNvZGVBcnJheQABDndhc206anMtc3RyaW5nEWZyb21DaGFyQ29kZUFycmF5AAIDBQQDAwQFBQQBAQEBBgsBZAAAQYAg+wcACwcsBQZtZW1vcnkCAAZsYXRpbjEAAgV1dGYxNgADBm5hcnJvdwAEBXdpZGVuAAUKuwgE0gIDAWQAAn8BeyMAIQIgAUFwcSEEAkADQCADIARPDQEgACADav0ABAAhBSACIANBAGogBf0WAPsOACACIANBAWogBf0WAfsOACACIANBAmogBf0WAvsOACACIANBA2ogBf0WA/sOACACIANBBGogBf0WBPsOACACIANBBWogBf0WBfsOACACIANBBmogBf0WBvsOACACIANBB2ogBf0WB/sOACACIANBCGogBf0WCPsOACACIANBCWogBf0WCfsOACACIANBCmogBf0WCvsOACACIANBC2ogBf0WC/sOACACIANBDGogBf0WDPsOACACIANBDWogBf0WDfsOACACIANBDmogBf0WDvsOACACIANBD2ogBf0WD/sOACADQRBqIQMMAAsLAkADQCADIAFPDQEgAiADIAAgA2otAAD7DgAgA0EBaiEDDAALCyACQQAgARABC+ABAwFkAAJ/AXsjACECIAFBeHEhBAJAA0AgAyAETw0BIAAgA0EBdGr9AAQAIQUgAiADQQBqIAX9GQD7DgAgAiADQQFqIAX9GQH7DgAgAiADQQJqIAX9GQL7DgAgAiADQQNqIAX9GQP7DgAgAiADQQRqIAX9GQT7DgAgAiADQQVqIAX9GQX7DgAgAiADQQZqIAX9GQb7DgAgAiADQQdqIAX9GQf7DgAgA0EIaiEDDAALCwJAA0AgAyABTw0BIAIgAyAAIANBAXRqLwEA+w4AIANBAWohAwwACwsgAkEAIAEQAQuYAgMBZAADfwF7IwAhAyAAIANBABAAGiABQXhxIQUCQANAIAQgBU8NASAHIAMgBEEAavsNAP0aACEHIAcgAyAEQQFq+w0A/RoBIQcgByADIARBAmr7DQD9GgIhByAHIAMgBEEDavsNAP0aAyEHIAcgAyAEQQRq+w0A/RoEIQcgByADIARBBWr7DQD9GgUhByAHIAMgBEEGavsNAP0aBiEHIAcgAyAEQQdq+w0A/RoHIQcgB/0MAP8A/wD/AP8A/wD/AP8A//1O/VMNASACIARqIAcgB/1m/VsDAAAgBEEIaiEEDAALCwJAA0AgBCABTw0BIAMgBPsNACEGIAZB/wFLDQEgAiAEaiAGOgAAIARBAWohBAwACwsgBAvoAQMBZAACfwF7IwAhAiAAQXhxIQQCQANAIAMgBE8NASAFIAIgA0EAavsNAP0aACEFIAUgAiADQQFq+w0A/RoBIQUgBSACIANBAmr7DQD9GgIhBSAFIAIgA0EDavsNAP0aAyEFIAUgAiADQQRq+w0A/RoEIQUgBSACIANBBWr7DQD9GgUhBSAFIAIgA0EGavsNAP0aBiEFIAUgAiADQQdq+w0A/RoHIQUgASADQQF0aiAF/QsEACADQQhqIQMMAAsLAkADQCADIABPDQEgASADQQF0aiACIAP7DQA7AQAgA0EBaiEDDAALCws="; + // wasm:end +/** The most chars a kernel takes: the size of its array of code units (test/wasm.test.ts checks text.wat's). */ +export const kernelText = 4096; +/** + * Where in the kernels' memory text is copied in and written out (`kernelText` UTF-16 code units): after the bytes of + * `deserialize`'s reader, which start the memory. + */ +export const transfer = scratchSize; +/** + * In Chromium the kernels read Latin-1 text longer than `mediumText` up to `kernelLatin1` chars (TextDecoder costs + * the same for longer text), UTF-16 text longer than `kernelUtf16` (shorter: `decodeShortUtf16`), and write text + * longer than `kernelWrite` (shorter costs less in JavaScript than a call), except ASCII longer than `kernelAscii`, + * which `TextEncoder.encodeInto` writes faster. + */ +export const kernelLatin1 = 128, kernelUtf16 = 24, kernelWrite = 64, kernelAscii = 1024; + +/** The kernels, if this engine runs them; undefined until first needed. */ +let loaded: Kernels | null | undefined; +/** The kernels in use: `loaded`, unless `useWasm(false)` turned them off. */ +export let kernels: Kernels | null | undefined; + +/** What the kernels need of the WebAssembly API, declared here so the runtime compiles without the DOM's types. */ +interface WebAssemblyApi { + validate(bytes: Uint8Array, options: object): boolean; + Module: new (bytes: Uint8Array, options: object) => object; + Instance: new (module: object, imports: object) => { exports: unknown }; +} + +function loadKernels(): Kernels | null { + try { + const api = (globalThis as { WebAssembly?: WebAssemblyApi }).WebAssembly; + if (api === undefined) return null; + const bytes = Uint8Array.from(atob(kernelModule), (c) => c.charCodeAt(0)), options = { builtins: ["js-string"] }; + if (!api.validate(bytes, options)) return null; + // No imports given: an engine without the builtins fails to link here. + const exports = new api.Instance(new api.Module(bytes, options), {}).exports as Kernels; + const k: Kernels = { ...exports, bytes: new Uint8Array(exports.memory.buffer) }; + // A check of each kernel on known text. + const probe = "a\u00e9\u4e2d\ud800"; + if (k.narrow(probe, 4, transfer) !== 2 || k.latin1(transfer, 2) !== "a\u00e9") return null; + k.widen(4, transfer); + return k.utf16(transfer, 4) === probe ? k : null; + } catch { + return null; + } +} + +/** The kernels in use, loaded on first use. */ +export function wasm(): Kernels | null { + if (kernels === undefined) kernels = loaded = loaded === undefined ? loadKernels() : loaded; + return kernels; +} + +/** + * Whether text is read and written with the WebAssembly kernels where they are faster than JavaScript (browsers and + * Deno; see `Kernels`): `useWasm(false)` turns them off, `useWasm(true)` back on where the engine runs them, and + * `useWasm()` only tells. The bytes are the same either way. Returns whether they are in use. + */ +export function useWasm(enabled?: boolean): boolean { + if (enabled === false) kernels = null; + else if (enabled === true) kernels = undefined; + // With Node's methods, text never needs them. + return nodeText === null && wasm() !== null; +} + +/** The text of UTF-16 code units, unpaired surrogates included (as .NET keeps them). */ +export function fromCodes(codes: ArrayLike): string { + if (codes.length <= chunk) return String.fromCharCode.apply(null, codes as number[]); + let text = ""; + for (let i = 0; i < codes.length; i += chunk) + text += String.fromCharCode.apply(null, Array.prototype.slice.call(codes, i, i + chunk) as number[]); + return text; +} + +/** The text of up to 16 Latin-1 bytes at `at`, in one call (a flat string, faster than any native decoder). */ +function decodeShortLatin1(d: Uint8Array, at: number, length: number): string { + const c = String.fromCharCode; + switch (length) { + case 0: return ""; + case 1: return c(d[at]); + case 2: return c(d[at], d[at + 1]); + case 3: return c(d[at], d[at + 1], d[at + 2]); + case 4: return c(d[at], d[at + 1], d[at + 2], d[at + 3]); + case 5: return c(d[at], d[at + 1], d[at + 2], d[at + 3], d[at + 4]); + case 6: return c(d[at], d[at + 1], d[at + 2], d[at + 3], d[at + 4], d[at + 5]); + case 7: return c(d[at], d[at + 1], d[at + 2], d[at + 3], d[at + 4], d[at + 5], d[at + 6]); + case 8: return c(d[at], d[at + 1], d[at + 2], d[at + 3], d[at + 4], d[at + 5], d[at + 6], d[at + 7]); + case 9: return c(d[at], d[at + 1], d[at + 2], d[at + 3], d[at + 4], d[at + 5], d[at + 6], d[at + 7], d[at + 8]); + case 10: + return c(d[at], d[at + 1], d[at + 2], d[at + 3], d[at + 4], d[at + 5], d[at + 6], d[at + 7], d[at + 8], d[at + 9]); + case 11: + return c(d[at], d[at + 1], d[at + 2], d[at + 3], d[at + 4], d[at + 5], d[at + 6], d[at + 7], d[at + 8], d[at + 9], + d[at + 10]); + case 12: + return c(d[at], d[at + 1], d[at + 2], d[at + 3], d[at + 4], d[at + 5], d[at + 6], d[at + 7], d[at + 8], d[at + 9], + d[at + 10], d[at + 11]); + case 13: + return c(d[at], d[at + 1], d[at + 2], d[at + 3], d[at + 4], d[at + 5], d[at + 6], d[at + 7], d[at + 8], d[at + 9], + d[at + 10], d[at + 11], d[at + 12]); + case 14: + return c(d[at], d[at + 1], d[at + 2], d[at + 3], d[at + 4], d[at + 5], d[at + 6], d[at + 7], d[at + 8], d[at + 9], + d[at + 10], d[at + 11], d[at + 12], d[at + 13]); + case 15: + return c(d[at], d[at + 1], d[at + 2], d[at + 3], d[at + 4], d[at + 5], d[at + 6], d[at + 7], d[at + 8], d[at + 9], + d[at + 10], d[at + 11], d[at + 12], d[at + 13], d[at + 14]); + default: + return c(d[at], d[at + 1], d[at + 2], d[at + 3], d[at + 4], d[at + 5], d[at + 6], d[at + 7], d[at + 8], d[at + 9], + d[at + 10], d[at + 11], d[at + 12], d[at + 13], d[at + 14], d[at + 15]); + } +} + +/** The text of `length` Latin-1 bytes at `at`. */ +export function decodeLatin1(data: Uint8Array, at: number, length: number): string { + if (length <= 16) return decodeShortLatin1(data, at, length); + if (nodeText !== null) return nodeText.latin1Slice.call(data, at, at + length); + if (length <= mediumText) { + // In one call: concatenating the text would leave a string to flatten on first use. + codes.length = length; + for (let i = 0; i < length; i++) codes[i] = data[at + i]; + return String.fromCharCode.apply(null, codes); + } + const bytes = new Uint8Array(data.buffer, data.byteOffset + at, length), text = latin1Decoder.decode(bytes); + // windows-1252 reads most of 0x80-0x9F as wider chars; those are read one by one instead. + return wide.test(text) ? fromCodes(bytes) : text; +} + +/** + * The text of up to 24 UTF-16 code units at `at`, in one call: flat, unpaired surrogates kept, and in Chromium and + * Node cheaper than a native decoder or an array of codes. Each code unit is one DataView read, inline: a helper per + * unit was past V8's inlining budget in a function this large, and stayed a call. + */ +export function decodeShortUtf16(v: DataView, at: number, length: number): string { + const c = String.fromCharCode; + switch (length) { + case 0: return ""; + case 1: return c(v.getUint16(at, true)); + case 2: return c(v.getUint16(at, true), v.getUint16(at + 2, true)); + case 3: return c(v.getUint16(at, true), v.getUint16(at + 2, true), v.getUint16(at + 4, true)); + case 4: + return c(v.getUint16(at, true), v.getUint16(at + 2, true), v.getUint16(at + 4, true), v.getUint16(at + 6, true)); + case 5: + return c(v.getUint16(at, true), v.getUint16(at + 2, true), v.getUint16(at + 4, true), v.getUint16(at + 6, true), + v.getUint16(at + 8, true)); + case 6: + return c(v.getUint16(at, true), v.getUint16(at + 2, true), v.getUint16(at + 4, true), v.getUint16(at + 6, true), + v.getUint16(at + 8, true), v.getUint16(at + 10, true)); + case 7: + return c(v.getUint16(at, true), v.getUint16(at + 2, true), v.getUint16(at + 4, true), v.getUint16(at + 6, true), + v.getUint16(at + 8, true), v.getUint16(at + 10, true), v.getUint16(at + 12, true)); + case 8: + return c(v.getUint16(at, true), v.getUint16(at + 2, true), v.getUint16(at + 4, true), v.getUint16(at + 6, true), + v.getUint16(at + 8, true), v.getUint16(at + 10, true), v.getUint16(at + 12, true), v.getUint16(at + 14, true)); + case 9: + return c(v.getUint16(at, true), v.getUint16(at + 2, true), v.getUint16(at + 4, true), v.getUint16(at + 6, true), + v.getUint16(at + 8, true), v.getUint16(at + 10, true), v.getUint16(at + 12, true), v.getUint16(at + 14, true), + v.getUint16(at + 16, true)); + case 10: + return c(v.getUint16(at, true), v.getUint16(at + 2, true), v.getUint16(at + 4, true), v.getUint16(at + 6, true), + v.getUint16(at + 8, true), v.getUint16(at + 10, true), v.getUint16(at + 12, true), v.getUint16(at + 14, true), + v.getUint16(at + 16, true), v.getUint16(at + 18, true)); + case 11: + return c(v.getUint16(at, true), v.getUint16(at + 2, true), v.getUint16(at + 4, true), v.getUint16(at + 6, true), + v.getUint16(at + 8, true), v.getUint16(at + 10, true), v.getUint16(at + 12, true), v.getUint16(at + 14, true), + v.getUint16(at + 16, true), v.getUint16(at + 18, true), v.getUint16(at + 20, true)); + case 12: + return c(v.getUint16(at, true), v.getUint16(at + 2, true), v.getUint16(at + 4, true), v.getUint16(at + 6, true), + v.getUint16(at + 8, true), v.getUint16(at + 10, true), v.getUint16(at + 12, true), v.getUint16(at + 14, true), + v.getUint16(at + 16, true), v.getUint16(at + 18, true), v.getUint16(at + 20, true), v.getUint16(at + 22, true)); + case 13: + return c(v.getUint16(at, true), v.getUint16(at + 2, true), v.getUint16(at + 4, true), v.getUint16(at + 6, true), + v.getUint16(at + 8, true), v.getUint16(at + 10, true), v.getUint16(at + 12, true), v.getUint16(at + 14, true), + v.getUint16(at + 16, true), v.getUint16(at + 18, true), v.getUint16(at + 20, true), v.getUint16(at + 22, true), + v.getUint16(at + 24, true)); + case 14: + return c(v.getUint16(at, true), v.getUint16(at + 2, true), v.getUint16(at + 4, true), v.getUint16(at + 6, true), + v.getUint16(at + 8, true), v.getUint16(at + 10, true), v.getUint16(at + 12, true), v.getUint16(at + 14, true), + v.getUint16(at + 16, true), v.getUint16(at + 18, true), v.getUint16(at + 20, true), v.getUint16(at + 22, true), + v.getUint16(at + 24, true), v.getUint16(at + 26, true)); + case 15: + return c(v.getUint16(at, true), v.getUint16(at + 2, true), v.getUint16(at + 4, true), v.getUint16(at + 6, true), + v.getUint16(at + 8, true), v.getUint16(at + 10, true), v.getUint16(at + 12, true), v.getUint16(at + 14, true), + v.getUint16(at + 16, true), v.getUint16(at + 18, true), v.getUint16(at + 20, true), v.getUint16(at + 22, true), + v.getUint16(at + 24, true), v.getUint16(at + 26, true), v.getUint16(at + 28, true)); + case 16: + return c(v.getUint16(at, true), v.getUint16(at + 2, true), v.getUint16(at + 4, true), v.getUint16(at + 6, true), + v.getUint16(at + 8, true), v.getUint16(at + 10, true), v.getUint16(at + 12, true), v.getUint16(at + 14, true), + v.getUint16(at + 16, true), v.getUint16(at + 18, true), v.getUint16(at + 20, true), v.getUint16(at + 22, true), + v.getUint16(at + 24, true), v.getUint16(at + 26, true), v.getUint16(at + 28, true), v.getUint16(at + 30, true)); + case 17: + return c(v.getUint16(at, true), v.getUint16(at + 2, true), v.getUint16(at + 4, true), v.getUint16(at + 6, true), + v.getUint16(at + 8, true), v.getUint16(at + 10, true), v.getUint16(at + 12, true), v.getUint16(at + 14, true), + v.getUint16(at + 16, true), v.getUint16(at + 18, true), v.getUint16(at + 20, true), v.getUint16(at + 22, true), + v.getUint16(at + 24, true), v.getUint16(at + 26, true), v.getUint16(at + 28, true), v.getUint16(at + 30, true), + v.getUint16(at + 32, true)); + case 18: + return c(v.getUint16(at, true), v.getUint16(at + 2, true), v.getUint16(at + 4, true), v.getUint16(at + 6, true), + v.getUint16(at + 8, true), v.getUint16(at + 10, true), v.getUint16(at + 12, true), v.getUint16(at + 14, true), + v.getUint16(at + 16, true), v.getUint16(at + 18, true), v.getUint16(at + 20, true), v.getUint16(at + 22, true), + v.getUint16(at + 24, true), v.getUint16(at + 26, true), v.getUint16(at + 28, true), v.getUint16(at + 30, true), + v.getUint16(at + 32, true), v.getUint16(at + 34, true)); + case 19: + return c(v.getUint16(at, true), v.getUint16(at + 2, true), v.getUint16(at + 4, true), v.getUint16(at + 6, true), + v.getUint16(at + 8, true), v.getUint16(at + 10, true), v.getUint16(at + 12, true), v.getUint16(at + 14, true), + v.getUint16(at + 16, true), v.getUint16(at + 18, true), v.getUint16(at + 20, true), v.getUint16(at + 22, true), + v.getUint16(at + 24, true), v.getUint16(at + 26, true), v.getUint16(at + 28, true), v.getUint16(at + 30, true), + v.getUint16(at + 32, true), v.getUint16(at + 34, true), v.getUint16(at + 36, true)); + case 20: + return c(v.getUint16(at, true), v.getUint16(at + 2, true), v.getUint16(at + 4, true), v.getUint16(at + 6, true), + v.getUint16(at + 8, true), v.getUint16(at + 10, true), v.getUint16(at + 12, true), v.getUint16(at + 14, true), + v.getUint16(at + 16, true), v.getUint16(at + 18, true), v.getUint16(at + 20, true), v.getUint16(at + 22, true), + v.getUint16(at + 24, true), v.getUint16(at + 26, true), v.getUint16(at + 28, true), v.getUint16(at + 30, true), + v.getUint16(at + 32, true), v.getUint16(at + 34, true), v.getUint16(at + 36, true), v.getUint16(at + 38, true)); + case 21: + return c(v.getUint16(at, true), v.getUint16(at + 2, true), v.getUint16(at + 4, true), v.getUint16(at + 6, true), + v.getUint16(at + 8, true), v.getUint16(at + 10, true), v.getUint16(at + 12, true), v.getUint16(at + 14, true), + v.getUint16(at + 16, true), v.getUint16(at + 18, true), v.getUint16(at + 20, true), v.getUint16(at + 22, true), + v.getUint16(at + 24, true), v.getUint16(at + 26, true), v.getUint16(at + 28, true), v.getUint16(at + 30, true), + v.getUint16(at + 32, true), v.getUint16(at + 34, true), v.getUint16(at + 36, true), v.getUint16(at + 38, true), + v.getUint16(at + 40, true)); + case 22: + return c(v.getUint16(at, true), v.getUint16(at + 2, true), v.getUint16(at + 4, true), v.getUint16(at + 6, true), + v.getUint16(at + 8, true), v.getUint16(at + 10, true), v.getUint16(at + 12, true), v.getUint16(at + 14, true), + v.getUint16(at + 16, true), v.getUint16(at + 18, true), v.getUint16(at + 20, true), v.getUint16(at + 22, true), + v.getUint16(at + 24, true), v.getUint16(at + 26, true), v.getUint16(at + 28, true), v.getUint16(at + 30, true), + v.getUint16(at + 32, true), v.getUint16(at + 34, true), v.getUint16(at + 36, true), v.getUint16(at + 38, true), + v.getUint16(at + 40, true), v.getUint16(at + 42, true)); + case 23: + return c(v.getUint16(at, true), v.getUint16(at + 2, true), v.getUint16(at + 4, true), v.getUint16(at + 6, true), + v.getUint16(at + 8, true), v.getUint16(at + 10, true), v.getUint16(at + 12, true), v.getUint16(at + 14, true), + v.getUint16(at + 16, true), v.getUint16(at + 18, true), v.getUint16(at + 20, true), v.getUint16(at + 22, true), + v.getUint16(at + 24, true), v.getUint16(at + 26, true), v.getUint16(at + 28, true), v.getUint16(at + 30, true), + v.getUint16(at + 32, true), v.getUint16(at + 34, true), v.getUint16(at + 36, true), v.getUint16(at + 38, true), + v.getUint16(at + 40, true), v.getUint16(at + 42, true), v.getUint16(at + 44, true)); + default: + return c(v.getUint16(at, true), v.getUint16(at + 2, true), v.getUint16(at + 4, true), v.getUint16(at + 6, true), + v.getUint16(at + 8, true), v.getUint16(at + 10, true), v.getUint16(at + 12, true), v.getUint16(at + 14, true), + v.getUint16(at + 16, true), v.getUint16(at + 18, true), v.getUint16(at + 20, true), v.getUint16(at + 22, true), + v.getUint16(at + 24, true), v.getUint16(at + 26, true), v.getUint16(at + 28, true), v.getUint16(at + 30, true), + v.getUint16(at + 32, true), v.getUint16(at + 34, true), v.getUint16(at + 36, true), v.getUint16(at + 38, true), + v.getUint16(at + 40, true), v.getUint16(at + 42, true), v.getUint16(at + 44, true), v.getUint16(at + 46, true)); + } +} diff --git a/runtimes/typescript/src/runtime/writer.ts b/runtimes/typescript/src/runtime/writer.ts new file mode 100644 index 000000000..beb6b09dd --- /dev/null +++ b/runtimes/typescript/src/runtime/writer.ts @@ -0,0 +1,611 @@ +import { NinoDeferrals, inlineDepth, maxDepth, sectionFlag, tooDeep, type NinoDeferred } from "./deferrals.ts"; +import { NinoError } from "./error.ts"; +import { maxGridElements, maxGridLength } from "./grid.ts"; +import { littleEndian, swapBytes, type NinoNumbers } from "./numbers.ts"; +import { hexValues, maxDateMilliseconds, unixEpochMilliseconds } from "./scalars.ts"; +import { + headerSize, kernelAscii, kernelText, kernelWrite, kernels, loopText, nodeText, nonAscii, shortText, transfer, + utf8Encoder, wasm, wide, +} from "./text.ts"; + +/** The smallest buffer `serialize` writes its results into (see `NinoWriter.next`). */ +const slabSize = 64 * 1024; + +/** + * Writes values in Nino's format. Generated code writes a run of fixed-size values with one `reserve`, then each + * value into `view` at its offset. + */ +export class NinoWriter { + private buffer: Uint8Array = new Uint8Array(256); + /** The buffer as a DataView. Growing replaces it, so read it after `reserve`. */ + view = new DataView(this.buffer.buffer); + /** The offset of the next byte: the number of bytes written, unless `serialize` uses the writer. */ + pos = 0; + // buffer.length, as a field: a typed array's length costs more to read. + private end = 256; + // Where the value being written starts: 0, unless `serialize` uses the writer (see `next`). + private start = 0; + /** Open class bodies, counted by generated code (see `defer`). */ + depth = 0; + // Open regions, open struct bodies that can hold themselves, and the deferred bodies (made on the first one). + private regions = 0; + private structs = 0; + private deferrals: NinoDeferrals | null = null; + // The size of the last value `detach` returned. + private last = 0; + // Reference tracking: the number of each object of a tracked type written so far (made on the first). + private refs: Map | null = null; + + /** Moves past `size` bytes, growing the buffer if needed: returns where they start. */ + reserve(size: number): number { + const at = this.pos; + if (size > this.end - at) { + // Offsets handed out stay valid: the value's bytes keep their place in the new buffer. + const grown = new Uint8Array(Math.max(this.end * 2, at + size)); + grown.set(this.buffer.subarray(this.start, at), this.start); + this.buffer = grown; + this.view = new DataView(grown.buffer); + this.end = grown.length; + } + this.pos = at + size; + return at; + } + + /** + * The int32 `value` at `at` (reserved), as four byte stores: in Chromium cheaper than the view's setter at an + * unaligned offset, and the same in Node. + */ + private int32At(at: number, value: number): void { + const buffer = this.buffer; + buffer[at] = value; + buffer[at + 1] = value >> 8; + buffer[at + 2] = value >> 16; + buffer[at + 3] = value >> 24; + } + + /** The bytes written so far, copied. */ + toBytes(): Uint8Array { return this.buffer.slice(this.start, this.pos); } + + /** + * Starts a value after the last one `detach` returned, 8-byte aligned (so it can be viewed as wider typed arrays), + * in a new buffer when less room is left than the last value took (room for 16 such values, up to 1 MiB). + */ + next(): void { + let at = (this.pos + 7) & ~7; + // A new buffer when the room left is less than the last value took: values of one type are about one size, and + // growing a buffer copies what the value wrote so far. + const last = this.last; + if (this.end - at < Math.max(slabSize >> 4, last)) { + const size = Math.max(slabSize, Math.min(16 * last, 1 << 20), 2 * last); + this.buffer = new Uint8Array(size); + this.view = new DataView(this.buffer.buffer); + this.end = size; + at = 0; + } + this.start = this.pos = at; + this.begin(); + } + + /** + * Empties the writer, keeping its buffer: the next value is written from offset 0, and allocates nothing while it + * fits (see `serializeInto`). + */ + reset(): void { + this.start = this.pos = 0; + this.begin(); + } + + /** Starts a value: closes what a value that failed may have left open, and forgets the last value's references. */ + private begin(): void { + this.depth = this.regions = this.structs = 0; + this.deferrals = null; + this.refs = null; + } + + /** The value started by `next`, as a view of the buffer, which the writer does not write to again. */ + detach(): Uint8Array { + const size = this.pos - this.start; + this.last = size; + return new Uint8Array(this.buffer.buffer, this.start, size); + } + + /** The bytes written so far, without a copy: valid until the writer writes again. */ + written(): Uint8Array { return this.buffer.subarray(this.start, this.pos); } + + /** The size of the buffer. */ + get capacity(): number { return this.end; } + + /** Reserves a value copied as raw memory, zeroed (as Nino zeroes padding): returns where it starts. */ + raw(size: number): number { + const at = this.reserve(size); + this.buffer.fill(0, at, at + size); + return at; + } + + bool(value: boolean): void { const at = this.reserve(1); this.view.setUint8(at, value ? 1 : 0); } + u8(value: number): void { const at = this.reserve(1); this.view.setUint8(at, value); } + i8(value: number): void { const at = this.reserve(1); this.view.setInt8(at, value); } + u16(value: number): void { const at = this.reserve(2); this.view.setUint16(at, value, true); } + i16(value: number): void { const at = this.reserve(2); this.view.setInt16(at, value, true); } + u32(value: number): void { const at = this.reserve(4); this.view.setUint32(at, value, true); } + i32(value: number): void { this.int32At(this.reserve(4), value | 0); } + // A bigint out of range wraps to 64 bits, as setBig(U)Int64 converts it. + u64(value: bigint): void { const at = this.reserve(8); this.view.setBigUint64(at, value, true); } + i64(value: bigint): void { const at = this.reserve(8); this.view.setBigInt64(at, value, true); } + f32(value: number): void { const at = this.reserve(4); this.view.setFloat32(at, value, true); } + f64(value: number): void { const at = this.reserve(8); this.view.setFloat64(at, value, true); } + // "" has no char code (NaN), which a Uint16 converts to 0. + char(value: string): void { this.u16(value.charCodeAt(0)); } + guid(value: string): void { this.guidAt(this.reserve(16), value); } + dateTime(value: Date): void { this.dateTimeAt(this.reserve(8), value); } + timeSpan(ticks: bigint): void { this.i64(ticks); } + decimal(value: string): void { this.decimalAt(this.reserve(16), value); } + + /** `System.Guid` from its text form (`D`, `N` or `B`), at `at`. */ + guidAt(at: number, value: string): void { + const buffer = this.buffer; + let digit = 0; + for (let i = 0; i < value.length; i++) { + const c = value.charCodeAt(i), nibble = c < 128 ? hexValues[c] : -1; + if (nibble < 0) { + if (c === 45 || c === 123 || c === 125) continue; // - { } + digit = -1; + break; + } + if (digit === 32) { digit = -1; break; } + // Bytes 0-3, 4-5 and 6-7 are little-endian integers; 8-15 are bytes in order. + const byte = digit >> 1, index = byte < 4 ? 3 - byte : byte < 6 ? 9 - byte : byte < 8 ? 13 - byte : byte; + buffer[at + index] = digit & 1 ? buffer[at + index] | nibble : nibble << 4; + digit++; + } + if (digit !== 32) throw new NinoError(`invalid Guid "${value}".`); + } + + /** A UTC `System.DateTime` at `at`. */ + dateTimeAt(at: number, value: Date): void { + // (milliseconds since 0001) * 10000 as two 32-bit halves, exact in Number arithmetic (no BigInt). + const ms = value.getTime() + unixEpochMilliseconds; + if (!(ms >= 0 && ms < maxDateMilliseconds)) throw new NinoError(`date out of range: ${value.getTime()}.`); + const a = Math.floor(ms / 65536) * 10000, b = (ms % 65536) * 10000; + const low = (a % 65536) * 65536 + b; + this.view.setUint32(at, low % 4294967296, true); + this.view.setUint32(at + 4, (Math.floor(a / 65536) + Math.floor(low / 4294967296)) | 0x40000000, true); // UTC + } + + /** `System.Decimal` from its decimal text, at `at`. */ + decimalAt(at: number, value: string): void { + const view = this.view; + if (value === "0") { + view.setBigUint64(at, 0n); + view.setBigUint64(at + 8, 0n); + return; + } + const match = /^([+-])?(\d*)(?:\.(\d*))?$/.exec(value.trim()); + if (match === null || (match[2] + (match[3] ?? "")).length === 0) throw new NinoError(`invalid decimal "${value}".`); + const fraction = match[3] ?? "", text = match[2] + fraction || "0"; + if (fraction.length > 28) throw new NinoError(`decimal out of range "${value}".`); + let negative = match[1] === "-"; + // Up to 15 digits in exact Number arithmetic, else as a BigInt. + if (text.length <= 15) { + const units = Number(text); + negative &&= units !== 0; + view.setUint32(at + 4, 0, true); + view.setUint32(at + 8, units % 4294967296, true); + view.setUint32(at + 12, Math.floor(units / 4294967296), true); + } else { + const units = BigInt(text); + if (units >= 1n << 96n) throw new NinoError(`decimal out of range "${value}".`); + negative &&= units !== 0n; + view.setUint32(at + 4, Number(units >> 64n), true); + view.setBigUint64(at + 8, units, true); + } + view.setInt32(at, (fraction.length << 16) | (negative ? 0x80000000 : 0), true); + } + + /** + * Writes `value` (below 2^32) at `at` as a string header (wire-format spec §2.3.1): the value itself below 0x80, + * else 0x80 and a uint16 up to 0xFFFF, else 0x81 and a uint32. Returns the bytes it took (`headerSize(value)`). + */ + private headerAt(at: number, value: number): number { + const buffer = this.buffer; + if (value < 0x80) { + buffer[at] = value; + return 1; + } + if (value <= 0xffff) { + buffer[at] = 0x80; + buffer[at + 1] = value; + buffer[at + 2] = value >>> 8; + return 3; + } + buffer[at] = 0x81; + buffer[at + 1] = value; + buffer[at + 2] = value >>> 8; + buffer[at + 3] = value >>> 16; + buffer[at + 4] = value >>> 24; + return 5; + } + + /** A header on its own (null, empty, a UTF-8 string's counts). */ + header(value: number): void { + this.headerAt(this.reserve(headerSize(value)), value); + } + + /** A string (the default encoding): one byte per char when every char is at most U+00FF, else UTF-16. */ + string(value: string | null): void { + if (value === null || value === undefined) { this.u8(0); return; } + const length = value.length; + if (length <= (nodeText === null ? kernelWrite : shortText) && length < 64) { + // `narrow`, written out here: the common path stays one function (calls to `narrow` and `utf16` measured + // 8-12% slower in Chromium on short text, x64 and Arm64). Up to 63 chars: a one-byte header. + const at = this.reserve(1 + length), buffer = this.buffer, view = this.view; + // Four chars a store: one bounds check where a byte each took four. The first char is tested on its own, so + // text that starts above U+00FF reads one char, not four, before it is written as UTF-16. + let i = 0; + for (; i + 3 < length; i += 4) { + const a = value.charCodeAt(i); + if (a > 0xff) break; + const b = value.charCodeAt(i + 1), c = value.charCodeAt(i + 2), d = value.charCodeAt(i + 3); + if ((b | c | d) > 0xff) break; + view.setUint32(at + 1 + i, a | (b << 8) | (c << 16) | (d << 24), true); + } + for (; i < length; i++) { + const c = value.charCodeAt(i); + if (c > 0xff) break; + buffer[at + 1 + i] = c; + } + if (i === length) { + buffer[at] = 2 * length + 1; + return; + } + this.pos = at; + } else if (nodeText === null) { + // Out of line, so the short text above compiles as it did without the kernels. + this.longString(value, length); + return; + } else if (!wide.test(value)) { + this.latin1(value, length); + return; + } + this.wideText(value, length); + } + + /** + * The `length` chars of `value`, some above U+00FF, as UTF-16 code units after their header. Out of `string`, whose + * common path V8 then still inlines into its callers (with this in it, it was too large to: 5% on short ASCII). + */ + private wideText(value: string, length: number): void { + // Up to 63 chars a one-byte header, written here: through headerSize and headerAt it cost 5-10% on short text. + let start = 1, at: number; + if (length < 64) { + at = this.reserve(1 + 2 * length); + this.buffer[at] = 2 * length; + } else { + start = headerSize(2 * length); + at = this.reserve(start + 2 * length); + this.headerAt(at, 2 * length); + } + const o = at + start; + if (nodeText !== null && length >= 32) { + nodeText.ucs2Write.call(this.buffer, value, o, 2 * length); + return; + } + // Two chars a store. Up to 31 chars this costs less than Node's ucs2Write, whose call outweighs short text and + // which writes the chars twice at an odd offset (where a one-byte header leaves them): all but the last into an + // aligned buffer, then moved. A third faster on 1,000 strings of 16 to 20 chars. + const view = this.view; + let i = 0; + for (; i + 1 < length; i += 2) view.setUint32(o + 2 * i, value.charCodeAt(i) | (value.charCodeAt(i + 1) << 16), true); + if (i < length) view.setUint16(o + 2 * i, value.charCodeAt(i), true); + } + + /** + * The `length` chars of `value` one byte each, after their header, in one pass while every char fits in a byte. + * Returns false, writing nothing, at the first wider char. + */ + private narrow(value: string, length: number): boolean { + const start = headerSize(2 * length), at = this.reserve(start + length), buffer = this.buffer; + let i = 0; + for (; i < length; i++) { + const c = value.charCodeAt(i); + if (c > 0xff) break; + buffer[at + start + i] = c; + } + if (i === length) { + this.headerAt(at, 2 * length + 1); + return true; + } + this.pos = at; + return false; + } + + /** The `length` chars of `value`, every one at most U+00FF, one byte each after their header. */ + private latin1(value: string, length: number): void { + const start = headerSize(2 * length), at = this.reserve(start + length); + this.headerAt(at, 2 * length + 1); + this.encodeLatin1(value, at + start); + } + + /** Without Node's methods: the `length` chars of `value` as UTF-16 code units, after their header. */ + private utf16(value: string, length: number): void { + const start = headerSize(2 * length), at = this.reserve(start + 2 * length); + this.headerAt(at, 2 * length); + const view = this.view; + for (let i = 0; i < length; i++) view.setUint16(at + start + 2 * i, value.charCodeAt(i), true); + } + + /** `string` without Node's methods, for text longer than `kernelWrite`: the kernels, else JavaScript. */ + private longString(value: string, length: number): void { + if (length <= kernelText && (length <= kernelAscii || wide.test(value)) && this.stringKernels(value, length)) return; + if (length <= loopText) { + if (this.narrow(value, length)) return; + } else if (!wide.test(value)) { + this.latin1(value, length); + return; + } + this.utf16(value, length); + } + + /** + * `string` with the kernels (text of at most `kernelText` chars): one byte per char if every char fits, else UTF-16. + * Returns false, writing nothing, without them. + */ + private stringKernels(value: string, length: number): boolean { + const k = kernels === undefined ? wasm() : kernels; + if (k === null) return false; + const start = headerSize(2 * length); + if (k.narrow(value, length, transfer) === length) { + const at = this.reserve(start + length); + this.headerAt(at, 2 * length + 1); + this.buffer.set(k.bytes.subarray(transfer, transfer + length), at + start); + return true; + } + k.widen(length, transfer); + const at = this.reserve(start + 2 * length); + this.headerAt(at, 2 * length); + this.buffer.set(k.bytes.subarray(transfer, transfer + 2 * length), at + start); + return true; + } + + /** A string as UTF-8 (`[NinoUtf8]`). Unpaired surrogates are written as U+FFFD, as in .NET. */ + utf8(value: string | null): void { + if (value === null || value === undefined) { this.u8(0); return; } + const length = value.length; + if (length === 0) { this.u8(1); return; } + // The char count plus one, then the byte count: string headers. + const countSize = headerSize(length + 1), sizeSize = headerSize(length); + if (!nonAscii.test(value)) { + // ASCII: as many bytes as chars, the same as Latin-1. + const at = this.reserve(countSize + sizeSize + length); + this.headerAt(at, length + 1); + this.headerAt(at + countSize, length); + this.encodeLatin1(value, at + countSize + sizeSize); + return; + } + // At most 3 bytes per UTF-16 code unit; the bytes not written are given back. They go after a byte count as + // long as the char count's (there are at least as many bytes as chars), and move up when it is longer. + const at = this.reserve(countSize + 5 + 3 * length), text = at + countSize + sizeSize; + const { written } = utf8Encoder.encodeInto(value, new Uint8Array(this.buffer.buffer, this.buffer.byteOffset + text, 3 * length)); + this.headerAt(at, length + 1); + const actual = headerSize(written); + if (actual !== sizeSize) this.buffer.copyWithin(at + countSize + actual, text, text + written); + this.headerAt(at + countSize, written); + this.pos = at + countSize + actual + written; + } + + /** Text whose every char is at most U+00FF, one byte per char at `at` (reserved). */ + private encodeLatin1(value: string, at: number): void { + const length = value.length, buffer = this.buffer; + if (nodeText !== null && length > shortText) { + nodeText.latin1Write.call(buffer, value, at, length); + return; + } + // Here nodeText is null, or the text is short. + const k = length > kernelWrite && length <= kernelText ? (kernels === undefined ? wasm() : kernels) : null; + if (length > (k !== null ? kernelAscii : loopText)) { + // ASCII is the same in UTF-8, written in one native call; other text by the kernels or char by char below. + const { read, written } = utf8Encoder.encodeInto(value, new Uint8Array(buffer.buffer, at, length)); + if (read === length && written === length) return; + } + if (k !== null) { + k.narrow(value, length, transfer); + buffer.set(k.bytes.subarray(transfer, transfer + length), at); + return; + } + for (let i = 0; i < length; i++) buffer[at + i] = value.charCodeAt(i); + } + + /** A `byte[]`: length, then the bytes. */ + bytes(value: Uint8Array | null): void { + if (value === null || value === undefined) { this.i32(-1); return; } + this.i32(value.length); + const at = this.reserve(value.length); + this.buffer.set(value, at); + } + + /** An array or list of a fixed-size number type (`int[]`, `List`...): length, then its bytes as one block. */ + numbers(values: NinoNumbers | null): void { + if (values === null || values === undefined) { this.i32(-1); return; } + this.i32(values.length); + this.numberBlock(values); + } + + /** Writes a block of fixed-size numbers without a collection length. */ + numberBlock(values: NinoNumbers): void { + const bytes = values.byteLength; + const at = this.reserve(bytes); + this.buffer.set(new Uint8Array(values.buffer, values.byteOffset, bytes), at); + if (!littleEndian) swapBytes(this.buffer, at, at + bytes, values.BYTES_PER_ELEMENT); + } + + /** Writes exactly `rank` dimensions whose product equals the size of the rectangular array's flat data. */ + gridShape(rank: number, lengths: readonly number[], count: number): void { + if (lengths.length !== rank) throw new NinoError("invalid grid rank."); + let total = 1; + for (const length of lengths) { + if (!Number.isInteger(length) || length < 0 || length > maxGridLength) + throw new NinoError(`invalid length ${length}.`); + total *= length; + if (total > maxGridElements) throw new NinoError("invalid grid dimensions."); + } + if (total !== count) throw new NinoError("grid dimensions do not match the data length."); + for (const length of lengths) this.i32(length); + } + + + array(values: readonly T[] | null, write: (writer: NinoWriter, value: T) => void): void { + if (values === null || values === undefined) { this.i32(-1); return; } + this.i32(values.length); + for (let i = 0; i < values.length; i++) write(this, values[i]); + } + + set(values: ReadonlySet | null, write: (writer: NinoWriter, value: T) => void): void { + if (values === null || values === undefined) { this.i32(-1); return; } + this.i32(values.size); + for (const value of values) write(this, value); + } + + map(map: ReadonlyMap | null, writeKey: (writer: NinoWriter, key: K) => void, + writeValue: (writer: NinoWriter, value: V) => void): void { + if (map === null || map === undefined) { this.i32(-1); return; } + this.i32(map.size); + // The keys and the values side by side: for-of over the entries makes an array an entry. + for (let keys = map.keys(), values = map.values(), i = map.size; i > 0; i--) { + writeKey(this, keys.next().value as K); + writeValue(this, values.next().value as V); + } + } + + nullable(value: T | null, write: (writer: NinoWriter, value: T) => void): void { + if (value === null || value === undefined) { this.u8(0); return; } + this.u8(1); + write(this, value); + } + + /** Starts a version tolerant or keyed body (or a keyed member): returns where its length goes. */ + beginRegion(): number { + this.regions++; + return this.reserve(4); + } + + /** + * Ends the region started at `start`: writes its byte length. The outermost region is followed by the bodies + * deferred inside it, if any. + */ + endRegion(start: number): void { + if (--this.regions === 0 && this.deferrals !== null && this.deferrals.regionHead !== this.deferrals.region.length) { + this.writeSection(start); + return; + } + this.view.setInt32(start, this.pos - start - 4, true); + } + + /** + * Generated code, for a class body opened when `depth` bodies are open already (128, `NinoDepth.Inline`): queues + * `value`, whose body `body` writes later. Throws on a cycle: the deferred objects form chains (each deferred while + * writing the one before), and an object that comes back in its own chain would be written forever. It is compared + * with the chain's object at the last power-of-two length (Brent), as in .NET. + */ + defer(value: T, body: (writer: NinoWriter, value: T) => void): void { + const d = this.deferrals ??= new NinoDeferrals(); + const generation = d.currentGeneration; + const anchor = generation !== 0 && (generation & (generation - 1)) === 0 ? d.current : d.currentAnchor; + if (value === d.current || value === anchor) + throw new NinoError(`${(value as object).constructor.name} is part of a cycle, which cannot be written.`); + d.add({ value, body: body as (writer: NinoWriter, value: never) => void, position: this.pos, anchor, + generation: generation + 1 }, this.regions); + } + + /** Generated code: the body of a class that cannot be deferred (built by its constructor in .NET), in place. */ + deep(value: T, body: (writer: NinoWriter, value: T) => void): void { + const depth = this.depth; + if (depth >= maxDepth) throw tooDeep(); + this.depth = depth + 1; + body(this, value); + this.depth = depth; + } + + /** Generated code: closes a class body opened when `depth` bodies were open; at 0, writes the deferred bodies. */ + exitBody(depth: number): void { + this.depth = depth; + if (depth === 0 && this.deferrals !== null) this.writeTop(); + } + + /** + * Generated code: opens the body of a struct that can hold itself, which no class body counts (a value .NET could + * not read, or a cycle, throws). + */ + enterStruct(): void { + if (++this.structs + this.depth > maxDepth) throw tooDeep(); + } + + /** Generated code: closes a body opened by `enterStruct`. */ + exitStruct(): void { this.structs--; } + + /** + * Generated code: the reference header of an object of a tracked type (wire-format spec §7.9): 0 for null, its + * number for an object written before, or -1 for a new one: then it returns true, and the caller writes its body. + */ + ref(value: T | null | undefined): value is T { + if (value === null || value === undefined) { + this.i32(0); + return false; + } + const refs = this.refs ??= new Map(); + const index = refs.get(value); + if (index !== undefined) { + this.i32(index); + return false; + } + refs.set(value, refs.size + 1); + this.i32(-1); + return true; + } + + /** Every body is closed and no region is open: writes the bodies deferred outside regions, in order. */ + private writeTop(): void { + const d = this.deferrals!; + if (d.topActive || d.topHead === d.top.length) return; + d.topActive = true; + while (d.topHead < d.top.length) this.writeDeferred(d, d.top[d.topHead++], 1); + this.depth = 0; + d.top.length = d.topHead = 0; + d.topActive = false; + d.current = d.currentAnchor = null; + d.currentGeneration = 0; + } + + private writeDeferred(d: NinoDeferrals, item: NinoDeferred, depth: number): void { + d.current = item.value; + d.currentAnchor = item.anchor; + d.currentGeneration = item.generation; + this.depth = depth; + item.body(this, item.value as never); + } + + /** + * Ends the outermost region (its length at `lengthAt`): writes the bodies deferred inside it as a section of + * `(int32 key, int32 length, body)` entries, then the section's offset, and sets `sectionFlag` in its length. + */ + private writeSection(lengthAt: number): void { + const d = this.deferrals!, queue = d.region, start = lengthAt + 4, section = this.pos, depth = this.depth; + const current = d.current, anchor = d.currentAnchor, generation = d.currentGeneration; + const entryDepth = Math.min(depth, inlineDepth - 1) + 1; + this.regions = 1; + while (d.regionHead < queue.length) { + const item = queue[d.regionHead++], at = this.reserve(8); + this.view.setInt32(at, item.position - start, true); + this.writeDeferred(d, item, entryDepth); + this.view.setInt32(at + 4, this.pos - at - 8, true); + } + this.regions = 0; + this.depth = depth; + d.current = current; + d.currentAnchor = anchor; + d.currentGeneration = generation; + queue.length = d.regionHead = 0; + const at = this.reserve(4); + this.view.setInt32(at, section - start, true); + this.view.setInt32(lengthAt, (this.pos - start) | sectionFlag, true); + } +} diff --git a/runtimes/typescript/test/corpus.test.ts b/runtimes/typescript/test/corpus.test.ts index 390f84408..8e20a7a9a 100644 --- a/runtimes/typescript/test/corpus.test.ts +++ b/runtimes/typescript/test/corpus.test.ts @@ -1,8 +1,8 @@ // The conformance corpus (tests/conformance/corpus, or NINO_CORPUS) over the code nino-gen generates for its types // (test/generated/Nino.Conformance.ts, and Nino.Conformance.TypedArrays.ts with --numeric-arrays typed; Nino.Codegen.Tests // checks they are what nino-gen writes today): every valid case -// read and written back byte for byte, every malicious case and every strict prefix of a valid case rejected with a -// NinoError. Types TypeScript has no form for (Half, BigInteger, grids...) are left out by the generator with a +// round trip compared against its bytes, every malicious case and every strict prefix of a valid case rejected with a +// NinoError. Types TypeScript has no form for (Half, BigInteger...) are left out by the generator with a // warning; the cases of those types are skipped, and the list of them is checked so none is skipped by mistake. import assert from "node:assert/strict"; import { existsSync, readFileSync } from "node:fs"; @@ -20,11 +20,9 @@ if (!present && process.env.NINO_CORPUS_REQUIRED === "1") /** The types the generator leaves out of TypeScript (its warnings), and the types holding them. */ const notGenerated = new Set([ "Conformance.Floats", "Conformance.Scalars", "Conformance.Dates", "Conformance.BigValues", - "Conformance.Collections", "Conformance.TreeHolder", "Conformance.EmptyStruct", "Conformance.Empties", - "Conformance.Targets.Grid", "Conformance.Targets.BigSlot", "Conformance.Targets.VersionSlot", + "Conformance.TreeHolder", "Conformance.EmptyStruct", "Conformance.Empties", + "Conformance.Targets.BigSlot", "Conformance.Targets.VersionSlot", "Conformance.BclRawOffset", - // int?[,]: the slots of raw nullables in a set and a nested set are read in test/shapes.test.ts (NullableSlots). - "Conformance.NullableSequences", "Conformance.Targets.MaybeIntGrid", ]); /** The optional features of the corpus the generated code supports. */ @@ -91,6 +89,23 @@ function skipReason(codecs: Codecs, c: any): string | null { return null; } +// JavaScript Number may canonicalize NaN when a value goes through number[] storage. Check the one +// binary64 NaN in the Collections fixture as a Number and compare the rest of that fixture byte for byte. +// The typed-array fixture still uses byte equality throughout. +function assertRoundTrip(data: Uint8Array, expected: string, numberArrayNaN: boolean, message?: string): void { + const actual = Buffer.from(data).toString("hex"); + if (!numberArrayNaN) { + assert.equal(actual, expected, message); + return; + } + const nan = "000000000000f8ff"; + const at = expected.indexOf(nan); + assert.ok(at >= 0 && at % 2 === 0 && at === expected.lastIndexOf(nan)); + const view = new DataView(data.buffer, data.byteOffset, data.byteLength); + assert.ok(Number.isNaN(view.getFloat64(at / 2, true)), message); + assert.equal(actual.slice(0, at) + nan + actual.slice(at + nan.length), expected, message); +} + for (const [label, module] of [["generated code", generated], ["generated code with typed arrays", typedArrays]] as const) { const codecs = module as unknown as Codecs; describe(`conformance corpus over ${label}`, { skip: present ? false : "no corpus (set NINO_CORPUS)" }, () => { @@ -105,11 +120,12 @@ for (const [label, module] of [["generated code", generated], ["generated code w assert.ok(codec, `no generated codec for ${c.type}`); const data = new Uint8Array(readFileSync(join(corpus, "valid", name + ".bin"))); const expected = c.roundTrip ? Buffer.from(data).toString("hex") : c.reencoded; - assert.deepEqual(Buffer.from(serialize(codec, read(codec, data))).toString("hex"), expected); - assert.deepEqual(Buffer.from(serialize(codec, deserialized(codec, data))).toString("hex"), expected); + const numberArrayNaN = module === generated && name === "collections-values"; + assertRoundTrip(serialize(codec, read(codec, data)), expected, numberArrayNaN); + assertRoundTrip(serialize(codec, deserialized(codec, data)), expected, numberArrayNaN); // Read into the value of the type's previous case (or its own): the same value. const into = readInto(codec, data, read(codec, previous.get(c.type) ?? data)); - assert.deepEqual(Buffer.from(serialize(codec, into)).toString("hex"), expected, "read into a value"); + assertRoundTrip(serialize(codec, into), expected, numberArrayNaN, "read into a value"); previous.set(c.type, data); }); } diff --git a/runtimes/typescript/test/generated/Nino.Codegen.Tests.ts b/runtimes/typescript/test/generated/Nino.Codegen.Tests.ts index be2163c83..496caf41c 100644 --- a/runtimes/typescript/test/generated/Nino.Codegen.Tests.ts +++ b/runtimes/typescript/test/generated/Nino.Codegen.Tests.ts @@ -1,7 +1,7 @@ // Generated by nino-gen from Nino.Codegen.Tests: its [NinoType]s, read and written as Nino serializes them in .NET. // Do not edit: it is overwritten on every build. -import { NinoReader, NinoSubtypes, NinoWriter, type NinoCodec, type NinoNullable, type NullableSlot } from "../../src/nino.ts"; +import { NinoReader, NinoSubtypes, NinoWriter, type NinoCodec, type NinoGrid as NinoGrid$, type NinoNullable, type NullableSlot } from "../../src/nino.ts"; const types = new NinoSubtypes(); @@ -746,6 +746,36 @@ function writeBody$Node(w: NinoWriter, v: Node, c: Node$Codecs): void { w.endRegion(start); } +/** `Shapes.NullableGrids`. */ +export class NullableGrids { + grid: NinoGrid$[]> | null = null; + cube: NinoGrid$[]> | null = null; + cells: NinoGrid$[]> | null = null; +} + +function readNullableGrids(r: NinoReader, v: NullableGrids = new NullableGrids()): NullableGrids { + if (r.depth >= 128) return r.defer(v, readBody$NullableGrids); + readBody$NullableGrids(r, v); + return v; +} + +function writeNullableGrids(w: NinoWriter, v: NullableGrids): void { + if (w.depth >= 128) w.defer(v, writeBody$NullableGrids); + else writeBody$NullableGrids(w, v); +} + +function readBody$NullableGrids(r: NinoReader, v: NullableGrids): void { + v.grid = read$20(r, v.grid); + v.cube = read$21(r, v.cube); + v.cells = read$22(r, v.cells); +} + +function writeBody$NullableGrids(w: NinoWriter, v: NullableGrids): void { + write$20(w, v.grid); + write$21(w, v.cube); + write$22(w, v.cells); +} + /** `Shapes.NullableSlots`. */ export class NullableSlots { queue: NullableSlot[] | null = null; @@ -782,31 +812,31 @@ function writeNullableSlots(w: NinoWriter, v: NullableSlots): void { } function readBody$NullableSlots(r: NinoReader, v: NullableSlots): void { - v.queue = (v.queue == null ? read$20(r) : readInto$20(r, v.queue)); - v.stack = (v.stack == null ? read$21(r) : readInto$21(r, v.stack)); - v.linked = (v.linked == null ? read$22(r) : readInto$22(r, v.linked)); - v.sorted = (v.sorted == null ? read$23(r) : readInto$23(r, v.sorted)); - v.readOnly = (v.readOnly == null ? read$24(r) : readInto$24(r, v.readOnly)); - v.nested = (v.nested == null ? read$25(r) : readInto$25(r, v.nested)); + v.queue = (v.queue == null ? read$23(r) : readInto$23(r, v.queue)); + v.stack = (v.stack == null ? read$24(r) : readInto$24(r, v.stack)); + v.linked = (v.linked == null ? read$25(r) : readInto$25(r, v.linked)); + v.sorted = (v.sorted == null ? read$26(r) : readInto$26(r, v.sorted)); + v.readOnly = (v.readOnly == null ? read$27(r) : readInto$27(r, v.readOnly)); + v.nested = (v.nested == null ? read$28(r) : readInto$28(r, v.nested)); v.boxedSet = (v.boxedSet == null ? codec$4.read(r) : r.into(codec$4, v.boxedSet)); v.boxedNested = (v.boxedNested == null ? codec$5.read(r) : r.into(codec$5, v.boxedNested)); - v.map = (v.map == null ? read$26(r) : readInto$26(r, v.map)); + v.map = (v.map == null ? read$29(r) : readInto$29(r, v.map)); v.boxedMap = (v.boxedMap == null ? codec$6.read(r) : r.into(codec$6, v.boxedMap)); - v.tuples = (v.tuples == null ? read$27(r) : readInto$27(r, v.tuples)); + v.tuples = (v.tuples == null ? read$30(r) : readInto$30(r, v.tuples)); } function writeBody$NullableSlots(w: NinoWriter, v: NullableSlots): void { - write$20(w, v.queue); - write$21(w, v.stack); - write$22(w, v.linked); - write$23(w, v.sorted); - write$24(w, v.readOnly); - write$25(w, v.nested); + write$23(w, v.queue); + write$24(w, v.stack); + write$25(w, v.linked); + write$26(w, v.sorted); + write$27(w, v.readOnly); + write$28(w, v.nested); codec$4.write(w, v.boxedSet); codec$5.write(w, v.boxedNested); - write$26(w, v.map); + write$29(w, v.map); codec$6.write(w, v.boxedMap); - write$27(w, v.tuples); + write$30(w, v.tuples); } /** `Shapes.Generic.Open`. */ @@ -874,12 +904,12 @@ function writeOpenHolder(w: NinoWriter, v: OpenHolder, c: OpenHolder$Codec function readBody$OpenHolder(r: NinoReader, v: OpenHolder, c: OpenHolder$Codecs): void { v.inner = (v.inner == null ? c.s0.read(r) : r.into(c.s0, v.inner)); - v.all = (v.all == null ? read$28(r, c) : readInto$28(r, c, v.all)); + v.all = (v.all == null ? read$31(r, c) : readInto$31(r, c, v.all)); } function writeBody$OpenHolder(w: NinoWriter, v: OpenHolder, c: OpenHolder$Codecs): void { c.s0.write(w, v.inner); - write$28(w, v.all, c); + write$31(w, v.all, c); } /** `Shapes.Generic.OpenHolderUse`. */ @@ -1001,13 +1031,13 @@ function writePicks(w: NinoWriter, v: Picks): void { function readBody$Picks(r: NinoReader, v: Picks): void { v.pick = readPick(r); - v.many = (v.many == null ? read$29(r) : readInto$29(r, v.many)); + v.many = (v.many == null ? read$32(r) : readInto$32(r, v.many)); v.measure = readMeasure(r); } function writeBody$Picks(w: NinoWriter, v: Picks): void { writePick(w, v.pick); - write$29(w, v.many); + write$32(w, v.many); writeMeasure(w, v.measure); } @@ -1178,12 +1208,12 @@ function writeStrides(w: NinoWriter, v: Strides): void { } function readBody$Strides(r: NinoReader, v: Strides): void { - v.cells = (v.cells == null ? read$24(r) : readInto$24(r, v.cells)); + v.cells = (v.cells == null ? read$27(r) : readInto$27(r, v.cells)); v.boxed = (v.boxed == null ? codec$8.read(r) : r.into(codec$8, v.boxed)); } function writeBody$Strides(w: NinoWriter, v: Strides): void { - write$24(w, v.cells); + write$27(w, v.cells); codec$8.write(w, v.boxed); } @@ -1296,13 +1326,13 @@ function readBody$Uses(r: NinoReader, v: Uses): void { v.pair = (v.pair == null ? codec$13.read(r) : r.into(codec$13, v.pair)); v.nested = (v.nested == null ? codec$14.read(r) : r.into(codec$14, v.nested)); v.mixed = (v.mixed == null ? codec$16.read(r) : r.into(codec$16, v.mixed)); - v.boxes = (v.boxes == null ? read$30(r) : readInto$30(r, v.boxes)); + v.boxes = (v.boxes == null ? read$33(r) : readInto$33(r, v.boxes)); v.bag = (v.bag == null ? codec$17.read(r) : r.into(codec$17, v.bag)); v.chain = (v.chain == null ? codec$18.read(r) : r.into(codec$18, v.chain)); v.thing = (v.thing == null ? codec$19.read(r) : r.into(codec$19, v.thing)); v.array = (v.array == null ? codec$20.read(r) : r.into(codec$20, v.array)); v.complex = (v.complex == null ? codec$21.read(r) : r.into(codec$21, v.complex)); - v.pairs = (v.pairs == null ? read$31(r) : readInto$31(r, v.pairs)); + v.pairs = (v.pairs == null ? read$34(r) : readInto$34(r, v.pairs)); v.raw = (v.raw == null ? codec$23.read(r) : r.into(codec$23, v.raw)); v.tuple = (v.tuple == null ? codec$24.read(r) : r.into(codec$24, v.tuple)); v.maybe = (v.maybe == null ? codec$25.read(r) : r.into(codec$25, v.maybe)); @@ -1318,13 +1348,13 @@ function writeBody$Uses(w: NinoWriter, v: Uses): void { codec$13.write(w, v.pair); codec$14.write(w, v.nested); codec$16.write(w, v.mixed); - write$30(w, v.boxes); + write$33(w, v.boxes); codec$17.write(w, v.bag); codec$18.write(w, v.chain); codec$19.write(w, v.thing); codec$20.write(w, v.array); codec$21.write(w, v.complex); - write$31(w, v.pairs); + write$34(w, v.pairs); codec$23.write(w, v.raw); codec$24.write(w, v.tuple); codec$25.write(w, v.maybe); @@ -1393,13 +1423,13 @@ function readMeasure(r: NinoReader): Measure | null { break; } case -217079013: { - const value = read$32(r); + const value = read$35(r); if (value === null) throw r.invalidCase(id); v = { case: "ListInt32", value }; break; } case -1803246716: { - const value = read$33(r); + const value = read$36(r); if (value === null) throw r.invalidCase(id); v = { case: "ListString", value }; break; @@ -1432,12 +1462,12 @@ function writeMeasure(w: NinoWriter, v: Measure | null): void { } case "ListInt32": { w.i32(-217079013); - write$32(w, v.value); + write$35(w, v.value); break; } case "ListString": { w.i32(-1803246716); - write$33(w, v.value); + write$36(w, v.value); break; } default: @@ -1594,7 +1624,7 @@ export class Recursive { function readRecursive(r: NinoReader, v: Recursive = new Recursive()): Recursive { r.enterStruct(); v.value = r.i32(); - v.children = (v.children == null ? read$34(r) : readInto$34(r, v.children)); + v.children = (v.children == null ? read$37(r) : readInto$37(r, v.children)); r.exitStruct(); return v; } @@ -1602,7 +1632,7 @@ function readRecursive(r: NinoReader, v: Recursive = new Recursive()): Recursive function writeRecursive(w: NinoWriter, v: Recursive): void { w.enterStruct(); w.i32(v.value); - write$34(w, v.children); + write$37(w, v.children); w.exitStruct(); } @@ -1641,6 +1671,7 @@ types.add(66748393, NinoGrid, readNinoGrid, writeNinoGrid); types.add(-644355297, NinoNullableArgs, readNinoNullableArgs, writeNinoNullableArgs); types.add(628271052, NinoNullableRaw, readNinoNullableRaw, writeNinoNullableRaw); types.add(-679804941, NinoNullableRawWide, readNinoNullableRawWide, writeNinoNullableRawWide); +types.add(-2136772539, NullableGrids, readNullableGrids, writeNullableGrids); types.add(988871401, NullableSlots, readNullableSlots, writeNullableSlots); types.add(-1638490777, OpenHolderUse, readOpenHolderUse, writeOpenHolderUse); types.add(-91676345, OpenUse, readOpenUse, writeOpenUse); @@ -1793,6 +1824,13 @@ export const NinoNullableRawWideCodec: NinoCodec = { }, readInto: (r, v) => (r.present() ? (v == null ? readNinoNullableRawWide(r) : readNinoNullableRawWide(r, v!)) : null), }; +export const NullableGridsCodec: NinoCodec = { + read: (r) => (r.present() ? readNullableGrids(r) : null), + write: (w, v) => { + if (v === null || v === undefined) w.u8(0); else { w.u8(1); writeNullableGrids(w, v); } + }, + readInto: (r, v) => (r.present() ? (v == null ? readNullableGrids(r) : readNullableGrids(r, v!)) : null), +}; export const NullableSlotsCodec: NinoCodec = { read: (r) => (r.present() ? readNullableSlots(r) : null), write: (w, v) => { @@ -2188,15 +2226,15 @@ const slot$1: NinoCodec | null> = { }, }; -const codec$0 = BoxCodec>({ read: (r) => read$35(r), write: (w, v) => { write$35(w, v); } }); -const codec$1 = BoxCodec>({ read: (r) => read$36(r), write: (w, v) => { write$36(w, v); } }); -const codec$2 = BoxCodec[] | null>({ read: (r) => read$37(r), write: (w, v) => { write$37(w, v); } }); -const codec$3 = BoxCodec[] | null>({ read: (r) => read$38(r), write: (w, v) => { write$38(w, v); } }); -const codec$4 = BoxCodec> | null>({ read: (r) => read$23(r), write: (w, v) => { write$23(w, v); } }); -const codec$5 = BoxCodec<(Set> | null)[] | null>({ read: (r) => read$40(r), write: (w, v) => { write$40(w, v); } }); -const codec$6 = BoxCodec | null>({ read: (r) => read$26(r), write: (w, v) => { write$26(w, v); } }); +const codec$0 = BoxCodec>({ read: (r) => read$38(r), write: (w, v) => { write$38(w, v); } }); +const codec$1 = BoxCodec>({ read: (r) => read$39(r), write: (w, v) => { write$39(w, v); } }); +const codec$2 = BoxCodec[] | null>({ read: (r) => read$40(r), write: (w, v) => { write$40(w, v); } }); +const codec$3 = BoxCodec[] | null>({ read: (r) => read$41(r), write: (w, v) => { write$41(w, v); } }); +const codec$4 = BoxCodec> | null>({ read: (r) => read$26(r), write: (w, v) => { write$26(w, v); } }); +const codec$5 = BoxCodec<(Set> | null)[] | null>({ read: (r) => read$43(r), write: (w, v) => { write$43(w, v); } }); +const codec$6 = BoxCodec | null>({ read: (r) => read$29(r), write: (w, v) => { write$29(w, v); } }); const codec$7 = OpenHolderCodec({ read: (r) => r.i64(), write: (w, v) => { w.i64(v); } }, slot$0); -const codec$8 = BoxCodec[] | null>({ read: (r) => read$24(r), write: (w, v) => { write$24(w, v); } }); +const codec$8 = BoxCodec[] | null>({ read: (r) => read$27(r), write: (w, v) => { write$27(w, v); } }); const codec$9 = BoxCodec({ read: (r) => r.i64(), write: (w, v) => { w.i64(v); } }); const codec$10 = KeysCodec | null>(codec$9); const codec$11 = BoxCodec({ read: (r) => r.i32(), write: (w, v) => { w.i32(v); } }); @@ -2208,7 +2246,7 @@ const codec$16 = BoxCodec>(codec$15); const codec$17 = BagCodec | null>(codec$9); const codec$18 = NodeCodec({ read: (r) => r.string(), write: (w, v) => { w.string(v); } }); const codec$19 = BoxCodec({ read: (r) => IThingCodec.read(r), write: (w, v) => { IThingCodec.write(w, v); } }); -const codec$20 = BoxCodec({ read: (r) => read$32(r), write: (w, v) => { write$32(w, v); } }); +const codec$20 = BoxCodec({ read: (r) => read$35(r), write: (w, v) => { write$35(w, v); } }); const codec$21 = PairCodec | null, Map | null>(codec$11, { read: (r) => read$6(r), write: (w, v) => { write$6(w, v); } }); const codec$22 = PairCodec({ read: (r) => r.i32(), write: (w, v) => { w.i32(v); } }, { read: (r) => r.i32(), write: (w, v) => { w.i32(v); } }); const codec$23 = RawPairCodec({ read: (r) => r.i32(), write: (w, v) => { w.i32(v); } }); @@ -2247,6 +2285,7 @@ export function ninoCodecOf(name: string): NinoCodec | undefined { case "Shapes.NinoNullableArgs": return NinoNullableArgsCodec; case "Shapes.NinoNullableRaw": return NinoNullableRawCodec; case "Shapes.NinoNullableRawWide": return NinoNullableRawWideCodec; + case "Shapes.NullableGrids": return NullableGridsCodec; case "Shapes.NullableSlots": return NullableSlotsCodec; case "Shapes.Generic.OpenHolderUse": return OpenHolderUseCodec; case "Shapes.Generic.OpenUse": return OpenUseCodec; @@ -2860,7 +2899,79 @@ function write$19(w: NinoWriter, values: readonly HoldsWideNinoNullable[] | null } } -function read$20(r: NinoReader): NullableSlot[] | null { +function read$20(r: NinoReader, cur?: NinoGrid$[]> | null): NinoGrid$[]> | null { + const shape = r.gridShape(2, 8); + if (shape === null) return null; + const { lengths, count } = shape; + const reuse = cur != null && lengths.length === cur.lengths.length && lengths.every((n, i) => n === cur.lengths[i]); + const values = reuse ? cur.data : new Array>(r.capacity(count)); + for (let i = 0, at = r.take(count * 8); i < count; i++, at += 8) values[i] = (r.presentAt(at) ? r.view.getInt32(at + 4, true) : null); + if (values.length !== count) values.length = count; + if (reuse) return cur; + return { lengths, data: values }; +} + +function read$21(r: NinoReader, cur?: NinoGrid$[]> | null): NinoGrid$[]> | null { + const shape = r.gridShape(3, 16); + if (shape === null) return null; + const { lengths, count } = shape; + const reuse = cur != null && lengths.length === cur.lengths.length && lengths.every((n, i) => n === cur.lengths[i]); + const values = reuse ? cur.data : new Array>(r.capacity(count)); + for (let i = 0, at = r.take(count * 16); i < count; i++, at += 16) values[i] = (r.presentAt(at) ? r.view.getBigInt64(at + 8, true) : null); + if (values.length !== count) values.length = count; + if (reuse) return cur; + return { lengths, data: values }; +} + +function read$22(r: NinoReader, cur?: NinoGrid$[]> | null): NinoGrid$[]> | null { + const shape = r.gridShape(2, 16); + if (shape === null) return null; + const { lengths, count } = shape; + const reuse = cur != null && lengths.length === cur.lengths.length && lengths.every((n, i) => n === cur.lengths[i]); + const values = reuse ? cur.data : new Array>(r.capacity(count)); + for (let i = 0, at = r.take(count * 16); i < count; i++, at += 16) values[i] = (r.presentAt(at) ? readTupleCell(r, at + 4) : null); + if (values.length !== count) values.length = count; + if (reuse) return cur; + return { lengths, data: values }; +} + +function write$20(w: NinoWriter, grid: NinoGrid$[]> | null): void { + if (grid == null) { w.i32(-1); return; } + const values = grid.data; + w.gridShape(2, grid.lengths, values.length); + let at = w.raw(values.length * 8); + for (let i = 0; i < values.length; i++) { + const value = values[i]; + if (value !== null && value !== undefined) { w.view.setUint8(at, 1); w.view.setInt32(at + 4, value, true); } + at += 8; + } +} + +function write$21(w: NinoWriter, grid: NinoGrid$[]> | null): void { + if (grid == null) { w.i32(-1); return; } + const values = grid.data; + w.gridShape(3, grid.lengths, values.length); + let at = w.raw(values.length * 16); + for (let i = 0; i < values.length; i++) { + const value = values[i]; + if (value !== null && value !== undefined) { w.view.setUint8(at, 1); w.view.setBigInt64(at + 8, value, true); } + at += 16; + } +} + +function write$22(w: NinoWriter, grid: NinoGrid$[]> | null): void { + if (grid == null) { w.i32(-1); return; } + const values = grid.data; + w.gridShape(2, grid.lengths, values.length); + let at = w.raw(values.length * 16); + for (let i = 0; i < values.length; i++) { + const value = values[i]; + if (value !== null && value !== undefined) { w.view.setUint8(at, 1); writeTupleCell(w, at + 4, value); } + at += 16; + } +} + +function read$23(r: NinoReader): NullableSlot[] | null { const length = r.length(); if (length < 0) return null; const values = new Array>(r.capacity(length)); @@ -2868,7 +2979,7 @@ function read$20(r: NinoReader): NullableSlot[] | null { return values; } -function readInto$20(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null { +function readInto$23(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -2877,7 +2988,7 @@ function readInto$20(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null { +function read$24(r: NinoReader): NullableSlot[] | null { const length = r.length(); if (length < 0) return null; const values = new Array>(r.capacity(length)); @@ -2885,7 +2996,7 @@ function read$21(r: NinoReader): NullableSlot[] | null { return values; } -function readInto$21(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null { +function readInto$24(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -2894,7 +3005,7 @@ function readInto$21(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null { +function read$25(r: NinoReader): NullableSlot[] | null { const length = r.length(); if (length < 0) return null; const values = new Array>(r.capacity(length)); @@ -2902,7 +3013,7 @@ function read$22(r: NinoReader): NullableSlot[] | null { return values; } -function readInto$22(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null { +function readInto$25(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -2911,7 +3022,7 @@ function readInto$22(r: NinoReader, cur: NullableSlot[]): NullableSlot> | null { +function read$26(r: NinoReader): Set> | null { const length = r.length(); if (length < 0) return null; const values = new Set>(); @@ -2921,7 +3032,7 @@ function read$23(r: NinoReader): Set> | null { return values; } -function readInto$23(r: NinoReader, cur: Set>): Set> | null { +function readInto$26(r: NinoReader, cur: Set>): Set> | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -2932,7 +3043,7 @@ function readInto$23(r: NinoReader, cur: Set>): Set[] | null { +function read$27(r: NinoReader): NullableSlot[] | null { const length = r.length(); if (length < 0) return null; const values = new Array>(r.capacity(length)); @@ -2940,7 +3051,7 @@ function read$24(r: NinoReader): NullableSlot[] | null { return values; } -function readInto$24(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null { +function readInto$27(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -2949,24 +3060,24 @@ function readInto$24(r: NinoReader, cur: NullableSlot[]): NullableSlo return values; } -function read$25(r: NinoReader): (NullableSlot[] | null)[] | null { +function read$28(r: NinoReader): (NullableSlot[] | null)[] | null { const length = r.length(); if (length < 0) return null; const values = new Array[] | null>(r.capacity(length)); - for (let i = 0; i < length; i++) values[i] = read$20(r); + for (let i = 0; i < length; i++) values[i] = read$23(r); return values; } -function readInto$25(r: NinoReader, cur: (NullableSlot[] | null)[]): (NullableSlot[] | null)[] | null { +function readInto$28(r: NinoReader, cur: (NullableSlot[] | null)[]): (NullableSlot[] | null)[] | null { const length = r.length(); if (length < 0) return null; const values = cur; - for (let i = 0; i < length; i++) values[i] = (values[i] == null ? read$20(r) : readInto$20(r, values[i]!)); + for (let i = 0; i < length; i++) values[i] = (values[i] == null ? read$23(r) : readInto$23(r, values[i]!)); if (values.length !== length) values.length = length; return values; } -function read$26(r: NinoReader): Map | null { +function read$29(r: NinoReader): Map | null { const length = r.length(); if (length < 0) return null; const map = new Map(); @@ -2979,7 +3090,7 @@ function read$26(r: NinoReader): Map | null { return map; } -function readInto$26(r: NinoReader, cur: Map): Map | null { +function readInto$29(r: NinoReader, cur: Map): Map | null { const length = r.length(); if (length < 0) return null; const map = cur; @@ -2993,7 +3104,7 @@ function readInto$26(r: NinoReader, cur: Map): Map(r.capacity(length)); @@ -3001,7 +3112,7 @@ function read$27(r: NinoReader): ([number, number | null])[] | null { return values; } -function readInto$27(r: NinoReader, cur: ([number, number | null])[]): ([number, number | null])[] | null { +function readInto$30(r: NinoReader, cur: ([number, number | null])[]): ([number, number | null])[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -3010,7 +3121,7 @@ function readInto$27(r: NinoReader, cur: ([number, number | null])[]): ([number, return values; } -function write$20(w: NinoWriter, values: readonly NullableSlot[] | null): void { +function write$23(w: NinoWriter, values: readonly NullableSlot[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -3024,7 +3135,7 @@ function write$20(w: NinoWriter, values: readonly NullableSlot[] | null) } } -function write$21(w: NinoWriter, values: readonly NullableSlot[] | null): void { +function write$24(w: NinoWriter, values: readonly NullableSlot[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -3038,7 +3149,7 @@ function write$21(w: NinoWriter, values: readonly NullableSlot[] | null) } } -function write$22(w: NinoWriter, values: readonly NullableSlot[] | null): void { +function write$25(w: NinoWriter, values: readonly NullableSlot[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -3052,7 +3163,7 @@ function write$22(w: NinoWriter, values: readonly NullableSlot[] | null) } } -function write$23(w: NinoWriter, values: ReadonlySet> | null): void { +function write$26(w: NinoWriter, values: ReadonlySet> | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -3065,7 +3176,7 @@ function write$23(w: NinoWriter, values: ReadonlySet> | nul } } -function write$24(w: NinoWriter, values: readonly NullableSlot[] | null): void { +function write$27(w: NinoWriter, values: readonly NullableSlot[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -3079,7 +3190,7 @@ function write$24(w: NinoWriter, values: readonly NullableSlot[] | nu } } -function write$25(w: NinoWriter, values: readonly (NullableSlot[] | null)[] | null): void { +function write$28(w: NinoWriter, values: readonly (NullableSlot[] | null)[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -3087,11 +3198,11 @@ function write$25(w: NinoWriter, values: readonly (NullableSlot[] | null w.i32(values.length); for (let i = 0; i < values.length; i++) { const value = values[i]; - write$20(w, value); + write$23(w, value); } } -function write$26(w: NinoWriter, map: ReadonlyMap | null): void { +function write$29(w: NinoWriter, map: ReadonlyMap | null): void { if (map === null || map === undefined) { w.i32(-1); return; @@ -3104,7 +3215,7 @@ function write$26(w: NinoWriter, map: ReadonlyMap | null) } } -function write$27(w: NinoWriter, values: readonly ([number, number | null])[] | null): void { +function write$30(w: NinoWriter, values: readonly ([number, number | null])[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -3116,7 +3227,7 @@ function write$27(w: NinoWriter, values: readonly ([number, number | null])[] | } } -function read$28(r: NinoReader, c: OpenHolder$Codecs): (Open | null)[] | null { +function read$31(r: NinoReader, c: OpenHolder$Codecs): (Open | null)[] | null { const length = r.length(); if (length < 0) return null; const values = new Array | null>(r.capacity(length)); @@ -3124,7 +3235,7 @@ function read$28(r: NinoReader, c: OpenHolder$Codecs): (Open | null)[] return values; } -function readInto$28(r: NinoReader, c: OpenHolder$Codecs, cur: (Open | null)[]): (Open | null)[] | null { +function readInto$31(r: NinoReader, c: OpenHolder$Codecs, cur: (Open | null)[]): (Open | null)[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -3133,7 +3244,7 @@ function readInto$28(r: NinoReader, c: OpenHolder$Codecs, cur: (Open | return values; } -function write$28(w: NinoWriter, values: readonly (Open | null)[] | null, c: OpenHolder$Codecs): void { +function write$31(w: NinoWriter, values: readonly (Open | null)[] | null, c: OpenHolder$Codecs): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -3145,7 +3256,7 @@ function write$28(w: NinoWriter, values: readonly (Open | null)[] | null, } } -function read$29(r: NinoReader): (Pick | null)[] | null { +function read$32(r: NinoReader): (Pick | null)[] | null { const length = r.length(); if (length < 0) return null; const values = new Array(r.capacity(length)); @@ -3153,7 +3264,7 @@ function read$29(r: NinoReader): (Pick | null)[] | null { return values; } -function readInto$29(r: NinoReader, cur: (Pick | null)[]): (Pick | null)[] | null { +function readInto$32(r: NinoReader, cur: (Pick | null)[]): (Pick | null)[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -3162,7 +3273,7 @@ function readInto$29(r: NinoReader, cur: (Pick | null)[]): (Pick | null)[] | nul return values; } -function write$29(w: NinoWriter, values: readonly (Pick | null)[] | null): void { +function write$32(w: NinoWriter, values: readonly (Pick | null)[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -3174,7 +3285,7 @@ function write$29(w: NinoWriter, values: readonly (Pick | null)[] | null): void } } -function read$30(r: NinoReader): (Box | null)[] | null { +function read$33(r: NinoReader): (Box | null)[] | null { const length = r.length(); if (length < 0) return null; const values = new Array | null>(r.capacity(length)); @@ -3182,7 +3293,7 @@ function read$30(r: NinoReader): (Box | null)[] | null { return values; } -function readInto$30(r: NinoReader, cur: (Box | null)[]): (Box | null)[] | null { +function readInto$33(r: NinoReader, cur: (Box | null)[]): (Box | null)[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -3191,7 +3302,7 @@ function readInto$30(r: NinoReader, cur: (Box | null)[]): (Box | return values; } -function read$31(r: NinoReader): Map> | null { +function read$34(r: NinoReader): Map> | null { const length = r.length(); if (length < 0) return null; const map = new Map>(); @@ -3204,7 +3315,7 @@ function read$31(r: NinoReader): Map> | null return map; } -function readInto$31(r: NinoReader, cur: Map>): Map> | null { +function readInto$34(r: NinoReader, cur: Map>): Map> | null { const length = r.length(); if (length < 0) return null; const map = cur; @@ -3218,7 +3329,7 @@ function readInto$31(r: NinoReader, cur: Map return map; } -function write$30(w: NinoWriter, values: readonly (Box | null)[] | null): void { +function write$33(w: NinoWriter, values: readonly (Box | null)[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -3230,7 +3341,7 @@ function write$30(w: NinoWriter, values: readonly (Box | null)[] | null) } } -function write$31(w: NinoWriter, map: ReadonlyMap> | null): void { +function write$34(w: NinoWriter, map: ReadonlyMap> | null): void { if (map === null || map === undefined) { w.i32(-1); return; @@ -3243,7 +3354,7 @@ function write$31(w: NinoWriter, map: ReadonlyMap(r.capacity(length)); @@ -3251,7 +3362,7 @@ function read$32(r: NinoReader): number[] | null { return values; } -function read$33(r: NinoReader): (string | null)[] | null { +function read$36(r: NinoReader): (string | null)[] | null { const length = r.length(); if (length < 0) return null; const values = new Array(r.capacity(length)); @@ -3259,7 +3370,7 @@ function read$33(r: NinoReader): (string | null)[] | null { return values; } -function write$32(w: NinoWriter, values: readonly number[] | null): void { +function write$35(w: NinoWriter, values: readonly number[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -3273,7 +3384,7 @@ function write$32(w: NinoWriter, values: readonly number[] | null): void { } } -function write$33(w: NinoWriter, values: readonly (string | null)[] | null): void { +function write$36(w: NinoWriter, values: readonly (string | null)[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -3285,7 +3396,7 @@ function write$33(w: NinoWriter, values: readonly (string | null)[] | null): voi } } -function read$34(r: NinoReader): Recursive[] | null { +function read$37(r: NinoReader): Recursive[] | null { const length = r.length(); if (length < 0) return null; const values = new Array(r.capacity(length)); @@ -3293,7 +3404,7 @@ function read$34(r: NinoReader): Recursive[] | null { return values; } -function readInto$34(r: NinoReader, cur: Recursive[]): Recursive[] | null { +function readInto$37(r: NinoReader, cur: Recursive[]): Recursive[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -3302,7 +3413,7 @@ function readInto$34(r: NinoReader, cur: Recursive[]): Recursive[] | null { return values; } -function write$34(w: NinoWriter, values: readonly Recursive[] | null): void { +function write$37(w: NinoWriter, values: readonly Recursive[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -3314,27 +3425,27 @@ function write$34(w: NinoWriter, values: readonly Recursive[] | null): void { } } -function read$35(r: NinoReader): NinoNullable { +function read$38(r: NinoReader): NinoNullable { const at = r.take(8); return (r.ninoNullableAt(at, 4) ? r.view.getInt32(at + 4, true) : null); } -function write$35(w: NinoWriter, v: NinoNullable): void { +function write$38(w: NinoWriter, v: NinoNullable): void { const at = w.raw(8); if (v !== null && v !== undefined) { w.view.setUint8(at, 1); w.view.setInt32(at + 4, v, true); } } -function read$36(r: NinoReader): NinoNullable { +function read$39(r: NinoReader): NinoNullable { const at = r.take(32); return (r.ninoNullableAt(at, 16) ? r.decimalAt(at + 16) : null); } -function write$36(w: NinoWriter, v: NinoNullable): void { +function write$39(w: NinoWriter, v: NinoNullable): void { const at = w.raw(32); if (v !== null && v !== undefined) { w.view.setUint8(at, 1); w.decimalAt(at + 16, v); } } -function read$37(r: NinoReader): NinoNullable[] | null { +function read$40(r: NinoReader): NinoNullable[] | null { const length = r.length(); if (length < 0) return null; const values = new Array>(r.capacity(length)); @@ -3342,7 +3453,7 @@ function read$37(r: NinoReader): NinoNullable[] | null { return values; } -function write$37(w: NinoWriter, values: readonly NinoNullable[] | null): void { +function write$40(w: NinoWriter, values: readonly NinoNullable[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -3356,7 +3467,7 @@ function write$37(w: NinoWriter, values: readonly NinoNullable[] | nu } } -function read$38(r: NinoReader): NinoNullable[] | null { +function read$41(r: NinoReader): NinoNullable[] | null { const length = r.length(); if (length < 0) return null; const values = new Array>(r.capacity(length)); @@ -3364,7 +3475,7 @@ function read$38(r: NinoReader): NinoNullable[] | null { return values; } -function write$38(w: NinoWriter, values: readonly NinoNullable[] | null): void { +function write$41(w: NinoWriter, values: readonly NinoNullable[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -3378,7 +3489,7 @@ function write$38(w: NinoWriter, values: readonly NinoNullable[] | null) } } -function read$39(r: NinoReader): Set> | null { +function read$42(r: NinoReader): Set> | null { const length = r.length(); if (length < 0) return null; const values = new Set>(); @@ -3388,15 +3499,15 @@ function read$39(r: NinoReader): Set> | null { return values; } -function read$40(r: NinoReader): (Set> | null)[] | null { +function read$43(r: NinoReader): (Set> | null)[] | null { const length = r.length(); if (length < 0) return null; const values = new Array> | null>(r.capacity(length)); - for (let i = 0; i < length; i++) values[i] = read$39(r); + for (let i = 0; i < length; i++) values[i] = read$42(r); return values; } -function write$39(w: NinoWriter, values: ReadonlySet> | null): void { +function write$42(w: NinoWriter, values: ReadonlySet> | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -3409,7 +3520,7 @@ function write$39(w: NinoWriter, values: ReadonlySet> | nul } } -function write$40(w: NinoWriter, values: readonly (Set> | null)[] | null): void { +function write$43(w: NinoWriter, values: readonly (Set> | null)[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -3417,6 +3528,6 @@ function write$40(w: NinoWriter, values: readonly (Set> | n w.i32(values.length); for (let i = 0; i < values.length; i++) { const value = values[i]; - write$39(w, value); + write$42(w, value); } } diff --git a/runtimes/typescript/test/generated/Nino.Conformance.TypedArrays.ts b/runtimes/typescript/test/generated/Nino.Conformance.TypedArrays.ts index 2e02468cb..ba78545a5 100644 --- a/runtimes/typescript/test/generated/Nino.Conformance.TypedArrays.ts +++ b/runtimes/typescript/test/generated/Nino.Conformance.TypedArrays.ts @@ -1,7 +1,7 @@ // Generated by nino-gen from Nino.Conformance: its [NinoType]s, read and written as Nino serializes them in .NET. // Do not edit: it is overwritten on every build. -import { NinoReader, NinoSubtypes, NinoWriter, type NinoCodec, type NinoNullable, type NullableSlot } from "../../src/nino.ts"; +import { NinoReader, NinoSubtypes, NinoWriter, type NinoCodec, type NinoGrid as NinoGrid$, type NinoNullable, type NullableSlot } from "../../src/nino.ts"; const types = new NinoSubtypes(); @@ -809,6 +809,99 @@ function writeBody$Circle(w: NinoWriter, v: Circle): void { w.view.setFloat64(at + 8, v.Radius, true); } +/** `Conformance.Collections`. */ +export class Collections { + Ints: Int32Array | null = null; + IntList: Int32Array | null = null; + IntSet: Set | null = null; + Longs: BigInt64Array | null = null; + Doubles: Float64Array | null = null; + Bools: boolean[] | null = null; + Chars: string[] | null = null; + Strings: (string | null)[] | null = null; + StringSet: Set | null = null; + Points: (Point | null)[] | null = null; + PointList: (Point | null)[] | null = null; + IntMap: Map | null = null; + StringMap: Map | null = null; + PointMap: Map | null = null; + ListMap: Map | null = null; + SortedInts: Map | null = null; + SortedStrings: Map | null = null; + Nested: (Int32Array | null)[] | null = null; + Jagged: (Int32Array | null)[] | null = null; + Grid: NinoGrid$ | null = null; + StringGrid: NinoGrid$<(string | null)[]> | null = null; +} + +function readCollections(r: NinoReader, v: Collections = new Collections()): Collections { + const depth = r.depth; + if (depth >= 128) return r.defer(v, readBody$Collections); + r.depth = depth + 1; + readBody$Collections(r, v); + r.exitBody(depth); + return v; +} + +function writeCollections(w: NinoWriter, v: Collections): void { + const depth = w.depth; + if (depth >= 128) { + w.defer(v, writeBody$Collections); + return; + } + w.depth = depth + 1; + writeBody$Collections(w, v); + w.exitBody(depth); +} + +function readBody$Collections(r: NinoReader, v: Collections): void { + v.Ints = read$8(r); + v.IntList = read$8(r); + v.IntSet = (v.IntSet == null ? read$9(r) : readInto$9(r, v.IntSet)); + v.Longs = read$10(r); + v.Doubles = read$11(r); + v.Bools = (v.Bools == null ? read$6(r) : readInto$6(r, v.Bools)); + v.Chars = (v.Chars == null ? read$12(r) : readInto$12(r, v.Chars)); + v.Strings = (v.Strings == null ? read$13(r) : readInto$13(r, v.Strings)); + v.StringSet = (v.StringSet == null ? read$14(r) : readInto$14(r, v.StringSet)); + v.Points = (v.Points == null ? read$15(r) : readInto$15(r, v.Points)); + v.PointList = (v.PointList == null ? read$15(r) : readInto$15(r, v.PointList)); + v.IntMap = (v.IntMap == null ? read$16(r) : readInto$16(r, v.IntMap)); + v.StringMap = (v.StringMap == null ? read$17(r) : readInto$17(r, v.StringMap)); + v.PointMap = (v.PointMap == null ? read$18(r) : readInto$18(r, v.PointMap)); + v.ListMap = (v.ListMap == null ? read$19(r) : readInto$19(r, v.ListMap)); + v.SortedInts = (v.SortedInts == null ? read$20(r) : readInto$20(r, v.SortedInts)); + v.SortedStrings = (v.SortedStrings == null ? read$21(r) : readInto$21(r, v.SortedStrings)); + v.Nested = (v.Nested == null ? read$22(r) : readInto$22(r, v.Nested)); + v.Jagged = (v.Jagged == null ? read$22(r) : readInto$22(r, v.Jagged)); + v.Grid = read$23(r); + v.StringGrid = read$24(r, v.StringGrid); +} + +function writeBody$Collections(w: NinoWriter, v: Collections): void { + write$8(w, v.Ints); + write$8(w, v.IntList); + write$9(w, v.IntSet); + write$10(w, v.Longs); + write$11(w, v.Doubles); + write$6(w, v.Bools); + write$12(w, v.Chars); + write$13(w, v.Strings); + write$14(w, v.StringSet); + write$15(w, v.Points); + write$15(w, v.PointList); + write$16(w, v.IntMap); + write$17(w, v.StringMap); + write$18(w, v.PointMap); + write$19(w, v.ListMap); + write$20(w, v.SortedInts); + write$21(w, v.SortedStrings); + write$22(w, v.Nested); + write$22(w, v.Jagged); + write$23(w, v.Grid); + write$24(w, v.StringGrid); +} + /** `Conformance.Crate`. */ export class Crate { declare Content: T; @@ -938,7 +1031,7 @@ function readBody$Enums(r: NinoReader, v: Enums): void { v.H = r.view.getBigUint64(at + 22, true) as EU64; v.Flags = r.view.getUint8(at + 30) as Permissions; v.Wide = r.view.getBigUint64(at + 31, true) as WideFlags; - v.Array = (v.Array == null ? read$8(r) : readInto$8(r, v.Array)); + v.Array = (v.Array == null ? read$25(r) : readInto$25(r, v.Array)); } function writeBody$Enums(w: NinoWriter, v: Enums): void { @@ -953,7 +1046,7 @@ function writeBody$Enums(w: NinoWriter, v: Enums): void { w.view.setBigUint64(at + 22, v.H, true); w.view.setUint8(at + 30, v.Flags); w.view.setBigUint64(at + 31, v.Wide, true); - write$8(w, v.Array); + write$25(w, v.Array); } /** `Conformance.GenericSlots`. */ @@ -992,7 +1085,7 @@ function readBody$GenericSlots(r: NinoReader, v: GenericSlots): void { v.Crate = (v.Crate == null ? slot$2.read(r) : r.into(slot$2, v.Crate)); v.TextCrate = (v.TextCrate == null ? slot$3.read(r) : r.into(slot$3, v.TextCrate)); v.Holder = (v.Holder == null ? slot$4.read(r) : r.into(slot$4, v.Holder)); - v.Shelves = (v.Shelves == null ? read$9(r) : readInto$9(r, v.Shelves)); + v.Shelves = (v.Shelves == null ? read$26(r) : readInto$26(r, v.Shelves)); } function writeBody$GenericSlots(w: NinoWriter, v: GenericSlots): void { @@ -1001,7 +1094,31 @@ function writeBody$GenericSlots(w: NinoWriter, v: GenericSlots): void { slot$2.write(w, v.Crate); slot$3.write(w, v.TextCrate); slot$4.write(w, v.Holder); - write$9(w, v.Shelves); + write$26(w, v.Shelves); +} + +/** `Conformance.Targets.Grid`. */ +export class Grid { + Values: NinoGrid$ | null = null; +} + +function readGrid(r: NinoReader, v: Grid = new Grid()): Grid { + if (r.depth >= 128) return r.defer(v, readBody$Grid); + readBody$Grid(r, v); + return v; +} + +function writeGrid(w: NinoWriter, v: Grid): void { + if (w.depth >= 128) w.defer(v, writeBody$Grid); + else writeBody$Grid(w, v); +} + +function readBody$Grid(r: NinoReader, v: Grid): void { + v.Values = read$23(r); +} + +function writeBody$Grid(w: NinoWriter, v: Grid): void { + write$23(w, v.Values); } /** `Conformance.Holder`. */ @@ -1096,11 +1213,11 @@ function writeIntArray(w: NinoWriter, v: IntArray): void { } function readBody$IntArray(r: NinoReader, v: IntArray): void { - v.Values = read$10(r); + v.Values = read$8(r); } function writeBody$IntArray(w: NinoWriter, v: IntArray): void { - write$10(w, v.Values); + write$8(w, v.Values); } /** `Conformance.Targets.IntMap`. */ @@ -1120,11 +1237,11 @@ function writeIntMap(w: NinoWriter, v: IntMap): void { } function readBody$IntMap(r: NinoReader, v: IntMap): void { - v.Values = (v.Values == null ? read$11(r) : readInto$11(r, v.Values)); + v.Values = (v.Values == null ? read$16(r) : readInto$16(r, v.Values)); } function writeBody$IntMap(w: NinoWriter, v: IntMap): void { - write$11(w, v.Values); + write$16(w, v.Values); } /** `Conformance.Targets.IntSet`. */ @@ -1144,11 +1261,11 @@ function writeIntSet(w: NinoWriter, v: IntSet): void { } function readBody$IntSet(r: NinoReader, v: IntSet): void { - v.Values = (v.Values == null ? read$12(r) : readInto$12(r, v.Values)); + v.Values = (v.Values == null ? read$9(r) : readInto$9(r, v.Values)); } function writeBody$IntSet(w: NinoWriter, v: IntSet): void { - write$12(w, v.Values); + write$9(w, v.Values); } /** `Conformance.Integers`. */ @@ -1292,13 +1409,13 @@ function writeKeyedHolder(w: NinoWriter, v: KeyedHolder): void { function readBody$KeyedHolder(r: NinoReader, v: KeyedHolder): void { v.Keyed = (r.present() ? (v.Keyed == null ? readKeyedV1(r) : readKeyedV1(r, v.Keyed!)) : null); v.Struct = readKeyedStruct(r, v.Struct); - v.Array = (v.Array == null ? read$13(r) : readInto$13(r, v.Array)); + v.Array = (v.Array == null ? read$27(r) : readInto$27(r, v.Array)); } function writeBody$KeyedHolder(w: NinoWriter, v: KeyedHolder): void { if (v.Keyed === null || v.Keyed === undefined) w.u8(0); else { w.u8(1); writeKeyedV1(w, v.Keyed); } writeKeyedStruct(w, v.Struct); - write$13(w, v.Array); + write$27(w, v.Array); } /** `Conformance.KeyedV1`. */ @@ -1334,7 +1451,7 @@ function readBody$KeyedV1(r: NinoReader, v: KeyedV1): void { r.endMember(member); continue; case -592928685: - v.Items = read$10(r); + v.Items = read$8(r); r.endMember(member); continue; case 72003917: @@ -1359,7 +1476,7 @@ function writeBody$KeyedV1(w: NinoWriter, v: KeyedV1): void { w.endRegion(Name$); w.i32(-592928685); const Items$ = w.beginRegion(); - write$10(w, v.Items); + write$8(w, v.Items); w.endRegion(Items$); w.i32(72003917); const Score$ = w.beginRegion(); @@ -1464,11 +1581,11 @@ function writeLongList(w: NinoWriter, v: LongList): void { } function readBody$LongList(r: NinoReader, v: LongList): void { - v.Values = read$14(r); + v.Values = read$10(r); } function writeBody$LongList(w: NinoWriter, v: LongList): void { - write$14(w, v.Values); + write$10(w, v.Values); } /** `Conformance.Targets.MaybeInt`. */ @@ -1512,11 +1629,35 @@ function writeMaybeIntArray(w: NinoWriter, v: MaybeIntArray): void { } function readBody$MaybeIntArray(r: NinoReader, v: MaybeIntArray): void { - v.Values = (v.Values == null ? read$15(r) : readInto$15(r, v.Values)); + v.Values = (v.Values == null ? read$28(r) : readInto$28(r, v.Values)); } function writeBody$MaybeIntArray(w: NinoWriter, v: MaybeIntArray): void { - write$15(w, v.Values); + write$28(w, v.Values); +} + +/** `Conformance.Targets.MaybeIntGrid`. */ +export class MaybeIntGrid { + Values: NinoGrid$[]> | null = null; +} + +function readMaybeIntGrid(r: NinoReader, v: MaybeIntGrid = new MaybeIntGrid()): MaybeIntGrid { + if (r.depth >= 128) return r.defer(v, readBody$MaybeIntGrid); + readBody$MaybeIntGrid(r, v); + return v; +} + +function writeMaybeIntGrid(w: NinoWriter, v: MaybeIntGrid): void { + if (w.depth >= 128) w.defer(v, writeBody$MaybeIntGrid); + else writeBody$MaybeIntGrid(w, v); +} + +function readBody$MaybeIntGrid(r: NinoReader, v: MaybeIntGrid): void { + v.Values = read$29(r, v.Values); +} + +function writeBody$MaybeIntGrid(w: NinoWriter, v: MaybeIntGrid): void { + write$29(w, v.Values); } /** `Conformance.Targets.MaybeIntSet`. */ @@ -1536,11 +1677,11 @@ function writeMaybeIntSet(w: NinoWriter, v: MaybeIntSet): void { } function readBody$MaybeIntSet(r: NinoReader, v: MaybeIntSet): void { - v.Values = (v.Values == null ? read$16(r) : readInto$16(r, v.Values)); + v.Values = (v.Values == null ? read$30(r) : readInto$30(r, v.Values)); } function writeBody$MaybeIntSet(w: NinoWriter, v: MaybeIntSet): void { - write$16(w, v.Values); + write$30(w, v.Values); } /** `Conformance.Middle`. */ @@ -1671,17 +1812,17 @@ function writeNinoNullableRuns(w: NinoWriter, v: NinoNullableRuns): void { } function readBody$NinoNullableRuns(r: NinoReader, v: NinoNullableRuns): void { - v.LongArray = (v.LongArray == null ? read$17(r) : readInto$17(r, v.LongArray)); - v.LongList = (v.LongList == null ? read$17(r) : readInto$17(r, v.LongList)); - v.IntArray = (v.IntArray == null ? read$18(r) : readInto$18(r, v.IntArray)); - v.ByteList = (v.ByteList == null ? read$19(r) : readInto$19(r, v.ByteList)); + v.LongArray = (v.LongArray == null ? read$31(r) : readInto$31(r, v.LongArray)); + v.LongList = (v.LongList == null ? read$31(r) : readInto$31(r, v.LongList)); + v.IntArray = (v.IntArray == null ? read$32(r) : readInto$32(r, v.IntArray)); + v.ByteList = (v.ByteList == null ? read$33(r) : readInto$33(r, v.ByteList)); } function writeBody$NinoNullableRuns(w: NinoWriter, v: NinoNullableRuns): void { - write$17(w, v.LongArray); - write$17(w, v.LongList); - write$18(w, v.IntArray); - write$19(w, v.ByteList); + write$31(w, v.LongArray); + write$31(w, v.LongList); + write$32(w, v.IntArray); + write$33(w, v.ByteList); } /** `Conformance.NinoNullables`. */ @@ -1721,18 +1862,18 @@ function readBody$NinoNullables(r: NinoReader, v: NinoNullables): void { v.Decimal = (r.ninoNullableAt(at + 16, 16) ? r.decimalAt(at + 32) : null); v.Guid = (r.ninoNullableAt(at + 48, 16) ? r.guidAt(at + 64) : null); v.Padded = (r.ninoNullableAt(at + 80, 16) ? readPadded(r, at + 96) : null); - v.LongArray = (v.LongArray == null ? read$17(r) : readInto$17(r, v.LongArray)); - v.LongList = (v.LongList == null ? read$17(r) : readInto$17(r, v.LongList)); - v.DecimalArray = (v.DecimalArray == null ? read$20(r) : readInto$20(r, v.DecimalArray)); - v.DecimalList = (v.DecimalList == null ? read$20(r) : readInto$20(r, v.DecimalList)); - v.GuidArray = (v.GuidArray == null ? read$21(r) : readInto$21(r, v.GuidArray)); - v.GuidList = (v.GuidList == null ? read$21(r) : readInto$21(r, v.GuidList)); - v.PaddedArray = (v.PaddedArray == null ? read$22(r) : readInto$22(r, v.PaddedArray)); - v.PaddedList = (v.PaddedList == null ? read$22(r) : readInto$22(r, v.PaddedList)); - v.GuidQueue = (v.GuidQueue == null ? read$21(r) : readInto$21(r, v.GuidQueue)); - v.DecimalMap = (v.DecimalMap == null ? read$23(r) : readInto$23(r, v.DecimalMap)); + v.LongArray = (v.LongArray == null ? read$31(r) : readInto$31(r, v.LongArray)); + v.LongList = (v.LongList == null ? read$31(r) : readInto$31(r, v.LongList)); + v.DecimalArray = (v.DecimalArray == null ? read$34(r) : readInto$34(r, v.DecimalArray)); + v.DecimalList = (v.DecimalList == null ? read$34(r) : readInto$34(r, v.DecimalList)); + v.GuidArray = (v.GuidArray == null ? read$35(r) : readInto$35(r, v.GuidArray)); + v.GuidList = (v.GuidList == null ? read$35(r) : readInto$35(r, v.GuidList)); + v.PaddedArray = (v.PaddedArray == null ? read$36(r) : readInto$36(r, v.PaddedArray)); + v.PaddedList = (v.PaddedList == null ? read$36(r) : readInto$36(r, v.PaddedList)); + v.GuidQueue = (v.GuidQueue == null ? read$35(r) : readInto$35(r, v.GuidQueue)); + v.DecimalMap = (v.DecimalMap == null ? read$37(r) : readInto$37(r, v.DecimalMap)); v.Fields = readNinoNullableFields(r, r.take(48)); - v.FieldsArray = (v.FieldsArray == null ? read$24(r) : readInto$24(r, v.FieldsArray)); + v.FieldsArray = (v.FieldsArray == null ? read$38(r) : readInto$38(r, v.FieldsArray)); } function writeBody$NinoNullables(w: NinoWriter, v: NinoNullables): void { @@ -1741,18 +1882,60 @@ function writeBody$NinoNullables(w: NinoWriter, v: NinoNullables): void { if (v.Decimal !== null && v.Decimal !== undefined) { w.view.setUint8(at + 16, 1); w.decimalAt(at + 32, v.Decimal); } if (v.Guid !== null && v.Guid !== undefined) { w.view.setUint8(at + 48, 1); w.guidAt(at + 64, v.Guid); } if (v.Padded !== null && v.Padded !== undefined) { w.view.setUint8(at + 80, 1); writePadded(w, at + 96, v.Padded); } - write$17(w, v.LongArray); - write$17(w, v.LongList); - write$20(w, v.DecimalArray); - write$20(w, v.DecimalList); - write$21(w, v.GuidArray); - write$21(w, v.GuidList); - write$22(w, v.PaddedArray); - write$22(w, v.PaddedList); - write$21(w, v.GuidQueue); - write$23(w, v.DecimalMap); + write$31(w, v.LongArray); + write$31(w, v.LongList); + write$34(w, v.DecimalArray); + write$34(w, v.DecimalList); + write$35(w, v.GuidArray); + write$35(w, v.GuidList); + write$36(w, v.PaddedArray); + write$36(w, v.PaddedList); + write$35(w, v.GuidQueue); + write$37(w, v.DecimalMap); writeNinoNullableFields(w, w.raw(48), v.Fields); - write$24(w, v.FieldsArray); + write$38(w, v.FieldsArray); +} + +/** `Conformance.NullableSequences`. */ +export class NullableSequences { + IntSet: Set> | null = null; + LongSet: Set> | null = null; + Grid: NinoGrid$[]> | null = null; + PaddedGrid: NinoGrid$[]> | null = null; + Nested: (Set> | null)[] | null = null; + Values: Map | null = null; + Pairs: ([number, number | null])[] | null = null; +} + +function readNullableSequences(r: NinoReader, v: NullableSequences = new NullableSequences()): NullableSequences { + if (r.depth >= 128) return r.defer(v, readBody$NullableSequences); + readBody$NullableSequences(r, v); + return v; +} + +function writeNullableSequences(w: NinoWriter, v: NullableSequences): void { + if (w.depth >= 128) w.defer(v, writeBody$NullableSequences); + else writeBody$NullableSequences(w, v); +} + +function readBody$NullableSequences(r: NinoReader, v: NullableSequences): void { + v.IntSet = (v.IntSet == null ? read$30(r) : readInto$30(r, v.IntSet)); + v.LongSet = (v.LongSet == null ? read$39(r) : readInto$39(r, v.LongSet)); + v.Grid = read$29(r, v.Grid); + v.PaddedGrid = read$40(r, v.PaddedGrid); + v.Nested = (v.Nested == null ? read$41(r) : readInto$41(r, v.Nested)); + v.Values = (v.Values == null ? read$42(r) : readInto$42(r, v.Values)); + v.Pairs = (v.Pairs == null ? read$43(r) : readInto$43(r, v.Pairs)); +} + +function writeBody$NullableSequences(w: NinoWriter, v: NullableSequences): void { + write$30(w, v.IntSet); + write$39(w, v.LongSet); + write$29(w, v.Grid); + write$40(w, v.PaddedGrid); + write$41(w, v.Nested); + write$42(w, v.Values); + write$43(w, v.Pairs); } /** `Conformance.NullableTwins`. */ @@ -1775,17 +1958,17 @@ function writeNullableTwins(w: NinoWriter, v: NullableTwins): void { } function readBody$NullableTwins(r: NinoReader, v: NullableTwins): void { - v.LongArray = (v.LongArray == null ? read$25(r) : readInto$25(r, v.LongArray)); - v.LongList = (v.LongList == null ? read$25(r) : readInto$25(r, v.LongList)); - v.IntArray = (v.IntArray == null ? read$15(r) : readInto$15(r, v.IntArray)); - v.ByteList = (v.ByteList == null ? read$26(r) : readInto$26(r, v.ByteList)); + v.LongArray = (v.LongArray == null ? read$44(r) : readInto$44(r, v.LongArray)); + v.LongList = (v.LongList == null ? read$44(r) : readInto$44(r, v.LongList)); + v.IntArray = (v.IntArray == null ? read$28(r) : readInto$28(r, v.IntArray)); + v.ByteList = (v.ByteList == null ? read$45(r) : readInto$45(r, v.ByteList)); } function writeBody$NullableTwins(w: NinoWriter, v: NullableTwins): void { - write$25(w, v.LongArray); - write$25(w, v.LongList); - write$15(w, v.IntArray); - write$26(w, v.ByteList); + write$44(w, v.LongArray); + write$44(w, v.LongList); + write$28(w, v.IntArray); + write$45(w, v.ByteList); } /** `Conformance.Nullables`. */ @@ -1826,10 +2009,10 @@ function readBody$Nullables(r: NinoReader, v: Nullables): void { v.Vec = (r.present() ? readVec2(r, r.take(8)) : null); v.Padded = (r.present() ? readPadded(r, r.take(16)) : null); v.Label = (r.present() ? (v.Label == null ? readLabel(r) : readLabel(r, v.Label!)) : null); - v.IntArray = (v.IntArray == null ? read$15(r) : readInto$15(r, v.IntArray)); - v.LongList = (v.LongList == null ? read$25(r) : readInto$25(r, v.LongList)); - v.PaddedArray = (v.PaddedArray == null ? read$27(r) : readInto$27(r, v.PaddedArray)); - v.Map = (v.Map == null ? read$28(r) : readInto$28(r, v.Map)); + v.IntArray = (v.IntArray == null ? read$28(r) : readInto$28(r, v.IntArray)); + v.LongList = (v.LongList == null ? read$44(r) : readInto$44(r, v.LongList)); + v.PaddedArray = (v.PaddedArray == null ? read$46(r) : readInto$46(r, v.PaddedArray)); + v.Map = (v.Map == null ? read$47(r) : readInto$47(r, v.Map)); } function writeBody$Nullables(w: NinoWriter, v: Nullables): void { @@ -1842,10 +2025,10 @@ function writeBody$Nullables(w: NinoWriter, v: Nullables): void { if (v.Vec === null || v.Vec === undefined) w.u8(0); else { w.u8(1); writeVec2(w, w.reserve(8), v.Vec); } if (v.Padded === null || v.Padded === undefined) w.u8(0); else { w.u8(1); writePadded(w, w.raw(16), v.Padded); } if (v.Label === null || v.Label === undefined) w.u8(0); else { w.u8(1); writeLabel(w, v.Label); } - write$15(w, v.IntArray); - write$25(w, v.LongList); - write$27(w, v.PaddedArray); - write$28(w, v.Map); + write$28(w, v.IntArray); + write$44(w, v.LongList); + write$46(w, v.PaddedArray); + write$47(w, v.Map); } /** `Conformance.Targets.ObjectSlot`. */ @@ -1937,11 +2120,11 @@ function writePaddedArray(w: NinoWriter, v: PaddedArray): void { } function readBody$PaddedArray(r: NinoReader, v: PaddedArray): void { - v.Values = (v.Values == null ? read$29(r) : readInto$29(r, v.Values)); + v.Values = (v.Values == null ? read$48(r) : readInto$48(r, v.Values)); } function writeBody$PaddedArray(w: NinoWriter, v: PaddedArray): void { - write$29(w, v.Values); + write$48(w, v.Values); } /** `Conformance.Plain`. */ @@ -2023,11 +2206,11 @@ function writePointList(w: NinoWriter, v: PointList): void { } function readBody$PointList(r: NinoReader, v: PointList): void { - v.Values = (v.Values == null ? read$30(r) : readInto$30(r, v.Values)); + v.Values = (v.Values == null ? read$15(r) : readInto$15(r, v.Values)); } function writeBody$PointList(w: NinoWriter, v: PointList): void { - write$30(w, v.Values); + write$15(w, v.Values); } /** `Conformance.RawOptionals`. */ @@ -2051,15 +2234,15 @@ function writeRawOptionals(w: NinoWriter, v: RawOptionals): void { function readBody$RawOptionals(r: NinoReader, v: RawOptionals): void { v.One = readRawOptional(r, r.take(56)); - v.Array = (v.Array == null ? read$31(r) : readInto$31(r, v.Array)); - v.List = (v.List == null ? read$31(r) : readInto$31(r, v.List)); + v.Array = (v.Array == null ? read$49(r) : readInto$49(r, v.Array)); + v.List = (v.List == null ? read$49(r) : readInto$49(r, v.List)); v.Maybe = (r.present() ? readRawOptional(r, r.take(56)) : null); } function writeBody$RawOptionals(w: NinoWriter, v: RawOptionals): void { writeRawOptional(w, w.raw(56), v.One); - write$31(w, v.Array); - write$31(w, v.List); + write$49(w, v.Array); + write$49(w, v.List); if (v.Maybe === null || v.Maybe === undefined) w.u8(0); else { w.u8(1); writeRawOptional(w, w.raw(56), v.Maybe); } } @@ -2158,11 +2341,11 @@ function writeSortedMap(w: NinoWriter, v: SortedMap): void { } function readBody$SortedMap(r: NinoReader, v: SortedMap): void { - v.Values = (v.Values == null ? read$11(r) : readInto$11(r, v.Values)); + v.Values = (v.Values == null ? read$16(r) : readInto$16(r, v.Values)); } function writeBody$SortedMap(w: NinoWriter, v: SortedMap): void { - write$11(w, v.Values); + write$16(w, v.Values); } /** `Conformance.Square`. */ @@ -2215,16 +2398,16 @@ function writeStringCollections(w: NinoWriter, v: StringCollections): void { } function readBody$StringCollections(r: NinoReader, v: StringCollections): void { - v.Array = (v.Array == null ? read$32(r) : readInto$32(r, v.Array)); - v.List = (v.List == null ? read$32(r) : readInto$32(r, v.List)); + v.Array = (v.Array == null ? read$13(r) : readInto$13(r, v.Array)); + v.List = (v.List == null ? read$13(r) : readInto$13(r, v.List)); v.Utf8A = r.utf8(); v.Plain = r.string(); v.Utf8B = r.utf8(); } function writeBody$StringCollections(w: NinoWriter, v: StringCollections): void { - write$32(w, v.Array); - write$32(w, v.List); + write$13(w, v.Array); + write$13(w, v.List); w.utf8(v.Utf8A); w.string(v.Plain); w.utf8(v.Utf8B); @@ -2247,11 +2430,11 @@ function writeStringList(w: NinoWriter, v: StringList): void { } function readBody$StringList(r: NinoReader, v: StringList): void { - v.Values = (v.Values == null ? read$32(r) : readInto$32(r, v.Values)); + v.Values = (v.Values == null ? read$13(r) : readInto$13(r, v.Values)); } function writeBody$StringList(w: NinoWriter, v: StringList): void { - write$32(w, v.Values); + write$13(w, v.Values); } /** `Conformance.Targets.StringMap`. */ @@ -2271,11 +2454,11 @@ function writeStringMap(w: NinoWriter, v: StringMap): void { } function readBody$StringMap(r: NinoReader, v: StringMap): void { - v.Values = (v.Values == null ? read$33(r) : readInto$33(r, v.Values)); + v.Values = (v.Values == null ? read$21(r) : readInto$21(r, v.Values)); } function writeBody$StringMap(w: NinoWriter, v: StringMap): void { - write$33(w, v.Values); + write$21(w, v.Values); } /** `Conformance.Targets.StringSet`. */ @@ -2295,11 +2478,11 @@ function writeStringSet(w: NinoWriter, v: StringSet): void { } function readBody$StringSet(r: NinoReader, v: StringSet): void { - v.Values = (v.Values == null ? read$34(r) : readInto$34(r, v.Values)); + v.Values = (v.Values == null ? read$14(r) : readInto$14(r, v.Values)); } function writeBody$StringSet(w: NinoWriter, v: StringSet): void { - write$34(w, v.Values); + write$14(w, v.Values); } /** `Conformance.Strings`. */ @@ -2367,11 +2550,11 @@ function readBody$Structs(r: NinoReader, v: Structs): void { v.Sized = readSized(r, at + 47); v.Nested = readNested(r, at + 63); v.Label = readLabel(r, v.Label); - v.VecArray = (v.VecArray == null ? read$35(r) : readInto$35(r, v.VecArray)); - v.PaddedList = (v.PaddedList == null ? read$29(r) : readInto$29(r, v.PaddedList)); - v.MixedArray = (v.MixedArray == null ? read$36(r) : readInto$36(r, v.MixedArray)); - v.Labels = (v.Labels == null ? read$37(r) : readInto$37(r, v.Labels)); - v.RawTuple = read$38(r); + v.VecArray = (v.VecArray == null ? read$50(r) : readInto$50(r, v.VecArray)); + v.PaddedList = (v.PaddedList == null ? read$48(r) : readInto$48(r, v.PaddedList)); + v.MixedArray = (v.MixedArray == null ? read$51(r) : readInto$51(r, v.MixedArray)); + v.Labels = (v.Labels == null ? read$52(r) : readInto$52(r, v.Labels)); + v.RawTuple = read$53(r); v.Tuple = [r.i32(), r.string()]; v.Pair = [r.string(), readVec2(r, r.take(8))]; } @@ -2385,11 +2568,11 @@ function writeBody$Structs(w: NinoWriter, v: Structs): void { writeSized(w, at + 47, v.Sized); writeNested(w, at + 63, v.Nested); writeLabel(w, v.Label); - write$35(w, v.VecArray); - write$29(w, v.PaddedList); - write$36(w, v.MixedArray); - write$37(w, v.Labels); - write$38(w, v.RawTuple); + write$50(w, v.VecArray); + write$48(w, v.PaddedList); + write$51(w, v.MixedArray); + write$52(w, v.Labels); + write$53(w, v.RawTuple); w.i32(v.Tuple[0]); w.string(v.Tuple[1]); w.string(v.Pair[0]); writeVec2(w, w.reserve(8), v.Pair[1]); } @@ -2655,7 +2838,7 @@ function readBody$TolerantV2(r: NinoReader, v: TolerantV2): void { if (r.pos < end) v.A = r.i32(); if (r.pos < end) v.B = r.string(); if (r.pos < end) v.C = r.i64(); - if (r.pos < end) v.D = read$10(r); + if (r.pos < end) v.D = read$8(r); r.endRegion(end); } @@ -2664,7 +2847,7 @@ function writeBody$TolerantV2(w: NinoWriter, v: TolerantV2): void { w.i32(v.A); w.string(v.B); w.i64(v.C); - write$10(w, v.D); + write$8(w, v.D); w.endRegion(start); } @@ -2745,14 +2928,14 @@ function writeTrackedHolder(w: NinoWriter, v: TrackedHolder): void { function readBody$TrackedHolder(r: NinoReader, v: TrackedHolder): void { v.A = (v.A == null ? TrackedCodec.read(r) : r.into(TrackedCodec, v.A)); v.B = (v.B == null ? TrackedCodec.read(r) : r.into(TrackedCodec, v.B)); - v.All = (v.All == null ? read$39(r) : readInto$39(r, v.All)); + v.All = (v.All == null ? read$54(r) : readInto$54(r, v.All)); v.Any = types.read(r, null); } function writeBody$TrackedHolder(w: NinoWriter, v: TrackedHolder): void { TrackedCodec.write(w, v.A); TrackedCodec.write(w, v.B); - write$39(w, v.All); + write$54(w, v.All); types.write(w, v.Any, null); } @@ -2790,8 +2973,8 @@ function readBody$TrackedMix(r: NinoReader, v: TrackedMix): void { v.Any = types.read(r, null); v.Node = r.tracked(TrackedNode, readTrackedNode); v.Base = (v.Base == null ? TrackedCodec.read(r) : r.into(TrackedCodec, v.Base)); - v.Nodes = (v.Nodes == null ? read$40(r) : readInto$40(r, v.Nodes)); - v.ById = (v.ById == null ? read$41(r) : readInto$41(r, v.ById)); + v.Nodes = (v.Nodes == null ? read$55(r) : readInto$55(r, v.Nodes)); + v.ById = (v.ById == null ? read$56(r) : readInto$56(r, v.ById)); v.Tolerant = r.tracked(TrackedTolerant, readTrackedTolerant); } @@ -2799,8 +2982,8 @@ function writeBody$TrackedMix(w: NinoWriter, v: TrackedMix): void { types.write(w, v.Any, null); if (w.ref(v.Node)) writeTrackedNode(w, v.Node); TrackedCodec.write(w, v.Base); - write$40(w, v.Nodes); - write$41(w, v.ById); + write$55(w, v.Nodes); + write$56(w, v.ById); if (w.ref(v.Tolerant)) writeTrackedTolerant(w, v.Tolerant); } @@ -2910,12 +3093,12 @@ function writeTreeNode(w: NinoWriter, v: TreeNode): void { function readBody$TreeNode(r: NinoReader, v: TreeNode): void { v.Value = r.i32(); - v.Children = (v.Children == null ? read$42(r) : readInto$42(r, v.Children)); + v.Children = (v.Children == null ? read$57(r) : readInto$57(r, v.Children)); } function writeBody$TreeNode(w: NinoWriter, v: TreeNode): void { w.i32(v.Value); - write$42(w, v.Children); + write$57(w, v.Children); } /** `Conformance.Unions`. */ @@ -2959,7 +3142,7 @@ function readBody$Unions(r: NinoReader, v: Unions): void { v.Numbers = readChoice(r); v.Maybe = readChoice(r); v.Empty = readChoice(r); - v.Many = (v.Many == null ? read$43(r) : readInto$43(r, v.Many)); + v.Many = (v.Many == null ? read$58(r) : readInto$58(r, v.Many)); v.Tree = readUnionTree(r); } @@ -2971,7 +3154,7 @@ function writeBody$Unions(w: NinoWriter, v: Unions): void { writeChoice(w, v.Numbers); writeChoice(w, v.Maybe); writeChoice(w, v.Empty); - write$43(w, v.Many); + write$58(w, v.Many); writeUnionTree(w, v.Tree); } @@ -3119,25 +3302,25 @@ function writeZoo(w: NinoWriter, v: Zoo): void { function readBody$Zoo(r: NinoReader, v: Zoo): void { v.Star = (v.Star == null ? AnimalCodec.read(r) : r.into(AnimalCodec, v.Star)); v.Dog = (v.Dog == null ? DogCodec.read(r) : r.into(DogCodec, v.Dog)); - v.Animals = (v.Animals == null ? read$44(r) : readInto$44(r, v.Animals)); - v.Cages = (v.Cages == null ? read$44(r) : readInto$44(r, v.Cages)); + v.Animals = (v.Animals == null ? read$59(r) : readInto$59(r, v.Animals)); + v.Cages = (v.Cages == null ? read$59(r) : readInto$59(r, v.Cages)); v.Shape = (v.Shape == null ? IShapeCodec.read(r) : r.into(IShapeCodec, v.Shape)); - v.Shapes = (v.Shapes == null ? read$45(r) : readInto$45(r, v.Shapes)); + v.Shapes = (v.Shapes == null ? read$60(r) : readInto$60(r, v.Shapes)); v.Plain = (v.Plain == null ? PlainCodec.read(r) : r.into(PlainCodec, v.Plain)); v.Anything = types.read(r, null); - v.ByName = (v.ByName == null ? read$46(r) : readInto$46(r, v.ByName)); + v.ByName = (v.ByName == null ? read$61(r) : readInto$61(r, v.ByName)); } function writeBody$Zoo(w: NinoWriter, v: Zoo): void { AnimalCodec.write(w, v.Star); DogCodec.write(w, v.Dog); - write$44(w, v.Animals); - write$44(w, v.Cages); + write$59(w, v.Animals); + write$59(w, v.Cages); IShapeCodec.write(w, v.Shape); - write$45(w, v.Shapes); + write$60(w, v.Shapes); PlainCodec.write(w, v.Plain); types.write(w, v.Anything, null); - write$46(w, v.ByName); + write$61(w, v.ByName); } /** `Conformance.Bag`. */ @@ -3158,12 +3341,12 @@ function writeBag(w: NinoWriter, v: Bag): void { } function readBody$Bag(r: NinoReader, v: Bag): void { - v.$elements = r.elements(read$10(r)); + v.$elements = r.elements(read$8(r)); v.Tag = r.string(); } function writeBody$Bag(w: NinoWriter, v: Bag): void { - write$10(w, v.$elements); + write$8(w, v.$elements); w.string(v.Tag); } @@ -3321,7 +3504,7 @@ function readChoice(r: NinoReader): Choice | null { break; } case -217079013: { - const value = read$10(r); + const value = read$8(r); if (value === null) throw r.invalidCase(id); v = value; break; @@ -3365,7 +3548,7 @@ function writeChoice(w: NinoWriter, v: Choice | null): void { } else if (v instanceof Int32Array) { w.i32(-217079013); - write$10(w, v); + write$8(w, v); } else if (typeof v === "bigint") { const at = w.reserve(13); @@ -3462,7 +3645,7 @@ function writeKeyedBag(w: NinoWriter, v: KeyedBag): void { function readBody$KeyedBag(r: NinoReader, v: KeyedBag): void { const end = r.beginRegion(); - v.$elements = r.elements((v.$elements == null ? read$33(r) : readInto$33(r, v.$elements))); + v.$elements = r.elements((v.$elements == null ? read$21(r) : readInto$21(r, v.$elements))); while (r.pos < end) { const key = r.i32(), member = r.beginRegion(); switch (key) { @@ -3478,7 +3661,7 @@ function readBody$KeyedBag(r: NinoReader, v: KeyedBag): void { function writeBody$KeyedBag(w: NinoWriter, v: KeyedBag): void { const start = w.beginRegion(); - write$33(w, v.$elements); + write$21(w, v.$elements); w.i32(-1909720929); const Version$ = w.beginRegion(); w.i32(v.Version); @@ -3618,12 +3801,12 @@ function writeListShelf(w: NinoWriter, v: ListShelf, c: ListShelf$Codecs(r: NinoReader, v: ListShelf, c: ListShelf$Codecs): void { v.Item = (v.Item == null ? c.p0.read(r) : r.into(c.p0, v.Item)); - v.More = (v.More == null ? read$47(r, c) : readInto$47(r, c, v.More)); + v.More = (v.More == null ? read$62(r, c) : readInto$62(r, c, v.More)); } function writeBody$ListShelf(w: NinoWriter, v: ListShelf, c: ListShelf$Codecs): void { c.p0.write(w, v.Item); - write$47(w, v.More, c); + write$62(w, v.More, c); } /** `Conformance.PointSet`. */ @@ -3653,12 +3836,12 @@ function writePointSet(w: NinoWriter, v: PointSet): void { } function readBody$PointSet(r: NinoReader, v: PointSet): void { - v.$elements = r.elements((v.$elements == null ? read$12(r) : readInto$12(r, v.$elements))); + v.$elements = r.elements((v.$elements == null ? read$9(r) : readInto$9(r, v.$elements))); v.Origin = (r.present() ? (v.Origin == null ? readPoint(r) : readPoint(r, v.Origin!)) : null); } function writeBody$PointSet(w: NinoWriter, v: PointSet): void { - write$12(w, v.$elements); + write$9(w, v.$elements); if (v.Origin === null || v.Origin === undefined) w.u8(0); else { w.u8(1); writePoint(w, v.Origin); } } @@ -3714,14 +3897,14 @@ function writeTolerantBag(w: NinoWriter, v: TolerantBag): void { } function readBody$TolerantBag(r: NinoReader, v: TolerantBag): void { - v.$elements = r.elements((v.$elements == null ? read$32(r) : readInto$32(r, v.$elements))); + v.$elements = r.elements((v.$elements == null ? read$13(r) : readInto$13(r, v.$elements))); const end = r.beginRegion(); if (r.pos < end) v.Tag = r.string(); r.endRegion(end); } function writeBody$TolerantBag(w: NinoWriter, v: TolerantBag): void { - write$32(w, v.$elements); + write$13(w, v.$elements); const start = w.beginRegion(); w.string(v.Tag); w.endRegion(start); @@ -3827,7 +4010,7 @@ function readUnionTree(r: NinoReader): UnionTree | null { let v: UnionTree; switch (id) { case 1950069485: { - const value = read$48(r); + const value = read$63(r); if (value === null) throw r.invalidCase(id); v = value; break; @@ -3851,7 +4034,7 @@ function writeUnionTree(w: NinoWriter, v: UnionTree | null): void { w.enterStruct(); if (Array.isArray(v)) { w.i32(1950069485); - write$48(w, v); + write$63(w, v); } else if (typeof v === "bigint") { const at = w.reserve(12); @@ -3912,11 +4095,13 @@ types.add(-1384569984, Cat, readCat, writeCat); types.add(-2126005709, Chain, readChain, writeChain); types.add(-585924235, ChoiceObject, (r) => new ChoiceObject(readChoice(r)), (w, v) => writeChoice(w, v.value)); types.add(-794369036, Circle, readCircle, writeCircle); +types.add(-20025893, Collections, readCollections, writeCollections); types.add(1772922506, Dog, readDog, writeDog); types.add(1207113682, DogSlot, readDogSlot, writeDogSlot); types.add(211121179, Empty, readEmpty, writeEmpty); types.add(1206893526, Enums, readEnums, writeEnums); types.add(-2124835064, GenericSlots, readGenericSlots, writeGenericSlots); +types.add(-118291654, Grid, readGrid, writeGrid); types.add(-1898071576, Inner, readInner, writeInner); types.add(1766682360, IntArray, readIntArray, writeIntArray); types.add(-752026235, IntMap, readIntMap, writeIntMap); @@ -3933,6 +4118,7 @@ types.add(877594808, Label, readLabel, writeLabel); types.add(-825281326, LongList, readLongList, writeLongList); types.add(1049426083, MaybeInt, readMaybeInt, writeMaybeInt); types.add(1131047346, MaybeIntArray, readMaybeIntArray, writeMaybeIntArray); +types.add(-898559237, MaybeIntGrid, readMaybeIntGrid, writeMaybeIntGrid); types.add(-1946182255, MaybeIntSet, readMaybeIntSet, writeMaybeIntSet); types.add(-765756749, Middle, readMiddle, writeMiddle); types.add(235403483, Mixed, (r) => readMixed(r, r.take(12)), (w, v) => writeMixed(w, w.raw(12), v)); @@ -3941,6 +4127,7 @@ types.add(103626619, Nested, (r) => readNested(r, r.take(32)), (w, v) => writeNe types.add(-18485656, NinoNullableFields, (r) => readNinoNullableFields(r, r.take(48)), (w, v) => writeNinoNullableFields(w, w.raw(48), v)); types.add(-1745896621, NinoNullableRuns, readNinoNullableRuns, writeNinoNullableRuns); types.add(1726570842, NinoNullables, readNinoNullables, writeNinoNullables); +types.add(-619270237, NullableSequences, readNullableSequences, writeNullableSequences); types.add(1660874880, NullableTwins, readNullableTwins, writeNullableTwins); types.add(958404412, Nullables, readNullables, writeNullables); types.add(2048313563, ObjectSlot, readObjectSlot, writeObjectSlot); @@ -4306,6 +4493,13 @@ export const CircleCodec: NinoCodec = { throw types.unreadable(id); }, }; +export const CollectionsCodec: NinoCodec = { + read: (r) => (r.present() ? readCollections(r) : null), + write: (w, v) => { + if (v === null || v === undefined) w.u8(0); else { w.u8(1); writeCollections(w, v); } + }, + readInto: (r, v) => (r.present() ? (v == null ? readCollections(r) : readCollections(r, v!)) : null), +}; export const DogCodec: NinoCodec = { read: (r) => { const id = r.i32(); @@ -4377,6 +4571,13 @@ export const GenericSlotsCodec: NinoCodec = { }, readInto: (r, v) => (r.present() ? (v == null ? readGenericSlots(r) : readGenericSlots(r, v!)) : null), }; +export const GridCodec: NinoCodec = { + read: (r) => (r.present() ? readGrid(r) : null), + write: (w, v) => { + if (v === null || v === undefined) w.u8(0); else { w.u8(1); writeGrid(w, v); } + }, + readInto: (r, v) => (r.present() ? (v == null ? readGrid(r) : readGrid(r, v!)) : null), +}; export const IShapeCodec: NinoCodec = { read: (r) => { const id = r.i32(); @@ -4563,6 +4764,13 @@ export const MaybeIntArrayCodec: NinoCodec = { }, readInto: (r, v) => (r.present() ? (v == null ? readMaybeIntArray(r) : readMaybeIntArray(r, v!)) : null), }; +export const MaybeIntGridCodec: NinoCodec = { + read: (r) => (r.present() ? readMaybeIntGrid(r) : null), + write: (w, v) => { + if (v === null || v === undefined) w.u8(0); else { w.u8(1); writeMaybeIntGrid(w, v); } + }, + readInto: (r, v) => (r.present() ? (v == null ? readMaybeIntGrid(r) : readMaybeIntGrid(r, v!)) : null), +}; export const MaybeIntSetCodec: NinoCodec = { read: (r) => (r.present() ? readMaybeIntSet(r) : null), write: (w, v) => { @@ -4610,6 +4818,13 @@ export const NinoNullablesCodec: NinoCodec = { }, readInto: (r, v) => (r.present() ? (v == null ? readNinoNullables(r) : readNinoNullables(r, v!)) : null), }; +export const NullableSequencesCodec: NinoCodec = { + read: (r) => (r.present() ? readNullableSequences(r) : null), + write: (w, v) => { + if (v === null || v === undefined) w.u8(0); else { w.u8(1); writeNullableSequences(w, v); } + }, + readInto: (r, v) => (r.present() ? (v == null ? readNullableSequences(r) : readNullableSequences(r, v!)) : null), +}; export const NullableTwinsCodec: NinoCodec = { read: (r) => (r.present() ? readNullableTwins(r) : null), write: (w, v) => { @@ -5163,7 +5378,7 @@ function Nest$codecs(p0: NinoCodec, type: new () => Nest): Nest$Codecs< }, }; let d0: NinoCodec | null> | undefined; - Object.defineProperty(c, "d0", { get: () => (d0 ??= NestCodec({ read: (r) => read$49(r, c), write: (w, v) => { write$49(w, v, c); } })) }); + Object.defineProperty(c, "d0", { get: () => (d0 ??= NestCodec({ read: (r) => read$64(r, c), write: (w, v) => { write$64(w, v, c); } })) }); return c; } @@ -5360,15 +5575,15 @@ const slot$4: NinoCodec | null> = { }; const codec$0 = NestCodec({ read: (r) => r.i32(), write: (w, v) => { w.i32(v); } }, NestInt32); -const codec$1 = WrapCodec[] | null>({ read: (r) => read$15(r), write: (w, v) => { write$15(w, v); } }, WrapListNullableInt32); -const codec$2 = WrapCodec> | null>({ read: (r) => read$16(r), write: (w, v) => { write$16(w, v); } }, WrapHashSetNullableInt32); -const codec$3 = WrapCodec[] | null>({ read: (r) => read$50(r), write: (w, v) => { write$50(w, v); } }, WrapListNullableVec2); -const codec$4 = WrapCodec | null>({ read: (r) => read$51(r), write: (w, v) => { write$51(w, v); } }, WrapDictionaryInt32NullableDouble); -const codec$5 = WrapCodec<([number, string | null])[] | null>({ read: (r) => read$52(r), write: (w, v) => { write$52(w, v); } }, WrapListKeyValuePairInt32String); -const codec$6 = WrapCodec<([string | null, number | null])[] | null>({ read: (r) => read$53(r), write: (w, v) => { write$53(w, v); } }, WrapKeyValuePair); +const codec$1 = WrapCodec[] | null>({ read: (r) => read$28(r), write: (w, v) => { write$28(w, v); } }, WrapListNullableInt32); +const codec$2 = WrapCodec> | null>({ read: (r) => read$30(r), write: (w, v) => { write$30(w, v); } }, WrapHashSetNullableInt32); +const codec$3 = WrapCodec[] | null>({ read: (r) => read$65(r), write: (w, v) => { write$65(w, v); } }, WrapListNullableVec2); +const codec$4 = WrapCodec | null>({ read: (r) => read$66(r), write: (w, v) => { write$66(w, v); } }, WrapDictionaryInt32NullableDouble); +const codec$5 = WrapCodec<([number, string | null])[] | null>({ read: (r) => read$67(r), write: (w, v) => { write$67(w, v); } }, WrapListKeyValuePairInt32String); +const codec$6 = WrapCodec<([string | null, number | null])[] | null>({ read: (r) => read$68(r), write: (w, v) => { write$68(w, v); } }, WrapKeyValuePair); const closed$0 = Box$codecs({ read: (r) => readVec2(r, r.take(8)), write: (w, v) => { writeVec2(w, w.reserve(8), v); } }, BoxVec2); -const closed$1 = Box$codecs<(Point | null)[] | null>({ read: (r) => read$30(r), write: (w, v) => { write$30(w, v); } }, BoxListPoint); +const closed$1 = Box$codecs<(Point | null)[] | null>({ read: (r) => read$15(r), write: (w, v) => { write$15(w, v); } }, BoxListPoint); const closed$2 = Box$codecs({ read: (r) => r.i32(), write: (w, v) => { w.i32(v); } }, BoxInt32); const closed$3 = Box$codecs({ read: (r) => r.string(), write: (w, v) => { w.string(v); } }, BoxString); const closed$4 = Crate$codecs({ read: (r) => r.i32(), write: (w, v) => { w.i32(v); } }, CrateInt32); @@ -5378,18 +5593,18 @@ const closed$7 = LabeledCrate$codecs({ read: (r) => r.i32(), write: (w, const closed$8 = LabeledCrate$codecs({ read: (r) => r.string(), write: (w, v) => { w.string(v); } }, LabeledCrateString); const closed$9 = ListShelf$codecs({ read: (r) => r.i32(), write: (w, v) => { w.i32(v); } }, ListShelfInt32); const closed$10 = ListShelf$codecs({ read: (r) => r.string(), write: (w, v) => { w.string(v); } }, ListShelfString); -const closed$11 = Nest$codecs<(((Int32Array | null)[] | null)[] | null)[] | null>({ read: (r) => read$56(r), write: (w, v) => { write$56(w, v); } }, NestListListListListInt32); -const closed$12 = Nest$codecs<((Int32Array | null)[] | null)[] | null>({ read: (r) => read$55(r), write: (w, v) => { write$55(w, v); } }, NestListListListInt32); -const closed$13 = Nest$codecs<(Int32Array | null)[] | null>({ read: (r) => read$54(r), write: (w, v) => { write$54(w, v); } }, NestListListInt32); -const closed$14 = Nest$codecs({ read: (r) => read$10(r), write: (w, v) => { write$10(w, v); } }, NestListInt32); +const closed$11 = Nest$codecs<(((Int32Array | null)[] | null)[] | null)[] | null>({ read: (r) => read$70(r), write: (w, v) => { write$70(w, v); } }, NestListListListListInt32); +const closed$12 = Nest$codecs<((Int32Array | null)[] | null)[] | null>({ read: (r) => read$69(r), write: (w, v) => { write$69(w, v); } }, NestListListListInt32); +const closed$13 = Nest$codecs<(Int32Array | null)[] | null>({ read: (r) => read$22(r), write: (w, v) => { write$22(w, v); } }, NestListListInt32); +const closed$14 = Nest$codecs({ read: (r) => read$8(r), write: (w, v) => { write$8(w, v); } }, NestListInt32); const closed$15 = Nest$codecs({ read: (r) => r.i32(), write: (w, v) => { w.i32(v); } }, NestInt32); -const closed$16 = Wrap$codecs | null>({ read: (r) => read$51(r), write: (w, v) => { write$51(w, v); } }, WrapDictionaryInt32NullableDouble); -const closed$17 = Wrap$codecs> | null>({ read: (r) => read$16(r), write: (w, v) => { write$16(w, v); } }, WrapHashSetNullableInt32); -const closed$18 = Wrap$codecs<([string | null, number | null])[] | null>({ read: (r) => read$53(r), write: (w, v) => { write$53(w, v); } }, WrapKeyValuePair); -const closed$19 = Wrap$codecs<([number, string | null])[] | null>({ read: (r) => read$52(r), write: (w, v) => { write$52(w, v); } }, WrapListKeyValuePairInt32String); -const closed$20 = Wrap$codecs[] | null>({ read: (r) => read$50(r), write: (w, v) => { write$50(w, v); } }, WrapListNullableVec2); -const closed$21 = Wrap$codecs[] | null>({ read: (r) => read$15(r), write: (w, v) => { write$15(w, v); } }, WrapListNullableInt32); -const closed$22 = Wrap$codecs[] | null>({ read: (r) => read$15(r), write: (w, v) => { write$15(w, v); } }, WrapNullable); +const closed$16 = Wrap$codecs | null>({ read: (r) => read$66(r), write: (w, v) => { write$66(w, v); } }, WrapDictionaryInt32NullableDouble); +const closed$17 = Wrap$codecs> | null>({ read: (r) => read$30(r), write: (w, v) => { write$30(w, v); } }, WrapHashSetNullableInt32); +const closed$18 = Wrap$codecs<([string | null, number | null])[] | null>({ read: (r) => read$68(r), write: (w, v) => { write$68(w, v); } }, WrapKeyValuePair); +const closed$19 = Wrap$codecs<([number, string | null])[] | null>({ read: (r) => read$67(r), write: (w, v) => { write$67(w, v); } }, WrapListKeyValuePairInt32String); +const closed$20 = Wrap$codecs[] | null>({ read: (r) => read$65(r), write: (w, v) => { write$65(w, v); } }, WrapListNullableVec2); +const closed$21 = Wrap$codecs[] | null>({ read: (r) => read$28(r), write: (w, v) => { write$28(w, v); } }, WrapListNullableInt32); +const closed$22 = Wrap$codecs[] | null>({ read: (r) => read$28(r), write: (w, v) => { write$28(w, v); } }, WrapNullable); types.add(-1580784064, BoxVec2, (r) => readBox(r, closed$0), (w, v) => writeBox(w, v, closed$0)); types.add(-1116656767, BoxListPoint, (r) => readBox(r, closed$1), (w, v) => writeBox(w, v, closed$1)); types.add(-794599344, BoxInt32, (r) => readBox(r, closed$2), (w, v) => writeBox(w, v, closed$2)); @@ -5436,11 +5651,13 @@ export function ninoCodecOf(name: string): NinoCodec | undefined { case "Conformance.Chain": return ChainCodec; case "Conformance.Choice": return ChoiceCodec; case "Conformance.Circle": return CircleCodec; + case "Conformance.Collections": return CollectionsCodec; case "Conformance.Dog": return DogCodec; case "Conformance.Targets.DogSlot": return DogSlotCodec; case "Conformance.Empty": return EmptyCodec; case "Conformance.Enums": return EnumsCodec; case "Conformance.GenericSlots": return GenericSlotsCodec; + case "Conformance.Targets.Grid": return GridCodec; case "Conformance.IShape": return IShapeCodec; case "Conformance.Inner": return InnerCodec; case "Conformance.Targets.IntArray": return IntArrayCodec; @@ -5459,6 +5676,7 @@ export function ninoCodecOf(name: string): NinoCodec | undefined { case "Conformance.Targets.LongList": return LongListCodec; case "Conformance.Targets.MaybeInt": return MaybeIntCodec; case "Conformance.Targets.MaybeIntArray": return MaybeIntArrayCodec; + case "Conformance.Targets.MaybeIntGrid": return MaybeIntGridCodec; case "Conformance.Targets.MaybeIntSet": return MaybeIntSetCodec; case "Conformance.Middle": return MiddleCodec; case "Conformance.Mixed": return MixedCodec; @@ -5467,6 +5685,7 @@ export function ninoCodecOf(name: string): NinoCodec | undefined { case "Conformance.NinoNullableFields": return NinoNullableFieldsCodec; case "Conformance.NinoNullableRuns": return NinoNullableRunsCodec; case "Conformance.NinoNullables": return NinoNullablesCodec; + case "Conformance.NullableSequences": return NullableSequencesCodec; case "Conformance.NullableTwins": return NullableTwinsCodec; case "Conformance.Nullables": return NullablesCodec; case "Conformance.Targets.ObjectSlot": return ObjectSlotCodec; @@ -5762,212 +5981,363 @@ function write$7(w: NinoWriter, values: Int8Array | null): void { } } -function read$8(r: NinoReader): E32[] | null { +function read$8(r: NinoReader): Int32Array | null { const length = r.length(); if (length < 0) return null; - const values = new Array(r.capacity(length)); - for (let i = 0, at = r.take(length * 4); i < length; i++, at += 4) values[i] = r.view.getInt32(at, true) as E32; + if (length > 16) return r.numbers(Int32Array, length); + const values = new Int32Array(length); + for (let i = 0, at = r.take(length * 4); i < length; i++, at += 4) values[i] = r.view.getInt32(at, true); return values; } -function readInto$8(r: NinoReader, cur: E32[]): E32[] | null { +function read$9(r: NinoReader): Set | null { const length = r.length(); if (length < 0) return null; - const values = cur; - for (let i = 0, at = r.take(length * 4); i < length; i++, at += 4) values[i] = r.view.getInt32(at, true) as E32; - if (values.length !== length) values.length = length; + const values = new Set(); + const guard = r.keyGuard(length); + for (let i = 0, at = r.take(length * 4); i < length; i++, at += 4) values.add(guard === null ? r.view.getInt32(at, true) : guard.int(r.view.getInt32(at, true))); + if (values.size !== length) throw r.duplicateKey(); return values; } -function write$8(w: NinoWriter, values: readonly E32[] | null): void { - if (values === null || values === undefined) { - w.i32(-1); - return; - } - w.i32(values.length); - let at = w.reserve(values.length * 4); - for (let i = 0; i < values.length; i++) { - const value = values[i]; - w.view.setInt32(at, value, true); - at += 4; - } -} - -function read$9(r: NinoReader): (Shelf | null)[] | null { +function readInto$9(r: NinoReader, cur: Set): Set | null { const length = r.length(); if (length < 0) return null; - const values = new Array | null>(r.capacity(length)); - for (let i = 0; i < length; i++) values[i] = slot$0.read(r); + const values = cur; + values.clear(); + const guard = r.keyGuard(length); + for (let i = 0, at = r.take(length * 4); i < length; i++, at += 4) values.add(guard === null ? r.view.getInt32(at, true) : guard.int(r.view.getInt32(at, true))); + if (values.size !== length) throw r.duplicateKey(); return values; } -function readInto$9(r: NinoReader, cur: (Shelf | null)[]): (Shelf | null)[] | null { +function read$10(r: NinoReader): BigInt64Array | null { const length = r.length(); if (length < 0) return null; - const values = cur; - for (let i = 0; i < length; i++) values[i] = (values[i] == null ? slot$0.read(r) : r.into(slot$0, values[i])); - if (values.length !== length) values.length = length; + if (length > 8) return r.numbers(BigInt64Array, length); + const values = new BigInt64Array(length); + for (let i = 0, at = r.take(length * 8); i < length; i++, at += 8) values[i] = r.view.getBigInt64(at, true); return values; } -function write$9(w: NinoWriter, values: readonly (Shelf | null)[] | null): void { - if (values === null || values === undefined) { - w.i32(-1); - return; - } - w.i32(values.length); - for (let i = 0; i < values.length; i++) { - const value = values[i]; - slot$0.write(w, value); - } -} - -function read$10(r: NinoReader): Int32Array | null { +function read$11(r: NinoReader): Float64Array | null { const length = r.length(); if (length < 0) return null; - if (length > 16) return r.numbers(Int32Array, length); - const values = new Int32Array(length); - for (let i = 0, at = r.take(length * 4); i < length; i++, at += 4) values[i] = r.view.getInt32(at, true); + if (length > 8) return r.numbers(Float64Array, length); + const values = new Float64Array(length); + for (let i = 0, at = r.take(length * 8); i < length; i++, at += 8) values[i] = r.view.getFloat64(at, true); return values; } -function write$10(w: NinoWriter, values: Int32Array | null): void { - if (values === null || values === undefined) { - w.i32(-1); - return; - } - if (values.length > 16) { - w.numbers(values); - return; - } - w.i32(values.length); - let at = w.reserve(values.length * 4); - for (let i = 0; i < values.length; i++) { - const value = values[i]; - w.view.setInt32(at, value, true); - at += 4; - } +function read$12(r: NinoReader): string[] | null { + const length = r.length(); + if (length < 0) return null; + const values = new Array(r.capacity(length)); + for (let i = 0, at = r.take(length * 2); i < length; i++, at += 2) values[i] = String.fromCharCode(r.view.getUint16(at, true)); + return values; } -function read$11(r: NinoReader): Map | null { +function readInto$12(r: NinoReader, cur: string[]): string[] | null { const length = r.length(); if (length < 0) return null; - const map = new Map(); - const guard = r.keyGuard(length); - for (let i = 0, at = r.take(length * 8); i < length; i++, at += 8) map.set(guard === null ? r.view.getInt32(at, true) : guard.int(r.view.getInt32(at, true)), r.view.getInt32(at + 4, true)); - if (map.size !== length) throw r.duplicateKey(); - return map; + const values = cur; + for (let i = 0, at = r.take(length * 2); i < length; i++, at += 2) values[i] = String.fromCharCode(r.view.getUint16(at, true)); + if (values.length !== length) values.length = length; + return values; } -function readInto$11(r: NinoReader, cur: Map): Map | null { +function read$13(r: NinoReader): (string | null)[] | null { const length = r.length(); if (length < 0) return null; - const map = cur; - map.clear(); - const guard = r.keyGuard(length); - for (let i = 0, at = r.take(length * 8); i < length; i++, at += 8) map.set(guard === null ? r.view.getInt32(at, true) : guard.int(r.view.getInt32(at, true)), r.view.getInt32(at + 4, true)); - if (map.size !== length) throw r.duplicateKey(); - return map; + const values = new Array(r.capacity(length)); + for (let i = 0; i < length; i++) values[i] = r.string(); + return values; } -function write$11(w: NinoWriter, map: ReadonlyMap | null): void { - if (map === null || map === undefined) { - w.i32(-1); - return; - } - w.i32(map.size); - let at = w.reserve(map.size * 8); - for (let keys = map.keys(), values = map.values(), i = map.size; i > 0; i--) { - const key = keys.next().value as number, value = values.next().value as number; - w.view.setInt32(at, key, true); - w.view.setInt32(at + 4, value, true); - at += 8; - } +function readInto$13(r: NinoReader, cur: (string | null)[]): (string | null)[] | null { + const length = r.length(); + if (length < 0) return null; + const values = cur; + for (let i = 0; i < length; i++) values[i] = r.string(); + if (values.length !== length) values.length = length; + return values; } -function read$12(r: NinoReader): Set | null { +function read$14(r: NinoReader): Set | null { const length = r.length(); if (length < 0) return null; - const values = new Set(); + const values = new Set(); const guard = r.keyGuard(length); - for (let i = 0, at = r.take(length * 4); i < length; i++, at += 4) values.add(guard === null ? r.view.getInt32(at, true) : guard.int(r.view.getInt32(at, true))); + for (let i = 0; i < length; i++) values.add(guard === null ? r.string() : guard.string(r.string())); if (values.size !== length) throw r.duplicateKey(); return values; } -function readInto$12(r: NinoReader, cur: Set): Set | null { +function readInto$14(r: NinoReader, cur: Set): Set | null { const length = r.length(); if (length < 0) return null; const values = cur; values.clear(); const guard = r.keyGuard(length); - for (let i = 0, at = r.take(length * 4); i < length; i++, at += 4) values.add(guard === null ? r.view.getInt32(at, true) : guard.int(r.view.getInt32(at, true))); + for (let i = 0; i < length; i++) values.add(guard === null ? r.string() : guard.string(r.string())); if (values.size !== length) throw r.duplicateKey(); return values; } -function write$12(w: NinoWriter, values: ReadonlySet | null): void { - if (values === null || values === undefined) { - w.i32(-1); - return; - } - w.i32(values.size); - let at = w.reserve(values.size * 4); - for (const value of values) { - w.view.setInt32(at, value, true); - at += 4; - } -} - -function read$13(r: NinoReader): (KeyedV1 | null)[] | null { +function read$15(r: NinoReader): (Point | null)[] | null { const length = r.length(); if (length < 0) return null; - const values = new Array(r.capacity(length)); - for (let i = 0; i < length; i++) values[i] = (r.present() ? readKeyedV1(r) : null); + const values = new Array(r.capacity(length)); + for (let i = 0; i < length; i++) values[i] = (r.present() ? readPoint(r) : null); return values; } -function readInto$13(r: NinoReader, cur: (KeyedV1 | null)[]): (KeyedV1 | null)[] | null { +function readInto$15(r: NinoReader, cur: (Point | null)[]): (Point | null)[] | null { const length = r.length(); if (length < 0) return null; const values = cur; - for (let i = 0; i < length; i++) values[i] = (r.present() ? (values[i] == null ? readKeyedV1(r) : readKeyedV1(r, values[i]!)) : null); + for (let i = 0; i < length; i++) values[i] = (r.present() ? (values[i] == null ? readPoint(r) : readPoint(r, values[i]!)) : null); if (values.length !== length) values.length = length; return values; } -function write$13(w: NinoWriter, values: readonly (KeyedV1 | null)[] | null): void { - if (values === null || values === undefined) { - w.i32(-1); - return; - } - w.i32(values.length); - for (let i = 0; i < values.length; i++) { - const value = values[i]; - if (value === null || value === undefined) w.u8(0); else { w.u8(1); writeKeyedV1(w, value); } - } +function read$16(r: NinoReader): Map | null { + const length = r.length(); + if (length < 0) return null; + const map = new Map(); + const guard = r.keyGuard(length); + for (let i = 0, at = r.take(length * 8); i < length; i++, at += 8) map.set(guard === null ? r.view.getInt32(at, true) : guard.int(r.view.getInt32(at, true)), r.view.getInt32(at + 4, true)); + if (map.size !== length) throw r.duplicateKey(); + return map; } -function read$14(r: NinoReader): BigInt64Array | null { +function readInto$16(r: NinoReader, cur: Map): Map | null { const length = r.length(); if (length < 0) return null; - if (length > 8) return r.numbers(BigInt64Array, length); - const values = new BigInt64Array(length); - for (let i = 0, at = r.take(length * 8); i < length; i++, at += 8) values[i] = r.view.getBigInt64(at, true); - return values; + const map = cur; + map.clear(); + const guard = r.keyGuard(length); + for (let i = 0, at = r.take(length * 8); i < length; i++, at += 8) map.set(guard === null ? r.view.getInt32(at, true) : guard.int(r.view.getInt32(at, true)), r.view.getInt32(at + 4, true)); + if (map.size !== length) throw r.duplicateKey(); + return map; } -function write$14(w: NinoWriter, values: BigInt64Array | null): void { - if (values === null || values === undefined) { - w.i32(-1); - return; - } - if (values.length > 8) { - w.numbers(values); - return; +function read$17(r: NinoReader): Map | null { + const length = r.length(); + if (length < 0) return null; + const map = new Map(); + const guard = r.keyGuard(length); + for (let i = 0; i < length; i++) { + const key = r.string(); + map.set(guard === null ? key : guard.string(key), r.string()); } - w.i32(values.length); - let at = w.reserve(values.length * 8); + if (map.size !== length) throw r.duplicateKey(); + return map; +} + +function readInto$17(r: NinoReader, cur: Map): Map | null { + const length = r.length(); + if (length < 0) return null; + const map = cur; + map.clear(); + const guard = r.keyGuard(length); + for (let i = 0; i < length; i++) { + const key = r.string(); + map.set(guard === null ? key : guard.string(key), r.string()); + } + if (map.size !== length) throw r.duplicateKey(); + return map; +} + +function read$18(r: NinoReader): Map | null { + const length = r.length(); + if (length < 0) return null; + const map = new Map(); + const guard = r.keyGuard(length); + for (let i = 0; i < length; i++) { + const key = r.string(); + map.set(guard === null ? key : guard.string(key), (r.present() ? readPoint(r) : null)); + } + if (map.size !== length) throw r.duplicateKey(); + return map; +} + +function readInto$18(r: NinoReader, cur: Map): Map | null { + const length = r.length(); + if (length < 0) return null; + const map = cur; + map.clear(); + const guard = r.keyGuard(length); + for (let i = 0; i < length; i++) { + const key = r.string(); + map.set(guard === null ? key : guard.string(key), (r.present() ? readPoint(r) : null)); + } + if (map.size !== length) throw r.duplicateKey(); + return map; +} + +function read$19(r: NinoReader): Map | null { + const length = r.length(); + if (length < 0) return null; + const map = new Map(); + const guard = r.keyGuard(length); + for (let i = 0; i < length; i++) { + const key = r.i32(); + map.set(guard === null ? key : guard.int(key), read$13(r)); + } + if (map.size !== length) throw r.duplicateKey(); + return map; +} + +function readInto$19(r: NinoReader, cur: Map): Map | null { + const length = r.length(); + if (length < 0) return null; + const map = cur; + map.clear(); + const guard = r.keyGuard(length); + for (let i = 0; i < length; i++) { + const key = r.i32(); + map.set(guard === null ? key : guard.int(key), read$13(r)); + } + if (map.size !== length) throw r.duplicateKey(); + return map; +} + +function read$20(r: NinoReader): Map | null { + const length = r.length(); + if (length < 0) return null; + const map = new Map(); + const guard = r.keyGuard(length); + for (let i = 0; i < length; i++) { + const key = r.i32(); + map.set(guard === null ? key : guard.int(key), r.string()); + } + if (map.size !== length) throw r.duplicateKey(); + return map; +} + +function readInto$20(r: NinoReader, cur: Map): Map | null { + const length = r.length(); + if (length < 0) return null; + const map = cur; + map.clear(); + const guard = r.keyGuard(length); + for (let i = 0; i < length; i++) { + const key = r.i32(); + map.set(guard === null ? key : guard.int(key), r.string()); + } + if (map.size !== length) throw r.duplicateKey(); + return map; +} + +function read$21(r: NinoReader): Map | null { + const length = r.length(); + if (length < 0) return null; + const map = new Map(); + const guard = r.keyGuard(length); + for (let i = 0; i < length; i++) { + const key = r.string(); + map.set(guard === null ? key : guard.string(key), r.i32()); + } + if (map.size !== length) throw r.duplicateKey(); + return map; +} + +function readInto$21(r: NinoReader, cur: Map): Map | null { + const length = r.length(); + if (length < 0) return null; + const map = cur; + map.clear(); + const guard = r.keyGuard(length); + for (let i = 0; i < length; i++) { + const key = r.string(); + map.set(guard === null ? key : guard.string(key), r.i32()); + } + if (map.size !== length) throw r.duplicateKey(); + return map; +} + +function read$22(r: NinoReader): (Int32Array | null)[] | null { + const length = r.length(); + if (length < 0) return null; + const values = new Array(r.capacity(length)); + for (let i = 0; i < length; i++) values[i] = read$8(r); + return values; +} + +function readInto$22(r: NinoReader, cur: (Int32Array | null)[]): (Int32Array | null)[] | null { + const length = r.length(); + if (length < 0) return null; + const values = cur; + for (let i = 0; i < length; i++) values[i] = read$8(r); + if (values.length !== length) values.length = length; + return values; +} + +function read$23(r: NinoReader): NinoGrid$ | null { + const shape = r.gridShape(2, 4); + if (shape === null) return null; + const { lengths, count } = shape; + if (count > 16) return { lengths, data: r.numbers(Int32Array, count)! }; + const values = new Int32Array(count); + for (let i = 0, at = r.take(count * 4); i < count; i++, at += 4) values[i] = r.view.getInt32(at, true); + return { lengths, data: values }; +} + +function read$24(r: NinoReader, cur?: NinoGrid$<(string | null)[]> | null): NinoGrid$<(string | null)[]> | null { + const shape = r.gridShape(2, 1); + if (shape === null) return null; + const { lengths, count } = shape; + const reuse = cur != null && lengths.length === cur.lengths.length && lengths.every((n, i) => n === cur.lengths[i]); + const values = reuse ? cur.data : new Array(r.capacity(count)); + for (let i = 0; i < count; i++) values[i] = r.string(); + if (values.length !== count) values.length = count; + if (reuse) return cur; + return { lengths, data: values }; +} + +function write$8(w: NinoWriter, values: Int32Array | null): void { + if (values === null || values === undefined) { + w.i32(-1); + return; + } + if (values.length > 16) { + w.numbers(values); + return; + } + w.i32(values.length); + let at = w.reserve(values.length * 4); + for (let i = 0; i < values.length; i++) { + const value = values[i]; + w.view.setInt32(at, value, true); + at += 4; + } +} + +function write$9(w: NinoWriter, values: ReadonlySet | null): void { + if (values === null || values === undefined) { + w.i32(-1); + return; + } + w.i32(values.size); + let at = w.reserve(values.size * 4); + for (const value of values) { + w.view.setInt32(at, value, true); + at += 4; + } +} + +function write$10(w: NinoWriter, values: BigInt64Array | null): void { + if (values === null || values === undefined) { + w.i32(-1); + return; + } + if (values.length > 8) { + w.numbers(values); + return; + } + w.i32(values.length); + let at = w.reserve(values.length * 8); for (let i = 0; i < values.length; i++) { const value = values[i]; w.view.setBigInt64(at, value, true); @@ -5975,7 +6345,278 @@ function write$14(w: NinoWriter, values: BigInt64Array | null): void { } } -function read$15(r: NinoReader): NullableSlot[] | null { +function write$11(w: NinoWriter, values: Float64Array | null): void { + if (values === null || values === undefined) { + w.i32(-1); + return; + } + if (values.length > 8) { + w.numbers(values); + return; + } + w.i32(values.length); + let at = w.reserve(values.length * 8); + for (let i = 0; i < values.length; i++) { + const value = values[i]; + w.view.setFloat64(at, value, true); + at += 8; + } +} + +function write$12(w: NinoWriter, values: readonly string[] | null): void { + if (values === null || values === undefined) { + w.i32(-1); + return; + } + w.i32(values.length); + let at = w.reserve(values.length * 2); + for (let i = 0; i < values.length; i++) { + const value = values[i]; + w.view.setUint16(at, value.charCodeAt(0), true); + at += 2; + } +} + +function write$13(w: NinoWriter, values: readonly (string | null)[] | null): void { + if (values === null || values === undefined) { + w.i32(-1); + return; + } + w.i32(values.length); + for (let i = 0; i < values.length; i++) { + const value = values[i]; + w.string(value); + } +} + +function write$14(w: NinoWriter, values: ReadonlySet | null): void { + if (values === null || values === undefined) { + w.i32(-1); + return; + } + w.i32(values.size); + for (const value of values) { + w.string(value); + } +} + +function write$15(w: NinoWriter, values: readonly (Point | null)[] | null): void { + if (values === null || values === undefined) { + w.i32(-1); + return; + } + w.i32(values.length); + for (let i = 0; i < values.length; i++) { + const value = values[i]; + if (value === null || value === undefined) w.u8(0); else { w.u8(1); writePoint(w, value); } + } +} + +function write$16(w: NinoWriter, map: ReadonlyMap | null): void { + if (map === null || map === undefined) { + w.i32(-1); + return; + } + w.i32(map.size); + let at = w.reserve(map.size * 8); + for (let keys = map.keys(), values = map.values(), i = map.size; i > 0; i--) { + const key = keys.next().value as number, value = values.next().value as number; + w.view.setInt32(at, key, true); + w.view.setInt32(at + 4, value, true); + at += 8; + } +} + +function write$17(w: NinoWriter, map: ReadonlyMap | null): void { + if (map === null || map === undefined) { + w.i32(-1); + return; + } + w.i32(map.size); + for (let keys = map.keys(), values = map.values(), i = map.size; i > 0; i--) { + const key = keys.next().value as string | null, value = values.next().value as string | null; + w.string(key); + w.string(value); + } +} + +function write$18(w: NinoWriter, map: ReadonlyMap | null): void { + if (map === null || map === undefined) { + w.i32(-1); + return; + } + w.i32(map.size); + for (let keys = map.keys(), values = map.values(), i = map.size; i > 0; i--) { + const key = keys.next().value as string | null, value = values.next().value as Point | null; + w.string(key); + if (value === null || value === undefined) w.u8(0); else { w.u8(1); writePoint(w, value); } + } +} + +function write$19(w: NinoWriter, map: ReadonlyMap | null): void { + if (map === null || map === undefined) { + w.i32(-1); + return; + } + w.i32(map.size); + for (let keys = map.keys(), values = map.values(), i = map.size; i > 0; i--) { + const key = keys.next().value as number, value = values.next().value as (string | null)[] | null; + w.i32(key); + write$13(w, value); + } +} + +function write$20(w: NinoWriter, map: ReadonlyMap | null): void { + if (map === null || map === undefined) { + w.i32(-1); + return; + } + w.i32(map.size); + for (let keys = map.keys(), values = map.values(), i = map.size; i > 0; i--) { + const key = keys.next().value as number, value = values.next().value as string | null; + w.i32(key); + w.string(value); + } +} + +function write$21(w: NinoWriter, map: ReadonlyMap | null): void { + if (map === null || map === undefined) { + w.i32(-1); + return; + } + w.i32(map.size); + for (let keys = map.keys(), values = map.values(), i = map.size; i > 0; i--) { + const key = keys.next().value as string | null, value = values.next().value as number; + w.string(key); + w.i32(value); + } +} + +function write$22(w: NinoWriter, values: readonly (Int32Array | null)[] | null): void { + if (values === null || values === undefined) { + w.i32(-1); + return; + } + w.i32(values.length); + for (let i = 0; i < values.length; i++) { + const value = values[i]; + write$8(w, value); + } +} + +function write$23(w: NinoWriter, grid: NinoGrid$ | null): void { + if (grid == null) { w.i32(-1); return; } + const values = grid.data; + w.gridShape(2, grid.lengths, values.length); + if (values.length > 16) { w.numberBlock(values); return; } + let at = w.reserve(values.length * 4); + for (let i = 0; i < values.length; i++) { + const value = values[i]; + w.view.setInt32(at, value, true); + at += 4; + } +} + +function write$24(w: NinoWriter, grid: NinoGrid$<(string | null)[]> | null): void { + if (grid == null) { w.i32(-1); return; } + const values = grid.data; + w.gridShape(2, grid.lengths, values.length); + for (let i = 0; i < values.length; i++) { + const value = values[i]; + w.string(value); + } +} + +function read$25(r: NinoReader): E32[] | null { + const length = r.length(); + if (length < 0) return null; + const values = new Array(r.capacity(length)); + for (let i = 0, at = r.take(length * 4); i < length; i++, at += 4) values[i] = r.view.getInt32(at, true) as E32; + return values; +} + +function readInto$25(r: NinoReader, cur: E32[]): E32[] | null { + const length = r.length(); + if (length < 0) return null; + const values = cur; + for (let i = 0, at = r.take(length * 4); i < length; i++, at += 4) values[i] = r.view.getInt32(at, true) as E32; + if (values.length !== length) values.length = length; + return values; +} + +function write$25(w: NinoWriter, values: readonly E32[] | null): void { + if (values === null || values === undefined) { + w.i32(-1); + return; + } + w.i32(values.length); + let at = w.reserve(values.length * 4); + for (let i = 0; i < values.length; i++) { + const value = values[i]; + w.view.setInt32(at, value, true); + at += 4; + } +} + +function read$26(r: NinoReader): (Shelf | null)[] | null { + const length = r.length(); + if (length < 0) return null; + const values = new Array | null>(r.capacity(length)); + for (let i = 0; i < length; i++) values[i] = slot$0.read(r); + return values; +} + +function readInto$26(r: NinoReader, cur: (Shelf | null)[]): (Shelf | null)[] | null { + const length = r.length(); + if (length < 0) return null; + const values = cur; + for (let i = 0; i < length; i++) values[i] = (values[i] == null ? slot$0.read(r) : r.into(slot$0, values[i])); + if (values.length !== length) values.length = length; + return values; +} + +function write$26(w: NinoWriter, values: readonly (Shelf | null)[] | null): void { + if (values === null || values === undefined) { + w.i32(-1); + return; + } + w.i32(values.length); + for (let i = 0; i < values.length; i++) { + const value = values[i]; + slot$0.write(w, value); + } +} + +function read$27(r: NinoReader): (KeyedV1 | null)[] | null { + const length = r.length(); + if (length < 0) return null; + const values = new Array(r.capacity(length)); + for (let i = 0; i < length; i++) values[i] = (r.present() ? readKeyedV1(r) : null); + return values; +} + +function readInto$27(r: NinoReader, cur: (KeyedV1 | null)[]): (KeyedV1 | null)[] | null { + const length = r.length(); + if (length < 0) return null; + const values = cur; + for (let i = 0; i < length; i++) values[i] = (r.present() ? (values[i] == null ? readKeyedV1(r) : readKeyedV1(r, values[i]!)) : null); + if (values.length !== length) values.length = length; + return values; +} + +function write$27(w: NinoWriter, values: readonly (KeyedV1 | null)[] | null): void { + if (values === null || values === undefined) { + w.i32(-1); + return; + } + w.i32(values.length); + for (let i = 0; i < values.length; i++) { + const value = values[i]; + if (value === null || value === undefined) w.u8(0); else { w.u8(1); writeKeyedV1(w, value); } + } +} + +function read$28(r: NinoReader): NullableSlot[] | null { const length = r.length(); if (length < 0) return null; const values = new Array>(r.capacity(length)); @@ -5983,7 +6624,7 @@ function read$15(r: NinoReader): NullableSlot[] | null { return values; } -function readInto$15(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null { +function readInto$28(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -5992,12 +6633,36 @@ function readInto$15(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null): void { - if (values === null || values === undefined) { - w.i32(-1); - return; - } - w.i32(values.length); +function write$28(w: NinoWriter, values: readonly NullableSlot[] | null): void { + if (values === null || values === undefined) { + w.i32(-1); + return; + } + w.i32(values.length); + let at = w.raw(values.length * 8); + for (let i = 0; i < values.length; i++) { + const value = values[i]; + if (value !== null && value !== undefined) { w.view.setUint8(at, 1); w.view.setInt32(at + 4, value, true); } + at += 8; + } +} + +function read$29(r: NinoReader, cur?: NinoGrid$[]> | null): NinoGrid$[]> | null { + const shape = r.gridShape(2, 8); + if (shape === null) return null; + const { lengths, count } = shape; + const reuse = cur != null && lengths.length === cur.lengths.length && lengths.every((n, i) => n === cur.lengths[i]); + const values = reuse ? cur.data : new Array>(r.capacity(count)); + for (let i = 0, at = r.take(count * 8); i < count; i++, at += 8) values[i] = (r.presentAt(at) ? r.view.getInt32(at + 4, true) : null); + if (values.length !== count) values.length = count; + if (reuse) return cur; + return { lengths, data: values }; +} + +function write$29(w: NinoWriter, grid: NinoGrid$[]> | null): void { + if (grid == null) { w.i32(-1); return; } + const values = grid.data; + w.gridShape(2, grid.lengths, values.length); let at = w.raw(values.length * 8); for (let i = 0; i < values.length; i++) { const value = values[i]; @@ -6006,7 +6671,7 @@ function write$15(w: NinoWriter, values: readonly NullableSlot[] | null) } } -function read$16(r: NinoReader): Set> | null { +function read$30(r: NinoReader): Set> | null { const length = r.length(); if (length < 0) return null; const values = new Set>(); @@ -6016,7 +6681,7 @@ function read$16(r: NinoReader): Set> | null { return values; } -function readInto$16(r: NinoReader, cur: Set>): Set> | null { +function readInto$30(r: NinoReader, cur: Set>): Set> | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -6027,7 +6692,7 @@ function readInto$16(r: NinoReader, cur: Set>): Set> | null): void { +function write$30(w: NinoWriter, values: ReadonlySet> | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -6040,7 +6705,7 @@ function write$16(w: NinoWriter, values: ReadonlySet> | nul } } -function read$17(r: NinoReader): NinoNullable[] | null { +function read$31(r: NinoReader): NinoNullable[] | null { const length = r.length(); if (length < 0) return null; const values = new Array>(r.capacity(length)); @@ -6048,7 +6713,7 @@ function read$17(r: NinoReader): NinoNullable[] | null { return values; } -function readInto$17(r: NinoReader, cur: NinoNullable[]): NinoNullable[] | null { +function readInto$31(r: NinoReader, cur: NinoNullable[]): NinoNullable[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -6057,7 +6722,7 @@ function readInto$17(r: NinoReader, cur: NinoNullable[]): NinoNullable[] | null { +function read$32(r: NinoReader): NinoNullable[] | null { const length = r.length(); if (length < 0) return null; const values = new Array>(r.capacity(length)); @@ -6065,7 +6730,7 @@ function read$18(r: NinoReader): NinoNullable[] | null { return values; } -function readInto$18(r: NinoReader, cur: NinoNullable[]): NinoNullable[] | null { +function readInto$32(r: NinoReader, cur: NinoNullable[]): NinoNullable[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -6074,7 +6739,7 @@ function readInto$18(r: NinoReader, cur: NinoNullable[]): NinoNullable[] | null { +function read$33(r: NinoReader): NinoNullable[] | null { const length = r.length(); if (length < 0) return null; const values = new Array>(r.capacity(length)); @@ -6082,7 +6747,7 @@ function read$19(r: NinoReader): NinoNullable[] | null { return values; } -function readInto$19(r: NinoReader, cur: NinoNullable[]): NinoNullable[] | null { +function readInto$33(r: NinoReader, cur: NinoNullable[]): NinoNullable[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -6091,7 +6756,7 @@ function readInto$19(r: NinoReader, cur: NinoNullable[]): NinoNullable[] | null): void { +function write$31(w: NinoWriter, values: readonly NinoNullable[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -6105,7 +6770,7 @@ function write$17(w: NinoWriter, values: readonly NinoNullable[] | null) } } -function write$18(w: NinoWriter, values: readonly NinoNullable[] | null): void { +function write$32(w: NinoWriter, values: readonly NinoNullable[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -6119,7 +6784,7 @@ function write$18(w: NinoWriter, values: readonly NinoNullable[] | null) } } -function write$19(w: NinoWriter, values: readonly NinoNullable[] | null): void { +function write$33(w: NinoWriter, values: readonly NinoNullable[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -6133,7 +6798,7 @@ function write$19(w: NinoWriter, values: readonly NinoNullable[] | null) } } -function read$20(r: NinoReader): NinoNullable[] | null { +function read$34(r: NinoReader): NinoNullable[] | null { const length = r.length(); if (length < 0) return null; const values = new Array>(r.capacity(length)); @@ -6141,7 +6806,7 @@ function read$20(r: NinoReader): NinoNullable[] | null { return values; } -function readInto$20(r: NinoReader, cur: NinoNullable[]): NinoNullable[] | null { +function readInto$34(r: NinoReader, cur: NinoNullable[]): NinoNullable[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -6150,7 +6815,7 @@ function readInto$20(r: NinoReader, cur: NinoNullable[]): NinoNullable[] | null { +function read$35(r: NinoReader): NinoNullable[] | null { const length = r.length(); if (length < 0) return null; const values = new Array>(r.capacity(length)); @@ -6158,7 +6823,7 @@ function read$21(r: NinoReader): NinoNullable[] | null { return values; } -function readInto$21(r: NinoReader, cur: NinoNullable[]): NinoNullable[] | null { +function readInto$35(r: NinoReader, cur: NinoNullable[]): NinoNullable[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -6167,7 +6832,7 @@ function readInto$21(r: NinoReader, cur: NinoNullable[]): NinoNullable[] | null { +function read$36(r: NinoReader): NinoNullable[] | null { const length = r.length(); if (length < 0) return null; const values = new Array>(r.capacity(length)); @@ -6175,7 +6840,7 @@ function read$22(r: NinoReader): NinoNullable[] | null { return values; } -function readInto$22(r: NinoReader, cur: NinoNullable[]): NinoNullable[] | null { +function readInto$36(r: NinoReader, cur: NinoNullable[]): NinoNullable[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -6184,7 +6849,7 @@ function readInto$22(r: NinoReader, cur: NinoNullable[]): NinoNullable

> | null { +function read$37(r: NinoReader): Map> | null { const length = r.length(); if (length < 0) return null; const map = new Map>(); @@ -6194,7 +6859,7 @@ function read$23(r: NinoReader): Map> | null { return map; } -function readInto$23(r: NinoReader, cur: Map>): Map> | null { +function readInto$37(r: NinoReader, cur: Map>): Map> | null { const length = r.length(); if (length < 0) return null; const map = cur; @@ -6205,7 +6870,7 @@ function readInto$23(r: NinoReader, cur: Map>): Map return map; } -function read$24(r: NinoReader): NinoNullableFields[] | null { +function read$38(r: NinoReader): NinoNullableFields[] | null { const length = r.length(); if (length < 0) return null; const values = new Array(r.capacity(length)); @@ -6213,7 +6878,7 @@ function read$24(r: NinoReader): NinoNullableFields[] | null { return values; } -function readInto$24(r: NinoReader, cur: NinoNullableFields[]): NinoNullableFields[] | null { +function readInto$38(r: NinoReader, cur: NinoNullableFields[]): NinoNullableFields[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -6222,7 +6887,7 @@ function readInto$24(r: NinoReader, cur: NinoNullableFields[]): NinoNullableFiel return values; } -function write$20(w: NinoWriter, values: readonly NinoNullable[] | null): void { +function write$34(w: NinoWriter, values: readonly NinoNullable[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -6236,7 +6901,7 @@ function write$20(w: NinoWriter, values: readonly NinoNullable[] | null) } } -function write$21(w: NinoWriter, values: readonly NinoNullable[] | null): void { +function write$35(w: NinoWriter, values: readonly NinoNullable[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -6250,7 +6915,7 @@ function write$21(w: NinoWriter, values: readonly NinoNullable[] | null) } } -function write$22(w: NinoWriter, values: readonly NinoNullable[] | null): void { +function write$36(w: NinoWriter, values: readonly NinoNullable[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -6264,7 +6929,7 @@ function write$22(w: NinoWriter, values: readonly NinoNullable[] | null) } } -function write$23(w: NinoWriter, map: ReadonlyMap> | null): void { +function write$37(w: NinoWriter, map: ReadonlyMap> | null): void { if (map === null || map === undefined) { w.i32(-1); return; @@ -6279,7 +6944,7 @@ function write$23(w: NinoWriter, map: ReadonlyMap> } } -function write$24(w: NinoWriter, values: readonly NinoNullableFields[] | null): void { +function write$38(w: NinoWriter, values: readonly NinoNullableFields[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -6293,7 +6958,163 @@ function write$24(w: NinoWriter, values: readonly NinoNullableFields[] | null): } } -function read$25(r: NinoReader): NullableSlot[] | null { +function read$39(r: NinoReader): Set> | null { + const length = r.length(); + if (length < 0) return null; + const values = new Set>(); + const guard = r.keyGuard(length); + for (let i = 0, at = r.take(length * 16); i < length; i++, at += 16) values.add(guard === null ? (r.presentAt(at) ? r.view.getBigInt64(at + 8, true) : null) : guard.key((r.presentAt(at) ? r.view.getBigInt64(at + 8, true) : null))); + if (values.size !== length) throw r.duplicateKey(); + return values; +} + +function readInto$39(r: NinoReader, cur: Set>): Set> | null { + const length = r.length(); + if (length < 0) return null; + const values = cur; + values.clear(); + const guard = r.keyGuard(length); + for (let i = 0, at = r.take(length * 16); i < length; i++, at += 16) values.add(guard === null ? (r.presentAt(at) ? r.view.getBigInt64(at + 8, true) : null) : guard.key((r.presentAt(at) ? r.view.getBigInt64(at + 8, true) : null))); + if (values.size !== length) throw r.duplicateKey(); + return values; +} + +function read$40(r: NinoReader, cur?: NinoGrid$[]> | null): NinoGrid$[]> | null { + const shape = r.gridShape(2, 24); + if (shape === null) return null; + const { lengths, count } = shape; + const reuse = cur != null && lengths.length === cur.lengths.length && lengths.every((n, i) => n === cur.lengths[i]); + const values = reuse ? cur.data : new Array>(r.capacity(count)); + for (let i = 0, at = r.take(count * 24); i < count; i++, at += 24) values[i] = (r.presentAt(at) ? readPadded(r, at + 8) : null); + if (values.length !== count) values.length = count; + if (reuse) return cur; + return { lengths, data: values }; +} + +function read$41(r: NinoReader): (Set> | null)[] | null { + const length = r.length(); + if (length < 0) return null; + const values = new Array> | null>(r.capacity(length)); + for (let i = 0; i < length; i++) values[i] = read$30(r); + return values; +} + +function readInto$41(r: NinoReader, cur: (Set> | null)[]): (Set> | null)[] | null { + const length = r.length(); + if (length < 0) return null; + const values = cur; + for (let i = 0; i < length; i++) values[i] = (values[i] == null ? read$30(r) : readInto$30(r, values[i]!)); + if (values.length !== length) values.length = length; + return values; +} + +function read$42(r: NinoReader): Map | null { + const length = r.length(); + if (length < 0) return null; + const map = new Map(); + const guard = r.keyGuard(length); + for (let i = 0; i < length; i++) { + const key = r.i32(); + map.set(guard === null ? key : guard.int(key), (r.present() ? r.i64() : null)); + } + if (map.size !== length) throw r.duplicateKey(); + return map; +} + +function readInto$42(r: NinoReader, cur: Map): Map | null { + const length = r.length(); + if (length < 0) return null; + const map = cur; + map.clear(); + const guard = r.keyGuard(length); + for (let i = 0; i < length; i++) { + const key = r.i32(); + map.set(guard === null ? key : guard.int(key), (r.present() ? r.i64() : null)); + } + if (map.size !== length) throw r.duplicateKey(); + return map; +} + +function read$43(r: NinoReader): ([number, number | null])[] | null { + const length = r.length(); + if (length < 0) return null; + const values = new Array<[number, number | null]>(r.capacity(length)); + for (let i = 0; i < length; i++) values[i] = [r.i32(), (r.present() ? r.i32() : null)]; + return values; +} + +function readInto$43(r: NinoReader, cur: ([number, number | null])[]): ([number, number | null])[] | null { + const length = r.length(); + if (length < 0) return null; + const values = cur; + for (let i = 0; i < length; i++) values[i] = [r.i32(), (r.present() ? r.i32() : null)]; + if (values.length !== length) values.length = length; + return values; +} + +function write$39(w: NinoWriter, values: ReadonlySet> | null): void { + if (values === null || values === undefined) { + w.i32(-1); + return; + } + w.i32(values.size); + let at = w.raw(values.size * 16); + for (const value of values) { + if (value !== null && value !== undefined) { w.view.setUint8(at, 1); w.view.setBigInt64(at + 8, value, true); } + at += 16; + } +} + +function write$40(w: NinoWriter, grid: NinoGrid$[]> | null): void { + if (grid == null) { w.i32(-1); return; } + const values = grid.data; + w.gridShape(2, grid.lengths, values.length); + let at = w.raw(values.length * 24); + for (let i = 0; i < values.length; i++) { + const value = values[i]; + if (value !== null && value !== undefined) { w.view.setUint8(at, 1); writePadded(w, at + 8, value); } + at += 24; + } +} + +function write$41(w: NinoWriter, values: readonly (Set> | null)[] | null): void { + if (values === null || values === undefined) { + w.i32(-1); + return; + } + w.i32(values.length); + for (let i = 0; i < values.length; i++) { + const value = values[i]; + write$30(w, value); + } +} + +function write$42(w: NinoWriter, map: ReadonlyMap | null): void { + if (map === null || map === undefined) { + w.i32(-1); + return; + } + w.i32(map.size); + for (let keys = map.keys(), values = map.values(), i = map.size; i > 0; i--) { + const key = keys.next().value as number, value = values.next().value as bigint | null; + w.i32(key); + if (value === null || value === undefined) w.u8(0); else { w.u8(1); w.i64(value); } + } +} + +function write$43(w: NinoWriter, values: readonly ([number, number | null])[] | null): void { + if (values === null || values === undefined) { + w.i32(-1); + return; + } + w.i32(values.length); + for (let i = 0; i < values.length; i++) { + const value = values[i]; + w.i32(value[0]); if (value[1] === null || value[1] === undefined) w.u8(0); else { w.u8(1); w.i32(value[1]); } + } +} + +function read$44(r: NinoReader): NullableSlot[] | null { const length = r.length(); if (length < 0) return null; const values = new Array>(r.capacity(length)); @@ -6301,7 +7122,7 @@ function read$25(r: NinoReader): NullableSlot[] | null { return values; } -function readInto$25(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null { +function readInto$44(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -6310,7 +7131,7 @@ function readInto$25(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null { +function read$45(r: NinoReader): NullableSlot[] | null { const length = r.length(); if (length < 0) return null; const values = new Array>(r.capacity(length)); @@ -6318,7 +7139,7 @@ function read$26(r: NinoReader): NullableSlot[] | null { return values; } -function readInto$26(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null { +function readInto$45(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -6327,7 +7148,7 @@ function readInto$26(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null): void { +function write$44(w: NinoWriter, values: readonly NullableSlot[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -6341,7 +7162,7 @@ function write$25(w: NinoWriter, values: readonly NullableSlot[] | null) } } -function write$26(w: NinoWriter, values: readonly NullableSlot[] | null): void { +function write$45(w: NinoWriter, values: readonly NullableSlot[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -6355,7 +7176,7 @@ function write$26(w: NinoWriter, values: readonly NullableSlot[] | null) } } -function read$27(r: NinoReader): NullableSlot[] | null { +function read$46(r: NinoReader): NullableSlot[] | null { const length = r.length(); if (length < 0) return null; const values = new Array>(r.capacity(length)); @@ -6363,7 +7184,7 @@ function read$27(r: NinoReader): NullableSlot[] | null { return values; } -function readInto$27(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null { +function readInto$46(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -6372,7 +7193,7 @@ function readInto$27(r: NinoReader, cur: NullableSlot[]): NullableSlot

| null { +function read$47(r: NinoReader): Map | null { const length = r.length(); if (length < 0) return null; const map = new Map(); @@ -6385,7 +7206,7 @@ function read$28(r: NinoReader): Map | null { return map; } -function readInto$28(r: NinoReader, cur: Map): Map | null { +function readInto$47(r: NinoReader, cur: Map): Map | null { const length = r.length(); if (length < 0) return null; const map = cur; @@ -6399,7 +7220,7 @@ function readInto$28(r: NinoReader, cur: Map): Map[] | null): void { +function write$46(w: NinoWriter, values: readonly NullableSlot[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -6413,7 +7234,7 @@ function write$27(w: NinoWriter, values: readonly NullableSlot[] | null) } } -function write$28(w: NinoWriter, map: ReadonlyMap | null): void { +function write$47(w: NinoWriter, map: ReadonlyMap | null): void { if (map === null || map === undefined) { w.i32(-1); return; @@ -6426,7 +7247,7 @@ function write$28(w: NinoWriter, map: ReadonlyMap | null) } } -function read$29(r: NinoReader): Padded[] | null { +function read$48(r: NinoReader): Padded[] | null { const length = r.length(); if (length < 0) return null; const values = new Array(r.capacity(length)); @@ -6434,7 +7255,7 @@ function read$29(r: NinoReader): Padded[] | null { return values; } -function readInto$29(r: NinoReader, cur: Padded[]): Padded[] | null { +function readInto$48(r: NinoReader, cur: Padded[]): Padded[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -6443,7 +7264,7 @@ function readInto$29(r: NinoReader, cur: Padded[]): Padded[] | null { return values; } -function write$29(w: NinoWriter, values: readonly Padded[] | null): void { +function write$48(w: NinoWriter, values: readonly Padded[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -6457,36 +7278,7 @@ function write$29(w: NinoWriter, values: readonly Padded[] | null): void { } } -function read$30(r: NinoReader): (Point | null)[] | null { - const length = r.length(); - if (length < 0) return null; - const values = new Array(r.capacity(length)); - for (let i = 0; i < length; i++) values[i] = (r.present() ? readPoint(r) : null); - return values; -} - -function readInto$30(r: NinoReader, cur: (Point | null)[]): (Point | null)[] | null { - const length = r.length(); - if (length < 0) return null; - const values = cur; - for (let i = 0; i < length; i++) values[i] = (r.present() ? (values[i] == null ? readPoint(r) : readPoint(r, values[i]!)) : null); - if (values.length !== length) values.length = length; - return values; -} - -function write$30(w: NinoWriter, values: readonly (Point | null)[] | null): void { - if (values === null || values === undefined) { - w.i32(-1); - return; - } - w.i32(values.length); - for (let i = 0; i < values.length; i++) { - const value = values[i]; - if (value === null || value === undefined) w.u8(0); else { w.u8(1); writePoint(w, value); } - } -} - -function read$31(r: NinoReader): RawOptional[] | null { +function read$49(r: NinoReader): RawOptional[] | null { const length = r.length(); if (length < 0) return null; const values = new Array(r.capacity(length)); @@ -6494,7 +7286,7 @@ function read$31(r: NinoReader): RawOptional[] | null { return values; } -function readInto$31(r: NinoReader, cur: RawOptional[]): RawOptional[] | null { +function readInto$49(r: NinoReader, cur: RawOptional[]): RawOptional[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -6503,7 +7295,7 @@ function readInto$31(r: NinoReader, cur: RawOptional[]): RawOptional[] | null { return values; } -function write$31(w: NinoWriter, values: readonly RawOptional[] | null): void { +function write$49(w: NinoWriter, values: readonly RawOptional[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -6517,108 +7309,7 @@ function write$31(w: NinoWriter, values: readonly RawOptional[] | null): void { } } -function read$32(r: NinoReader): (string | null)[] | null { - const length = r.length(); - if (length < 0) return null; - const values = new Array(r.capacity(length)); - for (let i = 0; i < length; i++) values[i] = r.string(); - return values; -} - -function readInto$32(r: NinoReader, cur: (string | null)[]): (string | null)[] | null { - const length = r.length(); - if (length < 0) return null; - const values = cur; - for (let i = 0; i < length; i++) values[i] = r.string(); - if (values.length !== length) values.length = length; - return values; -} - -function write$32(w: NinoWriter, values: readonly (string | null)[] | null): void { - if (values === null || values === undefined) { - w.i32(-1); - return; - } - w.i32(values.length); - for (let i = 0; i < values.length; i++) { - const value = values[i]; - w.string(value); - } -} - -function read$33(r: NinoReader): Map | null { - const length = r.length(); - if (length < 0) return null; - const map = new Map(); - const guard = r.keyGuard(length); - for (let i = 0; i < length; i++) { - const key = r.string(); - map.set(guard === null ? key : guard.string(key), r.i32()); - } - if (map.size !== length) throw r.duplicateKey(); - return map; -} - -function readInto$33(r: NinoReader, cur: Map): Map | null { - const length = r.length(); - if (length < 0) return null; - const map = cur; - map.clear(); - const guard = r.keyGuard(length); - for (let i = 0; i < length; i++) { - const key = r.string(); - map.set(guard === null ? key : guard.string(key), r.i32()); - } - if (map.size !== length) throw r.duplicateKey(); - return map; -} - -function write$33(w: NinoWriter, map: ReadonlyMap | null): void { - if (map === null || map === undefined) { - w.i32(-1); - return; - } - w.i32(map.size); - for (let keys = map.keys(), values = map.values(), i = map.size; i > 0; i--) { - const key = keys.next().value as string | null, value = values.next().value as number; - w.string(key); - w.i32(value); - } -} - -function read$34(r: NinoReader): Set | null { - const length = r.length(); - if (length < 0) return null; - const values = new Set(); - const guard = r.keyGuard(length); - for (let i = 0; i < length; i++) values.add(guard === null ? r.string() : guard.string(r.string())); - if (values.size !== length) throw r.duplicateKey(); - return values; -} - -function readInto$34(r: NinoReader, cur: Set): Set | null { - const length = r.length(); - if (length < 0) return null; - const values = cur; - values.clear(); - const guard = r.keyGuard(length); - for (let i = 0; i < length; i++) values.add(guard === null ? r.string() : guard.string(r.string())); - if (values.size !== length) throw r.duplicateKey(); - return values; -} - -function write$34(w: NinoWriter, values: ReadonlySet | null): void { - if (values === null || values === undefined) { - w.i32(-1); - return; - } - w.i32(values.size); - for (const value of values) { - w.string(value); - } -} - -function read$35(r: NinoReader): Vec2[] | null { +function read$50(r: NinoReader): Vec2[] | null { const length = r.length(); if (length < 0) return null; const values = new Array(r.capacity(length)); @@ -6626,7 +7317,7 @@ function read$35(r: NinoReader): Vec2[] | null { return values; } -function readInto$35(r: NinoReader, cur: Vec2[]): Vec2[] | null { +function readInto$50(r: NinoReader, cur: Vec2[]): Vec2[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -6635,7 +7326,7 @@ function readInto$35(r: NinoReader, cur: Vec2[]): Vec2[] | null { return values; } -function read$36(r: NinoReader): Mixed[] | null { +function read$51(r: NinoReader): Mixed[] | null { const length = r.length(); if (length < 0) return null; const values = new Array(r.capacity(length)); @@ -6643,7 +7334,7 @@ function read$36(r: NinoReader): Mixed[] | null { return values; } -function readInto$36(r: NinoReader, cur: Mixed[]): Mixed[] | null { +function readInto$51(r: NinoReader, cur: Mixed[]): Mixed[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -6652,7 +7343,7 @@ function readInto$36(r: NinoReader, cur: Mixed[]): Mixed[] | null { return values; } -function read$37(r: NinoReader): Label[] | null { +function read$52(r: NinoReader): Label[] | null { const length = r.length(); if (length < 0) return null; const values = new Array

> | null { +function read$38(r: NinoReader): Map> | null { const length = r.length(); if (length < 0) return null; const map = new Map>(); @@ -6237,7 +6906,7 @@ function read$24(r: NinoReader): Map> | null { return map; } -function readInto$24(r: NinoReader, cur: Map>): Map> | null { +function readInto$38(r: NinoReader, cur: Map>): Map> | null { const length = r.length(); if (length < 0) return null; const map = cur; @@ -6248,7 +6917,7 @@ function readInto$24(r: NinoReader, cur: Map>): Map return map; } -function read$25(r: NinoReader): NinoNullableFields[] | null { +function read$39(r: NinoReader): NinoNullableFields[] | null { const length = r.length(); if (length < 0) return null; const values = new Array(r.capacity(length)); @@ -6256,7 +6925,7 @@ function read$25(r: NinoReader): NinoNullableFields[] | null { return values; } -function readInto$25(r: NinoReader, cur: NinoNullableFields[]): NinoNullableFields[] | null { +function readInto$39(r: NinoReader, cur: NinoNullableFields[]): NinoNullableFields[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -6265,7 +6934,7 @@ function readInto$25(r: NinoReader, cur: NinoNullableFields[]): NinoNullableFiel return values; } -function write$21(w: NinoWriter, values: readonly NinoNullable[] | null): void { +function write$35(w: NinoWriter, values: readonly NinoNullable[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -6279,7 +6948,7 @@ function write$21(w: NinoWriter, values: readonly NinoNullable[] | null) } } -function write$22(w: NinoWriter, values: readonly NinoNullable[] | null): void { +function write$36(w: NinoWriter, values: readonly NinoNullable[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -6293,7 +6962,7 @@ function write$22(w: NinoWriter, values: readonly NinoNullable[] | null) } } -function write$23(w: NinoWriter, values: readonly NinoNullable[] | null): void { +function write$37(w: NinoWriter, values: readonly NinoNullable[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -6307,7 +6976,7 @@ function write$23(w: NinoWriter, values: readonly NinoNullable[] | null) } } -function write$24(w: NinoWriter, map: ReadonlyMap> | null): void { +function write$38(w: NinoWriter, map: ReadonlyMap> | null): void { if (map === null || map === undefined) { w.i32(-1); return; @@ -6322,7 +6991,7 @@ function write$24(w: NinoWriter, map: ReadonlyMap> } } -function write$25(w: NinoWriter, values: readonly NinoNullableFields[] | null): void { +function write$39(w: NinoWriter, values: readonly NinoNullableFields[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -6336,7 +7005,163 @@ function write$25(w: NinoWriter, values: readonly NinoNullableFields[] | null): } } -function read$26(r: NinoReader): NullableSlot[] | null { +function read$40(r: NinoReader): Set> | null { + const length = r.length(); + if (length < 0) return null; + const values = new Set>(); + const guard = r.keyGuard(length); + for (let i = 0, at = r.take(length * 16); i < length; i++, at += 16) values.add(guard === null ? (r.presentAt(at) ? r.view.getBigInt64(at + 8, true) : null) : guard.key((r.presentAt(at) ? r.view.getBigInt64(at + 8, true) : null))); + if (values.size !== length) throw r.duplicateKey(); + return values; +} + +function readInto$40(r: NinoReader, cur: Set>): Set> | null { + const length = r.length(); + if (length < 0) return null; + const values = cur; + values.clear(); + const guard = r.keyGuard(length); + for (let i = 0, at = r.take(length * 16); i < length; i++, at += 16) values.add(guard === null ? (r.presentAt(at) ? r.view.getBigInt64(at + 8, true) : null) : guard.key((r.presentAt(at) ? r.view.getBigInt64(at + 8, true) : null))); + if (values.size !== length) throw r.duplicateKey(); + return values; +} + +function read$41(r: NinoReader, cur?: NinoGrid$[]> | null): NinoGrid$[]> | null { + const shape = r.gridShape(2, 24); + if (shape === null) return null; + const { lengths, count } = shape; + const reuse = cur != null && lengths.length === cur.lengths.length && lengths.every((n, i) => n === cur.lengths[i]); + const values = reuse ? cur.data : new Array>(r.capacity(count)); + for (let i = 0, at = r.take(count * 24); i < count; i++, at += 24) values[i] = (r.presentAt(at) ? readPadded(r, at + 8) : null); + if (values.length !== count) values.length = count; + if (reuse) return cur; + return { lengths, data: values }; +} + +function read$42(r: NinoReader): (Set> | null)[] | null { + const length = r.length(); + if (length < 0) return null; + const values = new Array> | null>(r.capacity(length)); + for (let i = 0; i < length; i++) values[i] = read$31(r); + return values; +} + +function readInto$42(r: NinoReader, cur: (Set> | null)[]): (Set> | null)[] | null { + const length = r.length(); + if (length < 0) return null; + const values = cur; + for (let i = 0; i < length; i++) values[i] = (values[i] == null ? read$31(r) : readInto$31(r, values[i]!)); + if (values.length !== length) values.length = length; + return values; +} + +function read$43(r: NinoReader): Map | null { + const length = r.length(); + if (length < 0) return null; + const map = new Map(); + const guard = r.keyGuard(length); + for (let i = 0; i < length; i++) { + const key = r.i32(); + map.set(guard === null ? key : guard.int(key), (r.present() ? r.i64() : null)); + } + if (map.size !== length) throw r.duplicateKey(); + return map; +} + +function readInto$43(r: NinoReader, cur: Map): Map | null { + const length = r.length(); + if (length < 0) return null; + const map = cur; + map.clear(); + const guard = r.keyGuard(length); + for (let i = 0; i < length; i++) { + const key = r.i32(); + map.set(guard === null ? key : guard.int(key), (r.present() ? r.i64() : null)); + } + if (map.size !== length) throw r.duplicateKey(); + return map; +} + +function read$44(r: NinoReader): ([number, number | null])[] | null { + const length = r.length(); + if (length < 0) return null; + const values = new Array<[number, number | null]>(r.capacity(length)); + for (let i = 0; i < length; i++) values[i] = [r.i32(), (r.present() ? r.i32() : null)]; + return values; +} + +function readInto$44(r: NinoReader, cur: ([number, number | null])[]): ([number, number | null])[] | null { + const length = r.length(); + if (length < 0) return null; + const values = cur; + for (let i = 0; i < length; i++) values[i] = [r.i32(), (r.present() ? r.i32() : null)]; + if (values.length !== length) values.length = length; + return values; +} + +function write$40(w: NinoWriter, values: ReadonlySet> | null): void { + if (values === null || values === undefined) { + w.i32(-1); + return; + } + w.i32(values.size); + let at = w.raw(values.size * 16); + for (const value of values) { + if (value !== null && value !== undefined) { w.view.setUint8(at, 1); w.view.setBigInt64(at + 8, value, true); } + at += 16; + } +} + +function write$41(w: NinoWriter, grid: NinoGrid$[]> | null): void { + if (grid == null) { w.i32(-1); return; } + const values = grid.data; + w.gridShape(2, grid.lengths, values.length); + let at = w.raw(values.length * 24); + for (let i = 0; i < values.length; i++) { + const value = values[i]; + if (value !== null && value !== undefined) { w.view.setUint8(at, 1); writePadded(w, at + 8, value); } + at += 24; + } +} + +function write$42(w: NinoWriter, values: readonly (Set> | null)[] | null): void { + if (values === null || values === undefined) { + w.i32(-1); + return; + } + w.i32(values.length); + for (let i = 0; i < values.length; i++) { + const value = values[i]; + write$31(w, value); + } +} + +function write$43(w: NinoWriter, map: ReadonlyMap | null): void { + if (map === null || map === undefined) { + w.i32(-1); + return; + } + w.i32(map.size); + for (let keys = map.keys(), values = map.values(), i = map.size; i > 0; i--) { + const key = keys.next().value as number, value = values.next().value as bigint | null; + w.i32(key); + if (value === null || value === undefined) w.u8(0); else { w.u8(1); w.i64(value); } + } +} + +function write$44(w: NinoWriter, values: readonly ([number, number | null])[] | null): void { + if (values === null || values === undefined) { + w.i32(-1); + return; + } + w.i32(values.length); + for (let i = 0; i < values.length; i++) { + const value = values[i]; + w.i32(value[0]); if (value[1] === null || value[1] === undefined) w.u8(0); else { w.u8(1); w.i32(value[1]); } + } +} + +function read$45(r: NinoReader): NullableSlot[] | null { const length = r.length(); if (length < 0) return null; const values = new Array>(r.capacity(length)); @@ -6344,7 +7169,7 @@ function read$26(r: NinoReader): NullableSlot[] | null { return values; } -function readInto$26(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null { +function readInto$45(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -6353,7 +7178,7 @@ function readInto$26(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null { +function read$46(r: NinoReader): NullableSlot[] | null { const length = r.length(); if (length < 0) return null; const values = new Array>(r.capacity(length)); @@ -6361,7 +7186,7 @@ function read$27(r: NinoReader): NullableSlot[] | null { return values; } -function readInto$27(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null { +function readInto$46(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -6370,7 +7195,7 @@ function readInto$27(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null): void { +function write$45(w: NinoWriter, values: readonly NullableSlot[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -6384,7 +7209,7 @@ function write$26(w: NinoWriter, values: readonly NullableSlot[] | null) } } -function write$27(w: NinoWriter, values: readonly NullableSlot[] | null): void { +function write$46(w: NinoWriter, values: readonly NullableSlot[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -6398,7 +7223,7 @@ function write$27(w: NinoWriter, values: readonly NullableSlot[] | null) } } -function read$28(r: NinoReader): NullableSlot[] | null { +function read$47(r: NinoReader): NullableSlot[] | null { const length = r.length(); if (length < 0) return null; const values = new Array>(r.capacity(length)); @@ -6406,7 +7231,7 @@ function read$28(r: NinoReader): NullableSlot[] | null { return values; } -function readInto$28(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null { +function readInto$47(r: NinoReader, cur: NullableSlot[]): NullableSlot[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -6415,7 +7240,7 @@ function readInto$28(r: NinoReader, cur: NullableSlot[]): NullableSlot

| null { +function read$48(r: NinoReader): Map | null { const length = r.length(); if (length < 0) return null; const map = new Map(); @@ -6428,7 +7253,7 @@ function read$29(r: NinoReader): Map | null { return map; } -function readInto$29(r: NinoReader, cur: Map): Map | null { +function readInto$48(r: NinoReader, cur: Map): Map | null { const length = r.length(); if (length < 0) return null; const map = cur; @@ -6442,7 +7267,7 @@ function readInto$29(r: NinoReader, cur: Map): Map[] | null): void { +function write$47(w: NinoWriter, values: readonly NullableSlot[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -6456,7 +7281,7 @@ function write$28(w: NinoWriter, values: readonly NullableSlot[] | null) } } -function write$29(w: NinoWriter, map: ReadonlyMap | null): void { +function write$48(w: NinoWriter, map: ReadonlyMap | null): void { if (map === null || map === undefined) { w.i32(-1); return; @@ -6469,7 +7294,7 @@ function write$29(w: NinoWriter, map: ReadonlyMap | null) } } -function read$30(r: NinoReader): Padded[] | null { +function read$49(r: NinoReader): Padded[] | null { const length = r.length(); if (length < 0) return null; const values = new Array(r.capacity(length)); @@ -6477,7 +7302,7 @@ function read$30(r: NinoReader): Padded[] | null { return values; } -function readInto$30(r: NinoReader, cur: Padded[]): Padded[] | null { +function readInto$49(r: NinoReader, cur: Padded[]): Padded[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -6486,7 +7311,7 @@ function readInto$30(r: NinoReader, cur: Padded[]): Padded[] | null { return values; } -function write$30(w: NinoWriter, values: readonly Padded[] | null): void { +function write$49(w: NinoWriter, values: readonly Padded[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -6500,36 +7325,7 @@ function write$30(w: NinoWriter, values: readonly Padded[] | null): void { } } -function read$31(r: NinoReader): (Point | null)[] | null { - const length = r.length(); - if (length < 0) return null; - const values = new Array(r.capacity(length)); - for (let i = 0; i < length; i++) values[i] = (r.present() ? readPoint(r) : null); - return values; -} - -function readInto$31(r: NinoReader, cur: (Point | null)[]): (Point | null)[] | null { - const length = r.length(); - if (length < 0) return null; - const values = cur; - for (let i = 0; i < length; i++) values[i] = (r.present() ? (values[i] == null ? readPoint(r) : readPoint(r, values[i]!)) : null); - if (values.length !== length) values.length = length; - return values; -} - -function write$31(w: NinoWriter, values: readonly (Point | null)[] | null): void { - if (values === null || values === undefined) { - w.i32(-1); - return; - } - w.i32(values.length); - for (let i = 0; i < values.length; i++) { - const value = values[i]; - if (value === null || value === undefined) w.u8(0); else { w.u8(1); writePoint(w, value); } - } -} - -function read$32(r: NinoReader): RawOptional[] | null { +function read$50(r: NinoReader): RawOptional[] | null { const length = r.length(); if (length < 0) return null; const values = new Array(r.capacity(length)); @@ -6537,7 +7333,7 @@ function read$32(r: NinoReader): RawOptional[] | null { return values; } -function readInto$32(r: NinoReader, cur: RawOptional[]): RawOptional[] | null { +function readInto$50(r: NinoReader, cur: RawOptional[]): RawOptional[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -6546,7 +7342,7 @@ function readInto$32(r: NinoReader, cur: RawOptional[]): RawOptional[] | null { return values; } -function write$32(w: NinoWriter, values: readonly RawOptional[] | null): void { +function write$50(w: NinoWriter, values: readonly RawOptional[] | null): void { if (values === null || values === undefined) { w.i32(-1); return; @@ -6560,108 +7356,7 @@ function write$32(w: NinoWriter, values: readonly RawOptional[] | null): void { } } -function read$33(r: NinoReader): (string | null)[] | null { - const length = r.length(); - if (length < 0) return null; - const values = new Array(r.capacity(length)); - for (let i = 0; i < length; i++) values[i] = r.string(); - return values; -} - -function readInto$33(r: NinoReader, cur: (string | null)[]): (string | null)[] | null { - const length = r.length(); - if (length < 0) return null; - const values = cur; - for (let i = 0; i < length; i++) values[i] = r.string(); - if (values.length !== length) values.length = length; - return values; -} - -function write$33(w: NinoWriter, values: readonly (string | null)[] | null): void { - if (values === null || values === undefined) { - w.i32(-1); - return; - } - w.i32(values.length); - for (let i = 0; i < values.length; i++) { - const value = values[i]; - w.string(value); - } -} - -function read$34(r: NinoReader): Map | null { - const length = r.length(); - if (length < 0) return null; - const map = new Map(); - const guard = r.keyGuard(length); - for (let i = 0; i < length; i++) { - const key = r.string(); - map.set(guard === null ? key : guard.string(key), r.i32()); - } - if (map.size !== length) throw r.duplicateKey(); - return map; -} - -function readInto$34(r: NinoReader, cur: Map): Map | null { - const length = r.length(); - if (length < 0) return null; - const map = cur; - map.clear(); - const guard = r.keyGuard(length); - for (let i = 0; i < length; i++) { - const key = r.string(); - map.set(guard === null ? key : guard.string(key), r.i32()); - } - if (map.size !== length) throw r.duplicateKey(); - return map; -} - -function write$34(w: NinoWriter, map: ReadonlyMap | null): void { - if (map === null || map === undefined) { - w.i32(-1); - return; - } - w.i32(map.size); - for (let keys = map.keys(), values = map.values(), i = map.size; i > 0; i--) { - const key = keys.next().value as string | null, value = values.next().value as number; - w.string(key); - w.i32(value); - } -} - -function read$35(r: NinoReader): Set | null { - const length = r.length(); - if (length < 0) return null; - const values = new Set(); - const guard = r.keyGuard(length); - for (let i = 0; i < length; i++) values.add(guard === null ? r.string() : guard.string(r.string())); - if (values.size !== length) throw r.duplicateKey(); - return values; -} - -function readInto$35(r: NinoReader, cur: Set): Set | null { - const length = r.length(); - if (length < 0) return null; - const values = cur; - values.clear(); - const guard = r.keyGuard(length); - for (let i = 0; i < length; i++) values.add(guard === null ? r.string() : guard.string(r.string())); - if (values.size !== length) throw r.duplicateKey(); - return values; -} - -function write$35(w: NinoWriter, values: ReadonlySet | null): void { - if (values === null || values === undefined) { - w.i32(-1); - return; - } - w.i32(values.size); - for (const value of values) { - w.string(value); - } -} - -function read$36(r: NinoReader): Vec2[] | null { +function read$51(r: NinoReader): Vec2[] | null { const length = r.length(); if (length < 0) return null; const values = new Array(r.capacity(length)); @@ -6669,7 +7364,7 @@ function read$36(r: NinoReader): Vec2[] | null { return values; } -function readInto$36(r: NinoReader, cur: Vec2[]): Vec2[] | null { +function readInto$51(r: NinoReader, cur: Vec2[]): Vec2[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -6678,7 +7373,7 @@ function readInto$36(r: NinoReader, cur: Vec2[]): Vec2[] | null { return values; } -function read$37(r: NinoReader): Mixed[] | null { +function read$52(r: NinoReader): Mixed[] | null { const length = r.length(); if (length < 0) return null; const values = new Array(r.capacity(length)); @@ -6686,7 +7381,7 @@ function read$37(r: NinoReader): Mixed[] | null { return values; } -function readInto$37(r: NinoReader, cur: Mixed[]): Mixed[] | null { +function readInto$52(r: NinoReader, cur: Mixed[]): Mixed[] | null { const length = r.length(); if (length < 0) return null; const values = cur; @@ -6695,7 +7390,7 @@ function readInto$37(r: NinoReader, cur: Mixed[]): Mixed[] | null { return values; } -function read$38(r: NinoReader): Label[] | null { +function read$53(r: NinoReader): Label[] | null { const length = r.length(); if (length < 0) return null; const values = new Array