diff --git a/.claude/skills/audit-layout/SKILL.md b/.claude/skills/audit-layout/SKILL.md index c4d68e34f..f9ef6f6b5 100644 --- a/.claude/skills/audit-layout/SKILL.md +++ b/.claude/skills/audit-layout/SKILL.md @@ -109,6 +109,12 @@ its own `AGENTS.md` maps every file in it. - In the Unity project an asmdef, not the folder name, decides where an assembly compiles: `Assets/Test/Editor/Model` and `CrossRef` build for players too and sit under `Editor/` because only the editor tests use them (their namespaces say `Test.Editor`); move them only together with their namespaces. +- **Preserve the original module and item order when splitting Rust files whose machine code must stay identical.** + Moving impls to child modules can change rustc's codegen-unit partitioning and alter even untouched hot functions + (`DateOnly::new` in #248). Use ordered `include!` fragments when ordinary modules change the instructions. + Compare the release binaries from the same checkout path and flags with the same hot-path implementations on both + sides (`optimize-runtimes`). Check the fragments with `rustfmt --check` as well as `cargo fmt --all --check`, + which does not follow `include!`. ## Adding files that nothing builds diff --git a/.claude/skills/audit-runtimes/SKILL.md b/.claude/skills/audit-runtimes/SKILL.md index 1542f70a0..5485ad7e6 100644 --- a/.claude/skills/audit-runtimes/SKILL.md +++ b/.claude/skills/audit-runtimes/SKILL.md @@ -156,8 +156,7 @@ nothing. the bytes on its own. Read UTF-16 text from the wire with `MemoryMarshal.Cast`, never `Encoding.Unicode.GetString`, which replaces lone surrogates with U+FFFD (spec §4.1 keeps them; `string-lone-surrogates` caught it). Raise the depth of `JsonDocument` (64) and `Utf8JsonWriter` (1000) for deep corpus cases, and run deep - reads on a thread with a large stack. "Struct holds itself" is computed in four places (`CodegenModel.HoldsItself`, - used by inspect, and each target's own, which filters by the types it supports): merge them when a target changes. + reads on a thread with a large stack. - A `[NinoType]` added to `runtimes/csharp/tests/Nino.Codegen.Tests` (Shapes.cs, InspectTypes.cs) is in nino-gen's generated Shapes files unless every target leaves it out, and a keyed or version-tolerant one is in `LayoutsCommandTests`' baseline list: update that list with it. diff --git a/.claude/skills/benchmark/SKILL.md b/.claude/skills/benchmark/SKILL.md index 1073deef7..5a2bb1454 100644 --- a/.claude/skills/benchmark/SKILL.md +++ b/.claude/skills/benchmark/SKILL.md @@ -79,6 +79,9 @@ runs in both, so its two results show how much the machine moved. Heavy runs go - **Reach the commits** with `git merge -s ours --no-edit ` (history only: the test branch keeps main's code, so its CI runs main's code; merging an experiment's code ran CI on it, and a Go test that overflowed `int` on 386 and a Windows stack test mailed the owner a failure per push). + Check `git merge-base --is-ancestor HEAD` for both refs after the history merges. The #353 benchmark + baseline and candidate were built on independent branches, so merging only the candidate left the baseline + missing from every runner checkout (44333395182). - **Time the Nino.Core build you mean.** BenchmarkDotNet's runner project (`Nino.Benchmark-`) gets Nino.Core only through Nino.Benchmark's references, so a referenced package built for fewer frameworks than Nino.Core brings an older build into it: until f01a8d3c Nino.Immutable (net8.0 only) made every runner process load Nino.Core's @@ -133,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/SKILL.md b/.claude/skills/optimize-runtimes/SKILL.md index 3f66bd7d6..0b727bf0e 100644 --- a/.claude/skills/optimize-runtimes/SKILL.md +++ b/.claude/skills/optimize-runtimes/SKILL.md @@ -10,7 +10,8 @@ metadata: The techniques that made the Go, Rust and TypeScript runtimes and nino-gen's generated code faster or slower. The .NET and Unity techniques, reading .NET machine code and the prefetch design of every runtime are `optimize` (prefetch: its references/prefetch.md). How to measure on runners is `benchmark` (runtime A/B), where the next win is -`audit-perf`, each runtime's rules are `runtimes/*/AGENTS.md` and `audit-runtimes`. +`audit-perf`, each runtime's rules are `runtimes/*/AGENTS.md` and `audit-runtimes`. For Rust source splits that must +keep machine code identical, see [audit-layout](../audit-layout/SKILL.md#splitting-long-files). ## The techniques, by topic diff --git a/.claude/skills/optimize-runtimes/references/blocks.md b/.claude/skills/optimize-runtimes/references/blocks.md index cb0528c00..6ac88ec9e 100644 --- a/.claude/skills/optimize-runtimes/references/blocks.md +++ b/.claude/skills/optimize-runtimes/references/blocks.md @@ -14,6 +14,12 @@ value check in a runtime or a template. ## Fixed-size blocks in Rust +- Write fixed-size Rust sets through `extend_fixed_iter`, reserving the count and payload together in iteration order. + In runtime A/B 44329792122, the median write time for 1,000 `i32` hash-set elements fell 33–43 % across EPYC + 7763, 9V74, 9V45 and Xeon 8573C, and 58 % on Neoverse-N2. The GUID hash-set case fell 26–44 % on the same + x64 CPUs and 58 % on Neoverse-N2. The ordered `i32` case fell 37 % on Neoverse-N2 and ranged from on par + to 20 % lower on x64. The comparison used the same block benchmark harness on both sides. + - In Rust, give every fixed-size shape `FIXED_SIZE` with `decode_fixed` / `encode_fixed` and let `read_fixed` / `extend_fixed` run it over `chunks_exact`; write no shuffle kernel. LLVM already turns a block whose wire bytes equal its memory ((i32, i32), a raw struct, a derived plain `{i32, f32}`) into vector copies (`vmovups ymm` on @@ -41,6 +47,21 @@ value check in a runtime or a template. ## Checking blocks in Go +- Reserve one checked block for fixed-width Go containers. Use constant wire offsets for padded primitive pairs + and copy compatible primitive grids as blocks. In runtime A/B + [44339615693](https://github.com/JasonXuDeveloper/Nino/actions/runs/44339615693), padded-pair read times fell + 66–75 % on the measured x64 CPUs and 72 % on Neoverse-N2. Byte-grid writes fell 92–96 % on both architectures. + Fixed DateTimeOffset sequence writes fell 52–59 % on x64 and 47 % on Neoverse-N2. +- Encode fixed map entries through their addresses. In the original fixed-stride loop the x64 GUID entry value + crossed two stack temporaries. The address loop reduced ten `MOVUPS` per entry to two, with the stride guard + intact. In [44347813411](https://github.com/JasonXuDeveloper/Nino/actions/runs/44347813411) the revised GUID map + write took 82–85 % less time on x64 and 81 % less on Neoverse-N2. The revised map read took 52–54 % less on + x64 and 45 % less on Neoverse-N2. +- Keep generated raw fallback loops on direct codecs after the raw-memory attempt. In the + [prepared-key follow-up](https://github.com/JasonXuDeveloper/Nino/actions/runs/44451141322) both native + listings call `repeatedBits` directly for padded primitive pairs. The eight-pair read was on par on + EPYC and Neoverse-N2. Its Xeon 6973P-C sample took 9 % less time, with no same-CPU control. + - Check a block of range-limited 8- or 16-byte values four a step with one compare each (`w[0].Valid() && ... && w[3].Valid()`, then the failing step value by value), each `Valid` a single compare (a signed range from 0 as unsigned; a Decimal's flags without the sign, rotated by 16 bits, `<= 28`). Writing 1000 values (runtime A/B runs @@ -63,3 +84,50 @@ value check in a runtime or a template. read and 92-96 % to write; narrowing Latin-1 four units a word 40-64 % faster to write. Widening Latin-1 four bytes a word on read (`load32`, `widen`, `store64` into a fresh slice) was slower than the byte loop: +86 % on EPYC 7763, +56 % on Xeon 6973P, +10 % on Neoverse-N2 (run 40822228516); the byte loop stays. + +## Byte block copies + +- Confirm copy microbenchmarks in the codec that allocates or reuses the real buffer. Runtime A/B + [44339615693](https://github.com/JasonXuDeveloper/Nino/actions/runs/44339615693) probed disjoint copies with + rotated buffers, including a destination offset of four bytes. Go's candidate lowered the Neoverse-N2 time + by 10–33 % at 2–4 KiB but raised it by 21 % at 256 KiB with that offset. On the x64 runners it lowered the + hot 1 MiB time by 20–44 %, while the 2–4 KiB results varied by CPU and alignment. + Keep Go's built-in copy in `Reader.ByteArray`. The Arm64 candidate for fresh 2–4 KiB reads took 5–9 % + longer with a hot input and 24–26 % longer with a 64 MiB source rotation on Neoverse-N2 + ([44347813411](https://github.com/JasonXuDeveloper/Nino/actions/runs/44347813411), `DeserializeExact`). + The 128-byte fallback control also took 30 % longer. + The [1 MiB end-to-end x64 follow-up](https://github.com/JasonXuDeveloper/Nino/actions/runs/44451141322) + ran the AVX2 candidate through the same fresh `Reader.ByteArray` read. With a 64 MiB source rotation, + median time rose 17 % on Xeon 6975P-C, 39 % on EPYC 9V45 and 122 % on EPYC 7763. The hot 7763 row + rose 21 %. The same-revision 9V45 rotation moved 1.5 %. The other two x64 CPU models did not occur + in the floor jobs. The standard path compiles the allocation and copy to `runtime.makeslicecopy`. + Keep it for megabyte reads as well. +- Compare Rust's standard copy under the default loader and with + `GLIBC_TUNABLES=glibc.cpu.x86_rep_movsb_threshold=2112`. In the same run, forcing the historical lower + threshold made the unaligned 2,113-byte standard copy 7.1× its default time on EPYC 7763 and 5.8× on 9V74. + AVX2 took about 13–15 % of that tuned time. With the default loader the custom vectors had mixed x64 results + and the unaligned NEON copies cost 15–25 % more through 64 KiB. The lower threshold reproduces the AMD + `rep movsb` transition. The current loader still has its own upper stop threshold, so the 1 MiB row does + not reproduce every historical glibc configuration. + In real Rust codecs ([44347813411](https://github.com/JasonXuDeveloper/Nino/actions/runs/44347813411)), + the scoped AVX2 candidate lowered reused writes by 14–33 % at 2,113 and 4,096 bytes on EPYC with the + forced threshold. The 2,113-byte writes also fell 9–10 % under the default loader on EPYC 7763 and 9V74. + Ordinary read measurements shifted by about 25–30 % even with the same revision on both sides. +- Keep Rust's standard counted byte copy. A write-only AVX2 candidate gated to AMD family 19h + ([44443778134](https://github.com/JasonXuDeveloper/Nino/actions/runs/44443778134)) lowered reused + 2,113-byte writes by 31 % on EPYC 7763 and 19 % on 9V74 with the forced historical glibc threshold. + At 4,096 bytes the apparent gains were 30 % and 26 %, while the same-revision floors themselves + moved 27 % and 17 % lower by median. With the default loader, the 2,113-byte case improved 13 % on + 9V74 and was on par on 7763. The 4,096-byte 9V45 control took 19 % longer, with no matching same-CPU + floor. The 2,113-byte legacy gain is repeatable. Evidence for the full range and fallback remains + inconclusive. A separate [mixed workload](https://github.com/JasonXuDeveloper/Nino/actions/runs/44447481096) + varied source alignment and payload lengths from 2,113 to 4,096 bytes. The measured AMD writers + stayed on par under the default loader. Under the forced threshold, EPYC 9V74 fresh and reused times + fell 9 % and 18 %, respectively, with overlapping same-revision controls that fell 12 % for both. + Keep the standard writer. Do not infer the effective threshold from the glibc version alone. The + [glibc 2.39 stable branch](https://sourceware.org/pipermail/glibc-cvs/2024q2/084781.html) backported the + AMD change, as did [RHEL 9.5](https://docs.redhat.com/en-us/documentation/red_hat_enterprise_linux/9/pdf/9.5_release_notes/Red_Hat_Enterprise_Linux-9-9.5_Release_Notes-en-US.pdf). +- Keep `TypedArray.set` for ordinary TypeScript buffers. In 44339615693, copying through Wasm memory with both + staging copies took 82–339 % more time than `TypedArray.set` across the default and historical threshold + runs. For views already backed by Wasm memory, `memory.copy` varied from 8 % lower to 17 % higher by size and + CPU. These views avoid the staging cost and are timed separately from ordinary arrays. diff --git a/.claude/skills/optimize-runtimes/references/dispatch.md b/.claude/skills/optimize-runtimes/references/dispatch.md index 59cd3b636..c33dcf415 100644 --- a/.claude/skills/optimize-runtimes/references/dispatch.md +++ b/.claude/skills/optimize-runtimes/references/dispatch.md @@ -35,6 +35,21 @@ call, a helper that takes a function, or a `read_into` / `deserializeInto` path. the template's had none): in the release build of `tests/generated` the standalone raw `read`/`write` symbols are gone and their callers inline them (no runner number yet: the benches' `Point` uses the macros since). +- Generate a direct fixed-stride fallback when `TryReadRaw` or `TryWriteRaw` declines a Go layout. Apple Arm64 + disassembly of the padded Gappy and Marked fixtures had direct decode and encode calls on the fallback. + Keep the exported callback helpers available for callers that supply their own codecs. +- Keep structural composite-key discovery outside Go's scalar and string duplicate loops. When the initial #353 + implementation sent all keys through the shared cache and added a byte-size test to the string loop, + [44339615693](https://github.com/JasonXuDeveloper/Nino/actions/runs/44339615693) measured the eight-int control + 15 % higher on Neoverse-N2. Caching only the composite field walk and restoring the string probe brought both + controls within 2 % by median on that CPU ([44347813411](https://github.com/JasonXuDeveloper/Nino/actions/runs/44347813411)). + The bytewise path still uses the reader's shared seeded table and bounded probing. Prepare generated duplicate + checks in package initializers, shared by key type across set and dictionary helpers; primitive-entry readers + know the key width and distinguish integer `K(1)/K(2)` from floating point at compile time. + In [44451141322](https://github.com/JasonXuDeveloper/Nino/actions/runs/44451141322), eight-element Guid sets and + maps took 6–10 % and 5–7 % less time on sampled x64 CPUs and stayed on par on Neoverse-N2. The 1,024-entry Guid + map, eight-integer and 1,024-string controls were within 2 % by CPU median. + ## Reuse branches - Keep reuse branches off the read path of a new value: share the body, not the dispatch. Reading into an existing @@ -63,3 +78,16 @@ call, a helper that takes a function, or a `read_into` / `deserializeInto` path. and the tagged union is the faster form (12.1 µs serialize, 7.5 deserialize against 23.1 and 13.0 on EPYC 9V45, with fewer and smaller values); Go deserializes in about three times its serialize time (35.7 against 11.9 µs, EPYC 9V74) with an allocation per non-int case (808 for UnionArray). The gaps are #387. +- Construct the Rust union variant directly in its read, and record a deferred trail only for cases that can open + deferred bodies. Against 44d49866 on runtime A/B 44333395182, `UnionArray` / `TaggedUnionArray` deserialize + medians fell 38 % / 51 % on EPYC 9V74, 43 % / 55 % on Xeon 6975P-C and 33 % / 44 % on Neoverse-N2. + Both serialize controls stayed on par. Count struct depth around each non-null case, including a failed read. +- Reserve the case ID and fixed payload together in TypeScript union writers. Use the same offset writer and padding + policy as other fixed shapes. On runtime A/B 44333395182, Node's `UnionArray` / `TaggedUnionArray` serialize + medians fell 17 % / 22 % on Neoverse-N2. The plain union wrote its 1,000 values in 37.1 µs against JSON's 38.8 µs + on that CPU, within 5 %. The sampled x64 medians fell 10–14 % / 17–23 %. +- Treat the dynamic type of a generated Go union case as part of its API: callers assert the concrete value wrapper. + `go build -gcflags=-m ./model` in the Go bench module reports heap escape for `UnionValueInt32`, + `UnionValueInt64`, `UnionValueUnionPoint`, `UnionTaggedInt32` and `UnionTaggedInt16`. Go's small-integer + conversion table can still supply some of those boxes. The string wrapper has a single pointer field and fits + directly in an interface. Returning pointers into a typed slice would change what callers' type assertions accept. 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/.claude/skills/platforms/references/emulation.md b/.claude/skills/platforms/references/emulation.md index a7c4943c7..eeeeaa5e8 100644 --- a/.claude/skills/platforms/references/emulation.md +++ b/.claude/skills/platforms/references/emulation.md @@ -50,7 +50,14 @@ crashing. Read it before running anything under qemu or taking a listing for Arm garbage collector's lock-free lists (`runtime.(*lfstack).pop` SIGSEGV at address 0, during any test) in 2 to 5 of 8 runs with qemu 8.2 and the runners' qemu, and main's code before the run that showed it (f618b973) crashed too (1 of 10, more allocation only made it likelier); Go 1.24 crashed in 0 of 8, `GOMAXPROCS=1` in 0 of 18, `GOARM=6` - did not help (4 of 8). runtimes.yml sets it on that step (r101). + did not help (4 of 8). runtimes.yml sets it on that step (r101). If qemu-arm still faults in + `runtime.(*lfstack).pop`, retry with `GODEBUG=asyncpreemptoff=1` as well. With Go 1.26.11 and QEMU + 10.0.13, the first #353 run faulted during `TestStringEncodings`; all packages passed with both flags. + Use QEMU user-mode 10.0.13 or later for local Go 386 tests on Arm64 Linux. Go 1.26.11's same static + test binary reported `bad g in signal handler` or `morestack on gsignal` on QEMU 7.2.22. On Debian + trixie's QEMU 10.0.13 it passed three runs and `GOARCH=386 go test -exec qemu-i386 ./...` passed with + asynchronous preemption enabled (#353). Where QEMU 7.2 is required, `GODEBUG=asyncpreemptoff=1` and + `GOMAXPROCS=1` allowed the 386, Arm32 and s390x suites to pass. - To run tests under qemu-aarch64, pass `-cpu neoverse-n1` (listings can keep the default): qemu 8.2's default CPU (`max`) has LRCPC2, whose `ldapur`/`stlur` (what the optimizing JIT emits for `Volatile.Read`/`Write` of a field) it emulates wrong. With or without Nino's code, runs crashed (`ToImmutableDictionary`), or a static field written by 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/.github/scripts/bump_version.py b/.github/scripts/bump_version.py index 28a6fb4a8..8d999b15f 100644 --- a/.github/scripts/bump_version.py +++ b/.github/scripts/bump_version.py @@ -4,7 +4,8 @@ usage: bump_version.py NuGet (runtimes/csharp/Directory.Build.props), the Unity package (package.json, its OpenUPM version), the Rust crates -(nino-serialization and nino-serialization-derive, which the first pins exactly) and the npm package +(nino-serialization and nino-serialization-derive, which the first pins exactly, in both Cargo.lock files: the +crates' and the fuzz workspace's) and the npm package nino-serialization all take the release's version; the Go module takes it as the tag runtimes/go/v, which the module path's major version (runtimes/go/v4) must match. The install command in each runtime's README (shipped in the npm package and the crate) names the version too. Each file must change as expected, or this fails. @@ -54,6 +55,8 @@ def main(): rf'\g<1>"={version}"') sub("runtimes/rust/Cargo.lock", r'(name = "nino-serialization(?:-derive)?"\nversion = )"[^"]*"', rf'\g<1>"{version}"', count=0) + # The fuzz workspace (runtimes/rust/fuzz) has its own lockfile, with nino-serialization as a path dependency. + sub("runtimes/rust/fuzz/Cargo.lock", r'(name = "nino-serialization"\nversion = )"[^"]*"', rf'\g<1>"{version}"') bump_json("runtimes/typescript/package.json", version) bump_json("runtimes/typescript/package-lock.json", version, lock=True) diff --git a/.github/workflows/runtimes.yml b/.github/workflows/runtimes.yml index 398a07003..00894bf31 100644 --- a/.github/workflows/runtimes.yml +++ b/.github/workflows/runtimes.yml @@ -275,7 +275,10 @@ jobs: save-if: ${{ github.ref == 'refs/heads/main' }} - name: Format - run: cargo fmt --all --check + run: | + cargo fmt --all --check + # rustfmt does not follow the ordered include! fragments. + rustfmt --edition 2021 --check src/impls/*.rs - name: Clippy if: ${{ !cancelled() }} diff --git a/.gitignore b/.gitignore index 21e85de3d..fa3d8247b 100644 --- a/.gitignore +++ b/.gitignore @@ -16,6 +16,16 @@ TestResults/ runtimes/csharp/tests/Nino.UnitTests/*.rsp **/BenchmarkDotNet.Artifacts +# Local output from before the .NET projects moved under runtimes/csharp. +/benchmarks/results/ +/benchmarks/members/results/ +/src/Nino.Unity/[Ll]ibrary/ +/src/Nino.Unity/[Ll]ogs/ +/src/Nino.Unity/[Uu]ser[Ss]ettings/ +/src/Nino.Unity/*.csproj +/src/Nino.Unity/*.sln +/tests/Nino.Fuzz/findings/ + # Python bytecode (the scripts under runtimes/csharp/benchmarks/ and .github/scripts/) __pycache__/ diff --git a/AGENTS.md b/AGENTS.md index c0eed21ed..9c2c7e320 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/Directory.Packages.props b/runtimes/csharp/Directory.Packages.props index 71eebb290..9f4037841 100644 --- a/runtimes/csharp/Directory.Packages.props +++ b/runtimes/csharp/Directory.Packages.props @@ -24,7 +24,7 @@ 5.12.0 - + @@ -36,11 +36,11 @@ - + - + diff --git a/runtimes/csharp/benchmarks/Nino.GeneratorBenchmark/Nino.GeneratorBenchmark.csproj b/runtimes/csharp/benchmarks/Nino.GeneratorBenchmark/Nino.GeneratorBenchmark.csproj index 8c9247d69..a2735902a 100644 --- a/runtimes/csharp/benchmarks/Nino.GeneratorBenchmark/Nino.GeneratorBenchmark.csproj +++ b/runtimes/csharp/benchmarks/Nino.GeneratorBenchmark/Nino.GeneratorBenchmark.csproj @@ -7,6 +7,7 @@ disable + 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/Model/CodegenModel.cs b/runtimes/csharp/src/Nino.Codegen/Model/CodegenModel.cs index dafe69bbd..208672dc2 100644 --- a/runtimes/csharp/src/Nino.Codegen/Model/CodegenModel.cs +++ b/runtimes/csharp/src/Nino.Codegen/Model/CodegenModel.cs @@ -218,7 +218,7 @@ internal static IEnumerable OwnValues(TypeModel type) /// object): .NET counts the nesting of its bodies toward the depth limit (Reader.EnterStruct, /// wire-format spec §9.9), as nothing else bounds it. /// - internal bool HoldsItself(TypeModel type) + internal bool HoldsItself(TypeModel type, Func? supports = null) { var seen = new HashSet(); var pending = new Stack(); @@ -227,6 +227,8 @@ internal bool HoldsItself(TypeModel type) { foreach (var reached in OwnValues(pending.Pop()).SelectMany(v => v.Walk()).SelectMany(StructsIn)) { + if (supports != null && !supports(reached)) + continue; if (reached == type) return true; if (seen.Add(reached)) @@ -240,12 +242,12 @@ internal bool HoldsItself(TypeModel type) /// The non-raw struct bodies a value can open directly (behind a type id, any of those assignable). private IEnumerable StructsIn(ValueModel value) { - var candidates = value.Kind switch + IEnumerable candidates = value.Kind switch { ValueKind.Type when value.Type!.Header == HeaderKind.TypeId => value.Type.Assignable, - ValueKind.Type or ValueKind.Generic => new List { value.Type! }, - ValueKind.Object => Types, - _ => new List(), + ValueKind.Type or ValueKind.Generic => new[] { value.Type! }, + ValueKind.Object => Types.Where(t => t.TypeId != 0 && t.IsConcrete), + _ => Array.Empty(), }; return candidates.Where(t => t.IsValueType && !t.Raw); } diff --git a/runtimes/csharp/src/Nino.Codegen/Targets/CodegenTarget.cs b/runtimes/csharp/src/Nino.Codegen/Targets/CodegenTarget.cs index 010b5c5e2..866cc54d4 100644 --- a/runtimes/csharp/src/Nino.Codegen/Targets/CodegenTarget.cs +++ b/runtimes/csharp/src/Nino.Codegen/Targets/CodegenTarget.cs @@ -25,6 +25,8 @@ public abstract class CodegenTarget protected CodegenTarget(CodegenModel model) => _model = model; + internal bool HoldsItself(TypeModel type) => _model.HoldsItself(type, _supported.Contains); + /// /// The number in the names of the functions shared by every value of one shape (by its identity), the same for /// all of them (reading, writing...): the next one when the shape has none yet. diff --git a/runtimes/csharp/src/Nino.Codegen/Targets/Go/GoShape.cs b/runtimes/csharp/src/Nino.Codegen/Targets/Go/GoShape.cs index fd12da2ae..6c9a8ba9a 100644 --- a/runtimes/csharp/src/Nino.Codegen/Targets/Go/GoShape.cs +++ b/runtimes/csharp/src/Nino.Codegen/Targets/Go/GoShape.cs @@ -47,6 +47,18 @@ public sealed class GoShape /// Whether arrays of it are one block (nino.ReadPrimitives). public bool Block { get; internal set; } + /// Whether sequences of this value use nino.ReadBlock and nino.WriteBlock. + public bool BlockValue { get; internal set; } + + /// Whether this value needs range validation when written outside raw memory. + public bool CheckedWrite { get; internal set; } + + /// Whether the fixed encoder omits padding, unused slots or false booleans. + public bool NeedsZero => Kind is "rawstruct" or "emptystruct" or "rawnullable" or "rawtuple" || Primitive == "Bool"; + + /// Whether the key of each pair is checked for repeats. + public bool UniqueKeys { get; internal set; } + /// A raw struct that can be copied as memory, its arrays as one block; else null. public GoRawBlock? RawBlock { get; internal set; } @@ -92,7 +104,7 @@ public sealed class GoShape /// fixed (raw values at their stride), /// unique (a set of comparable values), stringset, slice; a map's: block /// (primitive keys and values, pairs copied as one block where their memory is their bytes; repeated keys - /// fail), unique (repeated keys fail) or entries. + /// fail), fixed (both shapes have a stride), unique (repeated keys fail) or entries. /// public string? Mode { get; internal set; } @@ -141,7 +153,7 @@ private IEnumerable Parts() yield return Struct?.FullName ?? ""; yield return Type?.FullName ?? ""; yield return Named?.FullName ?? ""; - yield return (Mode ?? "") + (UniqueSlots ? "/unique" : ""); + yield return (Mode ?? "") + (UniqueSlots || UniqueKeys ? "/unique" : ""); yield return Pair ? "pair" : ""; yield return FlagOffset + "/" + ValueOffset + "/" + Rank + (Clean ? "/clean" : "") + (SlotElement ? "/slot" : ""); yield return string.Join("/", Offsets); diff --git a/runtimes/csharp/src/Nino.Codegen/Targets/Go/GoTarget.Shapes.cs b/runtimes/csharp/src/Nino.Codegen/Targets/Go/GoTarget.Shapes.cs index debdff259..ff6c696d8 100644 --- a/runtimes/csharp/src/Nino.Codegen/Targets/Go/GoTarget.Shapes.cs +++ b/runtimes/csharp/src/Nino.Codegen/Targets/Go/GoTarget.Shapes.cs @@ -51,8 +51,8 @@ internal GoShape Shape(ValueModel value, bool key) { Type = definition, Items = value.Arguments.Select(a => Shape(a, false)).ToList(), Slots = value.SlotArguments.Select(a => Shape(a, false)).ToList(), - MinSize = definition.IsValueType ? 0 : 1, }; + SetGenericMinimum(shape); if (_context != null && value.IsSelf(_context.Type)) { shape.Field = "c.self"; @@ -88,15 +88,15 @@ internal GoShape Shape(ValueModel value, bool key) bool set = value.Collection is CollectionKind.HashSet or CollectionKind.SortedSet || CodegenModel.Implements(value.Clr, "System.Collections.Generic.ISet`1") != null; string mode = - element.Kind == "prim" && element.Primitive == "U8" ? "bytes" - : set && Comparable(element) ? "unique" + set && Comparable(element) ? "unique" + : element.Kind == "prim" && element.Primitive == "U8" ? "bytes" : set && element.Kind is "string" or "utf8" ? "stringset" : element.Kind == "prim" && element.Primitive == "Bool" ? "bools" : element.Block ? "block" - : element.Kind == "prim" && BlockValues.Contains(element.Primitive!) ? "values" + : element.BlockValue ? "values" : element is { Kind: "rawnullable", Clean: true, Inner.Block: true } ? "ninonullables" : element is { Kind: "rawnullable", SlotElement: true, Inner.Block: true } ? "nullableslots" - : element.Kind is "rawstruct" or "rawnullable" or "rawtuple" ? "fixed" + : element.Size > 0 && element.Kind != "emptystruct" ? "fixed" : "slice"; return Open(value, new GoShape("seq") { @@ -106,11 +106,13 @@ internal GoShape Shape(ValueModel value, bool key) case ValueKind.Map: { var (k, v) = (Shape(value.Key!, true), Shape(value.Value!, false)); + bool unique = Comparable(k) || k.Kind is "keystring" or "keyutf8"; return Open(value, new GoShape("map") { - Key = k, Value = v, + Key = k, Value = v, UniqueKeys = unique, Mode = k.Block && v.Block ? "block" - : Comparable(k) || k.Kind is "keystring" or "keyutf8" ? "unique" : "entries", + : k.Size > 0 && v.Size > 0 ? "fixed" + : unique ? "unique" : "entries", MinSize = 4, }, false); } @@ -133,7 +135,7 @@ internal GoShape Shape(ValueModel value, bool key) case ValueKind.Version: return new GoShape("version") { MinSize = 4 }; case ValueKind.DateTimeOffset: - return new GoShape("datetimeoffset") { MinSize = 10 }; + return new GoShape("datetimeoffset") { MinSize = 10, Size = 10, CheckedWrite = true }; case ValueKind.Unsupported: throw new UnsupportedException(value.Problem!.Replace("{lang}", "Go")); default: @@ -243,7 +245,7 @@ private GoShape TypeShape(TypeModel type) return Raw(type.RawValue!); return type.Header switch { - HeaderKind.None => new GoShape("struct") { Type = type, MinSize = StructMinSize(type) }, + HeaderKind.None => new GoShape("struct") { Type = type, MinSize = MinimumBody(type, Array.Empty()).Bytes }, HeaderKind.Presence => new GoShape("class") { Type = type, MinSize = type.TrackReferences ? 4 : 1 }, _ => new GoShape("slot") { Type = type, MinSize = 4 }, }; @@ -251,20 +253,34 @@ private GoShape TypeShape(TypeModel type) private readonly HashSet _sizing = new(); - /// The fewest bytes a struct's body takes (a collection's elements are checked against it). - private int StructMinSize(TypeModel type) + /// The least size of a generic struct, in terms of the codecs it was given. + internal string GenericBodyMinimum(TypeModel type) => MinimumBody(type, type.TypeParameters + .Select((_, i) => new WireMinimum(0, "c.p" + i.ToString(CultureInfo.InvariantCulture) + ".MinSize")) + .ToArray()).Text; + + private void SetGenericMinimum(GoShape shape) + { + var minimum = MinimumType(shape.Type!, + shape.Items.Select(s => new WireMinimum(s.MinSize, s.MinExpression)).ToArray()); + shape.MinSize = minimum.Bytes; + shape.MinExpression = minimum.Expression == null ? null : minimum.Text; + } + + /// + /// The fewest bytes the body can take. Size its members without creating codecs. In particular, a collection + /// of a recursive generic struct takes a length, so this never needs the half-built codec of the struct. + /// + private WireMinimum MinimumBody(TypeModel type, IReadOnlyList arguments) { // A union: its case's type id at least. if (type.Format != BodyFormat.Positional || type.IsUnion) - return 4; - // A generic struct's members are sized by its arguments: none is counted on. - if (type.IsGenericDefinition) - return 0; + return new WireMinimum(4); if (!_sizing.Add(type)) - return 0; + return default; try { - return type.Members.Sum(m => Shape(m.Value, false).MinSize); + return CodegenModel.OwnValues(type).Aggregate(default(WireMinimum), + (size, v) => size.Add(MinimumValue(v, arguments))); } finally { @@ -272,6 +288,39 @@ private int StructMinSize(TypeModel type) } } + private WireMinimum MinimumType(TypeModel type, IReadOnlyList arguments) => type.Raw + ? new WireMinimum(Math.Max(type.RawValue!.Size, 1)) + : type.Header switch + { + HeaderKind.TypeId => new WireMinimum(4), + HeaderKind.Presence => new WireMinimum(type.TrackReferences ? 4 : 1), + _ => MinimumBody(type, arguments), + }; + + private WireMinimum MinimumValue(ValueModel value, IReadOnlyList arguments) => value.Kind switch + { + ValueKind.Parameter => arguments[value.Parameter], + ValueKind.Type => MinimumType(value.Type!, Array.Empty()), + ValueKind.Generic => MinimumType(value.Type!, value.Arguments.Select(v => MinimumValue(v, arguments)).ToArray()), + ValueKind.Tuple => value.Items.Aggregate(default(WireMinimum), (size, v) => size.Add(MinimumValue(v, arguments))), + ValueKind.String or ValueKind.Utf8 or ValueKind.Nullable => new WireMinimum(1), + ValueKind.Sequence or ValueKind.Map or ValueKind.Grid or ValueKind.Named or ValueKind.Object + or ValueKind.BigInteger or ValueKind.Version => new WireMinimum(4), + ValueKind.DateTimeOffset => new WireMinimum(10), + ValueKind.RawStruct => new WireMinimum(Math.Max(value.Struct!.Size, 1)), + _ => new WireMinimum(Math.Max(value.Size, 0)), + }; + + private readonly record struct WireMinimum(int Bytes, string? Expression = null) + { + private string Constant => Bytes.ToString(CultureInfo.InvariantCulture); + + internal string Text => Expression == null ? Constant : Bytes == 0 ? Expression : Constant + " + " + Expression; + + internal WireMinimum Add(WireMinimum size) => new(Bytes + size.Bytes, + Expression == null ? size.Expression : size.Expression == null ? Expression : Expression + " + " + size.Expression); + } + private static readonly Dictionary Primitives = new() { [PrimitiveKind.Bool] = ("Bool", false, true), @@ -316,6 +365,7 @@ private GoShape Raw(ValueModel value) return new GoShape("prim") { Primitive = p.Name, Size = value.Size, MinSize = value.Size, Block = p.Block, + BlockValue = BlockValues.Contains(p.Name), CheckedWrite = p.Validated && p.Name != "Bool", // Read in a run of fixed-size members: any bit pattern is valid. Runnable = !p.Validated, }; diff --git a/runtimes/csharp/src/Nino.Codegen/Targets/Go/GoTarget.cs b/runtimes/csharp/src/Nino.Codegen/Targets/Go/GoTarget.cs index b1ca290a5..6cebeb357 100644 --- a/runtimes/csharp/src/Nino.Codegen/Targets/Go/GoTarget.cs +++ b/runtimes/csharp/src/Nino.Codegen/Targets/Go/GoTarget.cs @@ -27,6 +27,7 @@ public sealed partial class GoTarget : CodegenTarget private readonly List _namedCollections = new(); private readonly Dictionary _helperByKey = new(StringComparer.Ordinal); private readonly List _helpers = new(); + private readonly Dictionary _keyChecks = new(StringComparer.Ordinal); private readonly HashSet _tuples = new(); private readonly Dictionary _generics = new(); private readonly Dictionary _closedByKey = new(StringComparer.Ordinal); @@ -110,6 +111,9 @@ public string Render(string source) renderer.Set("generic_slots", _slots.ToList()); renderer.Set("uses_elements", types.Any(t => t.Elements != null)); renderer.Function("helper", new Func(Helper)); + renderer.Function("key_check", new Func(KeyCheck)); + renderer.Function("key_check_types", new Func(() => + _keyChecks.OrderBy(p => p.Value).Select(p => p.Key).ToArray())); renderer.Function("helper_count", new Func(() => _helpers.Count)); renderer.Function("helper_at", new Func(i => _helpers[i])); renderer.Function("tag_name", new Func(TagName)); @@ -156,12 +160,16 @@ public string Render(string source) protected override void DeclareRaw(TypeModel type) => Raw(type.RawValue!); /// A closed generic type in a slot: the shapes of its arguments, its codec built in init. - private GoShape ClosedShape(ClosedTypeModel closed) => new("generic") + private GoShape ClosedShape(ClosedTypeModel closed) { - Type = closed.Definition, Items = closed.Value.Arguments.Select(a => Shape(a, false)).ToList(), - Slots = closed.Value.SlotArguments.Select(a => Shape(a, false)).ToList(), - MinSize = closed.IsValueType ? 0 : 1, - }; + var shape = new GoShape("generic") + { + Type = closed.Definition, Items = closed.Value.Arguments.Select(a => Shape(a, false)).ToList(), + Slots = closed.Value.SlotArguments.Select(a => Shape(a, false)).ToList(), + }; + SetGenericMinimum(shape); + return shape; + } /// The slots of closed generic types and the types and closed types each allows. internal List SlotAllowed(GoSlot slot) => slot.Model.Assignable.Where(_supported.Contains) @@ -186,6 +194,7 @@ protected override void Reset() _namedCollections.Clear(); _helperByKey.Clear(); _helpers.Clear(); + _keyChecks.Clear(); _tuples.Clear(); _generics.Clear(); _closedByKey.Clear(); @@ -308,22 +317,6 @@ internal bool IsInterfaceSlot(TypeModel type) !type.ClosedAssignable.Any(_closedSupported.Contains)); } - /// - /// The non-raw structs a value holds without a class body between: itself, or (behind a type id, in an - /// object or interface slot) any struct the slot allows. - /// - internal IEnumerable StructsIn(ValueModel value) - { - var candidates = value.Kind switch - { - ValueKind.Type when value.Type!.Header == HeaderKind.TypeId => Allowed(value.Type), - ValueKind.Type => new List { value.Type! }, - ValueKind.Object => ObjectTypes().ToList(), - _ => new List(), - }; - return candidates.Where(t => t.IsValueType && !t.Raw && _supported.Contains(t)); - } - /// /// The cases of a union in Go. A case whose value is a generated struct or class that is not generic (its Go /// type X or *X) is that type, marked with the union's method: the value is not wrapped again, @@ -416,6 +409,16 @@ private static string GoString(string text) return sb.Append('"').ToString(); } + private string KeyCheck(string type) + { + if (!_keyChecks.TryGetValue(type, out var index)) + { + index = _keyChecks.Count; + _keyChecks.Add(type, index); + } + return "keyCheck" + index.ToString(CultureInfo.InvariantCulture); + } + // ---------------------------------------------------------------- helpers /// diff --git a/runtimes/csharp/src/Nino.Codegen/Targets/Go/GoTemplateTypes.cs b/runtimes/csharp/src/Nino.Codegen/Targets/Go/GoTemplateTypes.cs index 2d3556b31..06770896f 100644 --- a/runtimes/csharp/src/Nino.Codegen/Targets/Go/GoTemplateTypes.cs +++ b/runtimes/csharp/src/Nino.Codegen/Targets/Go/GoTemplateTypes.cs @@ -433,12 +433,10 @@ internal GoType(GoTarget target, TypeModel model) /// A struct whose nesting is counted: one that can hold itself through no class body, or a generic struct /// (whose .NET formatter counts every one). /// - public bool Counted => Model.IsValueType && (Model.IsGenericDefinition || HoldsItself()); + public bool Counted => Model.IsValueType && (Model.IsGenericDefinition || _target.HoldsItself(Model)); /// The fewest bytes of a generic struct's body: its members', its arguments' as its codec has them. - public string MinBody => Model.Format != BodyFormat.Positional ? "4" - : Members.Count == 0 ? "0" - : string.Join(" + ", Members.Select(m => m.Shape.Min)); + public string MinBody => _target.GenericBodyMinimum(Model); public List Members => _members ??= BuildMembers(); @@ -552,25 +550,5 @@ public List Runs public string RuntimeName => Model.RuntimeName; - private bool HoldsItself() - { - var seen = new HashSet(); - var pending = new Stack(); - pending.Push(Model); - while (pending.Count != 0) - { - var next = pending.Pop(); - foreach (var reached in next.Members.Select(m => m.Value).Concat(next.Cases.Select(c => c.Value)) - .SelectMany(v => v.Walk()).SelectMany(_target.StructsIn)) - { - if (reached == Model) - return true; - if (seen.Add(reached)) - pending.Push(reached); - } - } - - return false; - } } } diff --git a/runtimes/csharp/src/Nino.Codegen/Targets/Rust/RustTarget.cs b/runtimes/csharp/src/Nino.Codegen/Targets/Rust/RustTarget.cs index 013b833f7..0e47549a9 100644 --- a/runtimes/csharp/src/Nino.Codegen/Targets/Rust/RustTarget.cs +++ b/runtimes/csharp/src/Nino.Codegen/Targets/Rust/RustTarget.cs @@ -169,47 +169,6 @@ private IEnumerable ObjectTypes() => private List Allowed(TypeModel type) => ObjectTypes().Where(type.IsAssignableFrom).ToList(); - /// - /// The non-raw structs a value holds without a class body between: itself, or (behind a type id) any struct - /// the slot allows. - /// - private IEnumerable StructsIn(ValueModel value) - { - var candidates = value.Kind switch - { - ValueKind.Type when value.Type!.Header == HeaderKind.TypeId => Allowed(value.Type), - ValueKind.Type => new List { value.Type! }, - ValueKind.Object => ObjectTypes().ToList(), - _ => new List(), - }; - return candidates.Where(t => t.IsValueType && !t.Raw && _supported.Contains(t)); - } - - /// - /// Whether a struct can hold itself through no class body: its nesting counts toward the depth limit - /// (enter_struct), as nothing else bounds it. - /// - internal bool HoldsItself(TypeModel type) - { - var seen = new HashSet(); - var pending = new Stack(); - pending.Push(type); - while (pending.Count != 0) - { - var next = pending.Pop(); - foreach (var reached in next.Members.Select(m => m.Value).Concat(next.Cases.Select(c => c.Value)) - .SelectMany(v => v.Walk()).SelectMany(StructsIn)) - { - if (reached == type) - return true; - if (seen.Add(reached)) - pending.Push(reached); - } - } - - return false; - } - // ---------------------------------------------------------------- names /// Names a generated type must not take: the prelude's and the generated code's own. 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.Nesting.cs b/runtimes/csharp/src/Nino.Codegen/Targets/TypeScript/TypeScriptTarget.Nesting.cs index abdcd6176..f653588e3 100644 --- a/runtimes/csharp/src/Nino.Codegen/Targets/TypeScript/TypeScriptTarget.Nesting.cs +++ b/runtimes/csharp/src/Nino.Codegen/Targets/TypeScript/TypeScriptTarget.Nesting.cs @@ -42,33 +42,6 @@ private static IEnumerable BodyValues(TypeModel type) => type.Members.Select(m => (ValueModel?)m.Value).Append(type.Elements) .Concat(type.Cases.Select(c => c.Value)).Where(v => v != null).Select(v => v!); - /// - /// Whether a struct can hold itself without a class body between (through collections, nullables, - /// object or interfaces): its nesting is counted (Reader.EnterStruct in .NET), so deep data throws - /// instead of overflowing the stack. - /// - internal bool HoldsItself(TypeModel type) - { - var seen = new HashSet(); - var pending = new Stack(); - pending.Push(type); - while (pending.Count != 0) - { - var next = pending.Pop(); - if (!_supported.Contains(next)) - continue; - foreach (var reached in BodyValues(next).SelectMany(v => ShapeIn(next, v).Reaches)) - { - if (reached == type) - return true; - if (seen.Add(reached)) - pending.Push(reached); - } - } - - return false; - } - private readonly HashSet _warnedDeferrable = new(); /// 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/go/shapes.sbn b/runtimes/csharp/src/Nino.Codegen/Templates/go/shapes.sbn index e99b69c59..df3073932 100644 --- a/runtimes/csharp/src/Nino.Codegen/Templates/go/shapes.sbn +++ b/runtimes/csharp/src/Nino.Codegen/Templates/go/shapes.sbn @@ -204,7 +204,7 @@ func reads_into(s) if s.kind == "seq" ret s.mode != "bytes" && s.mode != "block" && s.mode != "bools" && s.mode != "values" && s.mode != "ninonullables" && s.mode != "nullableslots" && s.mode != "unique" && s.mode != "stringset" && s.mode != "fixed" else if s.kind == "map" - ret s.mode != "block" && s.mode != "unique" + ret s.mode == "entries" || (s.mode == "fixed" && !s.unique_keys) end ret false end @@ -311,6 +311,8 @@ func decode(s, o) ret decode_fn(s) + "(r, " + span(o, s.size) + ")" when "emptystruct" ret name(s.struct) + "{}" + when "datetimeoffset" + ret "r.DateTimeOffsetAt(" + span(o, s.size) + ")" end $a = at(o) case s.primitive @@ -364,6 +366,8 @@ func encode(s, o, x) ret [encode_fn(s) + "(" + span(o, s.size) + ", " + x + ")"] when "emptystruct" ret [] + when "datetimeoffset" + ret [x + ".Put(" + span(o, s.size) + ")"] end $a = at(o) case s.primitive diff --git a/runtimes/csharp/src/Nino.Codegen/Templates/go/types.sbn b/runtimes/csharp/src/Nino.Codegen/Templates/go/types.sbn index 3ac95ec81..d965a1211 100644 --- a/runtimes/csharp/src/Nino.Codegen/Templates/go/types.sbn +++ b/runtimes/csharp/src/Nino.Codegen/Templates/go/types.sbn @@ -214,6 +214,10 @@ func write_members(c) ret $o end +func check_unique_values(s, value) + ret key_check(gotype(s)) + ".Values(r, " + value + ")" +end + func helper_body(h) $s = h.shape $n = h.name @@ -253,7 +257,7 @@ func helper_body(h) end $each = read_into($s.element, "e") ret $o + read_into_loop(gotype($s.element), $s.element.min, $each, $each != "e = " + read($s.element)) + "}\n" - else if h.mode == "read" && reads_into($s) + else if h.mode == "read" && reads_into($s) && $s.mode != "fixed" # The loop of the into form (a nil slice: a new one). ret "func " + $n + "(r *nino.Reader) (v " + $t + ") {\n\t" + helper($s, "readinto") + "(r, &v)\n\treturn v\n}\n" else if h.mode == "read" @@ -273,38 +277,52 @@ func helper_body(h) ret $o + "\treturn v\n}\n" when "grid" $o = $o + "\tg := readGrid[" + gotype($s.element) + "](r, " + $s.rank + ", " + compact($s.element.min) + ")\n\tif g == nil {\n\t\treturn nil\n\t}\n" + if $s.element.block + ret $o + "\tnino.ReadPrimitivesInto(r, g.Items)\n\tif r.Failed() {\n\t\treturn nil\n\t}\n\treturn g\n}\n" + end + if $s.element.size > 0 + $each = "_ = b[" + ($s.element.size - 1) + "]\n\t\tg.Items[i] = " + decode($s.element, 0) + ret $o + read_fixed_block($s.element.size, "len(g.Items)", "", $each, "", "for i := range g.Items", !$s.element.runnable) + "\treturn g\n}\n" + end ret $o + "\tfor i := range g.Items {\n\t\tg.Items[i] = " + read($s.element) + "\n\t\tif r.Failed() {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn g\n}\n" when "map" $e = "nino.Entry[" + gotype($s.key) + ", " + gotype($s.value) + "]" - $o = $o + read_loop($e, plus($s.key, $s.value), "k := " + read($s.key) + "\n\t\te = " + $e + "{Key: k, Value: " + read($s.value) + "}") + if $s.mode == "fixed" + $z = $s.key.size + $s.value.size + $each = "e = " + $e + "{Key: " + decode($s.key, 0) + ", Value: " + decode($s.value, $s.key.size) + "}" + $o = $o + read_fixed($e, $z, $each, !$s.key.runnable || !$s.value.runnable) + else + $o = $o + read_loop($e, plus($s.key, $s.value), "k := " + read($s.key) + "\n\t\te = " + $e + "{Key: k, Value: " + read($s.value) + "}") + end # Keys read twice fail, checked once over the pairs. - ret $o + ($s.mode == "unique" ? "\treturn nino.CheckUniqueKeys(r, v)\n}\n" : "\treturn v\n}\n") + ret $o + ($s.unique_keys ? "\treturn nino.CheckUniqueKeysWith(r, v, &" + key_check(gotype($s.key)) + ")\n}\n" : "\treturn v\n}\n") end # A sequence. case $s.mode - when "unique" + when "unique", "fixed" # Elements read twice fail, checked once over the elements (primitives read as one block). - if $s.element.block - ret $o + "\treturn nino.CheckUniqueValues(r, nino.ReadPrimitives[" + gotype($s.element) + "](r))\n}\n" + if $s.mode == "unique" && $s.element.block + ret $o + "\treturn " + check_unique_values($s.element, "nino.ReadPrimitives[" + gotype($s.element) + "](r)") + "\n}\n" + end + if $s.element.block_value + ret $o + "\treturn " + check_unique_values($s.element, "nino.ReadBlock[" + gotype($s.element) + "](r)") + "\n}\n" end - ret $o + read_loop(gotype($s.element), $s.element.min, "e = " + read($s.element)) + "\treturn nino.CheckUniqueValues(r, v)\n}\n" + if $s.element.kind == "prim" && $s.element.primitive == "Bool" + ret $o + "\treturn " + check_unique_values($s.element, "nino.ReadBools(r)") + "\n}\n" + end + $unique = $s.mode == "unique" || $s.unique_slots + $b = $s.element.raw_block + if $b + $o = $o + "\tif v, ok := nino.TryReadRaw[" + gotype($s.element) + "](r, " + $s.element.size + ", " + $b.as_is + ", " + $b.bools + "); ok {\n\t\treturn " + ($unique ? check_unique_values($s.element, "v") : "v") + "\n\t}\n" + end + ret $o + read_fixed(gotype($s.element), $s.element.size, "e = " + decode($s.element, 0), !$s.element.runnable) + "\treturn " + ($unique ? check_unique_values($s.element, "v") : "v") + "\n}\n" when "stringset" # A set of strings in the order of the data: a string (or null) read twice fails. ret $o + read_loop(gotype($s.element), $s.element.min, "e = " + read($s.element)) + "\treturn nino.CheckUniqueStrings(r, v)\n}\n" when "nullableslots" # A set of the slots of a number (any other sequence of them calls the block directly): an element read twice # fails, null included. - ret $o + "\treturn nino.CheckUniqueValues(r, nino.ReadNullableSlots[" + gotype($s.element.inner) + "](r))\n}\n" - when "fixed" - $b = $s.element.raw_block - if $b - ret $o + "\treturn nino.ReadRaw(r, " + $s.element.size + ", " + $b.as_is + ", " + $b.bools + ", " + decode_fn($s.element) + ")\n}\n" - end - # The elements' bytes with one bounds check, then each element's from a cursor. - $z = $s.element.size - $o = $o + "\tn := r.Length(" + $z + ")\n\tif n < 0 {\n\t\treturn nil\n\t}\n\tb := r.Take(n * " + $z + ")\n\tif len(b) != n*" + $z + " {\n\t\treturn nil\n\t}\n" - $o = $o + make_slice(gotype($s.element)) + "\tfor len(b) >= " + $z + " {\n\t\te = " + decode_fn($s.element) + "(r, b[:" + $z + ":" + $z + "])\n" - ret $o + "\t\tif r.Failed() {\n\t\t\treturn nil\n\t\t}\n\t\tv = append(v, e)\n\t\tb = b[" + $z + ":]\n\t}\n\treturn " + ($s.unique_slots ? "nino.CheckUniqueValues(r, v)" : "v") + "\n}\n" + ret $o + "\treturn " + check_unique_values($s.element, "nino.ReadNullableSlots[" + gotype($s.element.inner) + "](r)") + "\n}\n" end ret $o + read_loop(gotype($s.element), $s.element.min, "e = " + read($s.element)) + "\treturn v\n}\n" end @@ -323,21 +341,32 @@ func helper_body(h) end ret $o + "}\n" when "grid" - ret $o + "\tif !writeGrid(w, v, " + $s.rank + ") {\n\t\treturn\n\t}\n\tfor _, e := range v.Items {\n\t\t" + write($s.element, "e") + "\n\t}\n}\n" + $o = $o + "\tif !writeGrid(w, v, " + $s.rank + ") {\n\t\treturn\n\t}\n" + if $s.element.block + ret $o + "\tnino.WritePrimitivesRaw(w, v.Items)\n}\n" + end + if $s.element.size > 0 + ret $o + write_fixed_block("v.Items", $s.element.size, $s.element, "e", null, "") + "}\n" + end + ret $o + "\tfor _, e := range v.Items {\n\t\t" + write($s.element, "e") + "\n\t}\n}\n" when "map" + if $s.mode == "fixed" + ret $o + write_length() + write_fixed_block("v", $s.key.size + $s.value.size, $s.key, "e.Key", $s.value, "e.Value") + "}\n" + end ret $o + write_loop(write($s.key, "e.Key") + "\n\t\t" + write($s.value, "e.Value")) end - if $s.mode == "fixed" + if $s.element.block + ret $o + "\tnino.WritePrimitives(w, v)\n}\n" + else if $s.element.block_value + ret $o + "\tnino.WriteBlock(w, v)\n}\n" + else if $s.element.kind == "prim" && $s.element.primitive == "Bool" + ret $o + "\tnino.WriteBools(w, v)\n}\n" + else if $s.mode == "fixed" || $s.mode == "unique" $b = $s.element.raw_block if $b - ret $o + "\tnino.WriteRaw(w, v, " + $s.element.size + ", " + $b.as_is + ", " + $b.bools + ", " + $b.pads + ", " + encode_fn($s.element) + ")\n}\n" + $o = $o + "\tif nino.TryWriteRaw(w, v, " + $s.element.size + ", " + $b.as_is + ", " + $b.bools + ", " + $b.pads + ") {\n\t\treturn\n\t}\n" end - # One reservation, cleared (padding is written as zeros), then each element's bytes from a cursor. - $z = $s.element.size - $o = $o + "\tif v == nil {\n\t\tw.NullLength()\n\t\treturn\n\t}\n\tw.Length(len(v))\n\tb := w.ExtendZero(len(v) * " + $z + ")\n\tif len(b) != len(v)*" + $z + " {\n\t\treturn\n\t}\n" - ret $o + "\tfor _, e := range v {\n\t\t" + encode_fn($s.element) + "(b[:" + $z + ":" + $z + "], e)\n\t\tb = b[" + $z + ":]\n\t}\n}\n" - else if $s.element.block - ret $o + "\tnino.WritePrimitives(w, v)\n}\n" + ret $o + write_length() + write_fixed_block("v", $s.element.size, $s.element, "e", null, "") + "}\n" else if $s.element.kind == "string" && !$s.element.field ret $o + "\tnino.WriteStringPtrs(w, v)\n}\n" else if $s.element.kind == "keystring" && !$s.element.field @@ -346,6 +375,52 @@ func helper_body(h) ret $o + write_loop(write($s.element, "e")) end +# A fixed run's cursor. The count was checked against the input by Length or ReadShape. +func read_fixed_block(size, n, setup, each, after, loop, checked) + $o = "\tb := r.Take(" + n + " * " + size + ")\n\tif r.Failed() {\n\t\treturn nil\n\t}\n" + setup + "\t" + loop + " {\n\t\t" + each + "\n" + if checked + $o = $o + "\t\tif r.Failed() {\n\t\t\treturn nil\n\t\t}\n" + end + ret $o + after + "\t\tb = b[" + size + ":]\n\t}\n" +end + +func read_fixed(t, size, each, checked) + $o = "\tn := r.Length(" + size + ")\n\tif n < 0 {\n\t\treturn nil\n\t}\n" + ret $o + read_fixed_block(size, "n", make_slice(t), each, "\t\tv = append(v, e)\n", "for len(b) >= " + size, checked) +end + +# Preflight range-limited fields. If one is invalid, use the scalar writer on the prefix ending at that field +# so it reports the same offset as the element loop. +func write_fixed_block(values, size, first, a, second, b) + $o = "" + if first.checked_write || (second && second.checked_write) + $test = first.checked_write ? "!" + a + ".Valid()" : "" + if second && second.checked_write + $test = $test + ($test == "" ? "" : " || ") + "!" + b + ".Valid()" + end + $scalar = "\t\t\t\t" + write(first, a) + "\n" + if second + $scalar = $scalar + "\t\t\t\t" + write(second, b) + "\n" + end + $o = "\tfor i, e := range " + values + " {\n\t\tif " + $test + " {\n\t\t\tfor _, e := range " + values + "[:i+1] {\n" + $scalar + "\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n" + end + $code = encode(first, 0, a) + if second + $code = array.concat $code (encode(second, first.size, b)) + end + $zero = first.needs_zero || (second && second.needs_zero) ? "true" : "false" + $o = $o + "\tb := w.ExtendFixed(len(" + values + "), " + size + ", " + $zero + ")\n\tif b == nil {\n\t\treturn\n\t}\n" + if $code.size != 0 + if second + $o = $o + "\tfor i := range " + values + " {\n\t\te := &" + values + "[i]\n" + else + $o = $o + "\tfor _, e := range " + values + " {\n" + end + $o = $o + "\t\t_ = b[" + (size - 1) + "]\n" + lines($code, "\t\t") + "\t\tb = b[" + size + ":]\n\t}\n" + end + ret $o +end + # The loop of a sequence's read helper: its length (n), then each element, read by `each` into `e` (of type `t`) # with direct calls (no func value an element), appended to `v`. As the runtime's own loops do: nil for null and on a # failure, the slice presized only as far as the bytes left allow (Reader.SliceCap). @@ -374,7 +449,11 @@ end # The rest of a sequence's write helper: null for nil, else its length and each element `e`, written by `each`. func write_loop(each) - ret "\tif v == nil {\n\t\tw.NullLength()\n\t\treturn\n\t}\n\tw.Length(len(v))\n\tfor _, e := range v {\n\t\t" + each + "\n\t}\n}\n" + ret write_length() + "\tfor _, e := range v {\n\t\t" + each + "\n\t}\n}\n" +end + +func write_length() + ret "\tif v == nil {\n\t\tw.NullLength()\n\t\treturn\n\t}\n\tw.Length(len(v))\n" end # A slot's dispatch: the type id, then the body of one of the types the declared type allows. `read` and `write` @@ -948,6 +1027,11 @@ while $i < helper_count() $i = $i + 1 end +# The duplicate check initializers shared across helpers by the Go key type. +for $type in key_check_types() + "\nvar keyCheck" + for.index + " = nino.PrepareKeyCheck[" + $type + "]()\n" +end + for n in tuples $params = [] $fields = [] diff --git a/runtimes/csharp/src/Nino.Codegen/Templates/rust/types.sbn b/runtimes/csharp/src/Nino.Codegen/Templates/rust/types.sbn index 22da9ae52..66bfeed4a 100644 --- a/runtimes/csharp/src/Nino.Codegen/Templates/rust/types.sbn +++ b/runtimes/csharp/src/Nino.Codegen/Templates/rust/types.sbn @@ -263,14 +263,25 @@ func union_rs(t) end $o = $o + " fn read_case(r: &mut nino::Reader<'_>, id: i32) -> nino::Result {\n Ok(match id {\n" for $k in t.cases + $defer = t.model.union_nests && !$k.model.leaf + if !$k.model.nullable && !$defer + $o = $o + " " + $k.model.type_id + " => Self::" + $k.name + "(r.read()?),\n" + continue + end + $o = $o + " " + $k.model.type_id + " => {\n" + if $defer + # A primitive, raw value or string cannot introduce a deferred class body. + $o = $o + " let mark = r.defer_mark();\n" + end + $o = $o + " let value: " + rtype($k.shape) + " = r.read()?;\n" if $k.model.nullable # A case read as None is invalid: .NET writes the empty union for a case given null. - $o = $o + " " + $k.model.type_id + " => {\n let value: " + rtype($k.shape) + " = r.read()?;\n" $o = $o + " if value.is_none() {\n return Err(nino::Error::new(nino::ErrorKind::UnexpectedNull, id));\n }\n" - $o = $o + " Self::" + $k.name + "(value)\n }\n" - else - $o = $o + " " + $k.model.type_id + " => Self::" + $k.name + "(r.read()?),\n" end + if $defer + $o = $o + " r.defer_trail(mark, nino::Step::Field(|p| p.downcast_mut::<" + $n + ">()?.case_value()));\n" + end + $o = $o + " Self::" + $k.name + "(value)\n }\n" end $o = $o + " _ => return Err(nino::Error::new(nino::ErrorKind::UnknownTypeId, id)),\n })\n }\n}\n" $o = $o + "impl NinoRead for " + $n + " {\n" @@ -278,17 +289,15 @@ func union_rs(t) $o = $o + " const MAY_DEFER: bool = true;\n" end $o = $o + " const MIN_SIZE: usize = 4;\n" - $o = $o + " fn read(r: &mut nino::Reader<'_>) -> nino::Result {\n let mut v = Self::Empty;\n v.read_into(r)?;\n Ok(v)\n }\n" - $o = $o + " fn read_into(&mut self, r: &mut nino::Reader<'_>) -> nino::Result<()> {\n let id = r.i32()?;\n" - $o = $o + " if id == 0 {\n *self = Self::Empty;\n return Ok(());\n }\n" + $o = $o + " #[inline]\n fn read(r: &mut nino::Reader<'_>) -> nino::Result {\n let id = r.i32()?;\n" + $o = $o + " if id == 0 {\n return Ok(Self::Empty);\n }\n" if t.model.union_nests $o = $o + " // A case can hold the union again: each level counts toward the depth limit.\n r.enter_struct()?;\n" - $o = $o + " let mark = r.defer_mark();\n let value = Self::read_case(r, id);\n r.exit_struct();\n *self = value?;\n" - $o = $o + " r.defer_trail(mark, nino::Step::Field(|p| p.downcast_mut::<" + $n + ">()?.case_value()));\n" + $o = $o + " let value = Self::read_case(r, id);\n r.exit_struct();\n value\n" else - $o = $o + " *self = Self::read_case(r, id)?;\n" + $o = $o + " Self::read_case(r, id)\n" end - $o = $o + " Ok(())\n }\n}\n" + $o = $o + " }\n}\n" $o = $o + "impl NinoWrite for " + $n + " {\n fn write<'a>(&'a self, w: &mut nino::Writer<'a>) -> nino::Result<()> {\n match self {\n" for $k in t.cases $o = $o + " Self::" + $k.name + "(v)" + ($k.model.nullable ? " if v.is_some()" : "") + " => {\n" 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 44651d1fa..490b0c2de 100644 --- a/runtimes/csharp/src/Nino.Codegen/Templates/typescript/types.sbn +++ b/runtimes/csharp/src/Nino.Codegen/Templates/typescript/types.sbn @@ -247,12 +247,26 @@ func case_ts(k) ret $t end -# Writing a union case's value, never null: a nullable's presence byte is 1. +# Writing a union case's id and value. Reserve both together if the payload size is known. func case_write(k, v) - if k.shape.kind == "nullable" - ret "w.u8(1);\n " + stmt(write(k.shape.inner, v)) + $s = k.shape + $nullable = $s.kind == "nullable" + if $nullable + $s = $s.inner end - ret stmt(write(k.shape, v)) + if $s.fixed + $size = 4 + ($nullable ? 1 : 0) + $o = "const at = " + reserve($size + $s.size, $s.zeroed) + ";\nw.view.setInt32(at, " + k.model.type_id + ", true);\n" + if $nullable + $o = $o + "w.view.setUint8(at + 4, 1);\n" + end + ret $o + stmt(write_at($s, $size, v)) + end + $o = "w.i32(" + k.model.type_id + ");\n" + if $nullable + $o = $o + "w.u8(1);\n" + end + ret $o + stmt(write($s, v)) end # A C# union (spec §7.12): the type id of its case (0, null, for the empty union), then the case's value, never null. @@ -318,12 +332,12 @@ func union_type(c) if c.tagged $o = $o + " switch (v.case) {\n" for $k in c.cases - $o = $o + " case \"" + $k.model.name + "\":\n w.i32(" + $k.model.type_id + ");\n " + case_write($k, "v.value") + "\n break;\n" + $o = $o + " case \"" + $k.model.name + "\": {\n " + (string.replace (case_write($k, "v.value")) "\n" "\n ") + "\n break;\n }\n" end $o = $o + " default:\n throw types.unwritable(v);\n }\n" else for $k in c.cases - $o = $o + (for.first ? " if (" : " else if (") + $k.test + ") {\n w.i32(" + $k.model.type_id + ");\n " + (string.replace (case_write($k, "v")) "\n " "\n ") + "\n }\n" + $o = $o + (for.first ? " if (" : " else if (") + $k.test + ") {\n " + (string.replace (case_write($k, "v")) "\n" "\n ") + "\n }\n" end $o = $o + " else throw types.unwritable(v as object);\n" end @@ -346,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 a0f29585d..9b1ca0661 100644 --- a/runtimes/csharp/tests/Nino.Codegen.Tests/Shapes.cs +++ b/runtimes/csharp/tests/Nino.Codegen.Tests/Shapes.cs @@ -111,6 +111,17 @@ public struct Marked public short Code; } + /// Fixed-width collections whose Go element memory is not necessarily the wire layout. + [NinoType] + public sealed class FixedCollections + { + public Dictionary Ids; + public HashSet UniqueIds; + public byte[,] Grid; + public Dictionary Pairs; + public System.DateTimeOffset[] Offsets; + } + /// Keys Rust cannot hash: Rust leaves the type out, with a warning; Go and TypeScript keep it. [NinoType] public sealed class FloatKeys @@ -167,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 885de9412..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\] ")); @@ -295,6 +297,13 @@ public void RawNullableSlotsAreGeneratedInEveryLanguage() Assert.IsFalse(tsOutput.Contains("NullableSlots", StringComparison.Ordinal), tsOutput); } + [TestMethod] + public void ClosedGenericStructsGiveGoCollectionsTheirMinimumSize() + { + var (go, _) = Run("go", "nino_types.go"); + Assert.IsTrue(Regex.IsMatch(go, @"func readV\d+\(r \*nino.Reader\) \[\]nino.Entry\[string, Pair\[int32, int32\]\] \{\n\tn := r.Length\(9\)")); + } + /// /// A NinoNullable<T> has a type of its own in Go and Rust (nino.NinoNullable[T], a value /// and whether it has one; nino::NinoNullable<T>, an Option<T> with those bytes), diff --git a/runtimes/go/AGENTS.md b/runtimes/go/AGENTS.md index 45a96b438..53b2f9f0d 100644 --- a/runtimes/go/AGENTS.md +++ b/runtimes/go/AGENTS.md @@ -29,9 +29,9 @@ nullable.go NullableSlot[T] (a T? as the element of a sequence) where Go's layout is the wire's) endian_little.go littleEndian = true on little-endian architectures (blocks copied as memory) endian_other.go littleEndian = false elsewhere (blocks converted element by element) -unique.go duplicate keys of sets and maps read in data order: numbers, strings and NullableSlots of - numbers (a set of T?) compared as .NET does, pairwise or in a seeded open-addressing table - (the reader's scratch), no map +unique.go duplicate keys of sets and maps read in data order: numbers, strings, NullableSlots of + numbers (a set of T?) and keys whose equality is their bytes, pairwise or in a seeded + open-addressing table (the reader's scratch); generated codecs prepare key metadata per Go key type collections.go slices, maps, sets, entries, fixed-size runs, multidimensional shapes (the func-value helpers unexported, for the runtime's rare paths); counts checked against the bytes left depth.go class bodies (Class, ReadClass, WriteClass), deferral past 128, the 512 limit @@ -142,8 +142,10 @@ requirements: of allocations (`bench`, `-benchmem`). A collection of fixed-size elements takes a block helper (`ReadPrimitives`, `ReadPrimitiveEntries`, `ReadPrimitiveMap`), never the generic helpers that take element functions: those are an indirect call per element (`(*Reader).I32` is never inlined through a func value) and a - bounds check per value. Any other collection loop in generated code is written out with the element's call made directly - (nino-gen's `read_loop` / `write_loop`), never a helper taking a func value (the runtime keeps `readSlice` and the like unexported, for its own rare paths) (`optimize-runtimes`, references/dispatch.md). + bounds check per value. Generated fixed-width maps, sequences, sets and grids without a matching bulk copy + share a cursor loop at constant offsets. Raw sequences still attempt the memory copy through `TryReadRaw` / + `TryWriteRaw`, then take the same cursor on other hosts. Other generated collection loops also call the + element's codec directly (nino-gen's `read_loop` / `write_loop`; `optimize-runtimes`, references/dispatch.md). `ReadPrimitiveMap` read a 10-pair `map[int32]int32` 31 % faster than `ReadMap` (now unexported), and SimpleClass 4-7 % faster on runners (7ac8b46). Walk a block with a cursor (`for len(b) >= wire { ...; b = b[wire:] }`): indexing `b[i*wire:]` kept a bounds check per pair. A runner A/B can move code you did not touch by @@ -151,9 +153,11 @@ requirements: (it then measured 7-14 % faster) rather than land a loss. - Checks over a block (ranges of dates and decimals, the bools of raw structs) and UTF-16 copies: what measured faster and slower is in the `optimize-runtimes` skill, "Checking blocks in Go"; time them with BenchmarkBlocks and BenchmarkUTF16. -- Struct tags (`tagged.go`, `layout.go`, `marshal.go`) are the one place reflection is allowed: a plan built once - per type, then walked. Anything the wire format cannot express is a `*TagError` naming the field when the plan - is built, never a silent default; reads go through the same `Reader` calls as generated code, so the guarantees +- Prepare generated set and dictionary duplicate checks once in package initializers (`PrepareKeyCheck`). + Primitive-entry checks use their generic type constraint. Struct tags (`tagged.go`, `layout.go`, + `marshal.go`) also build a reflection plan once per type, then walk it. Anything the wire format cannot express + is a `*TagError` naming the field when the plan is built, never a silent default; reads go through the same + `Reader` calls as generated code, so the guarantees above hold there too. The sample types carry the tags and `NinoLayout` a generator emits (README, "Tags on generated structs"); keep them and `internal/sample/tagged_test.go` in step with the hand-written codecs. A type decides its own encoding wherever the wire has two for one .NET shape: `nino.NinoNullable[T]` is .NET's diff --git a/runtimes/go/bench/model/nino_types.go b/runtimes/go/bench/model/nino_types.go index 145b6a820..43e59d13d 100644 --- a/runtimes/go/bench/model/nino_types.go +++ b/runtimes/go/bench/model/nino_types.go @@ -26738,11 +26738,48 @@ func writeV8(w *nino.Writer, v []*CardDef) { } func readV9(r *nino.Reader) []Buff { - return nino.ReadRaw(r, 8, asIsBuff, nil, decodeBuff) + if v, ok := nino.TryReadRaw[Buff](r, 8, asIsBuff, nil); ok { + return v + } + n := r.Length(8) + if n < 0 { + return nil + } + b := r.Take(n * 8) + if r.Failed() { + return nil + } + var e Buff + v := make([]Buff, 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) + for len(b) >= 8 { + e = decodeBuff(r, b[0:8]) + if r.Failed() { + return nil + } + v = append(v, e) + b = b[8:] + } + return v } func writeV9(w *nino.Writer, v []Buff) { - nino.WriteRaw(w, v, 8, asIsBuff, nil, []int{3}, encodeBuff) + if nino.TryWriteRaw(w, v, 8, asIsBuff, nil, []int{3}) { + return + } + if v == nil { + w.NullLength() + return + } + w.Length(len(v)) + b := w.ExtendFixed(len(v), 8, true) + if b == nil { + return + } + for _, e := range v { + _ = b[7] + encodeBuff(b[0:8], e) + b = b[8:] + } } func readintoV10(r *nino.Reader, p *[]*BattlePlayer) { @@ -27045,7 +27082,7 @@ func readV19(r *nino.Reader) []nino.Entry[string, *string] { } v = append(v, e) } - return nino.CheckUniqueKeys(r, v) + return nino.CheckUniqueKeysWith(r, v, &keyCheck0) } func writeV18(w *nino.Writer, v Severity) { @@ -27079,7 +27116,7 @@ func readV20(r *nino.Reader) []nino.Entry[string, int32] { } v = append(v, e) } - return nino.CheckUniqueKeys(r, v) + return nino.CheckUniqueKeysWith(r, v, &keyCheck0) } func readV21(r *nino.Reader) []nino.Entry[int32, *string] { @@ -27097,7 +27134,7 @@ func readV21(r *nino.Reader) []nino.Entry[int32, *string] { } v = append(v, e) } - return nino.CheckUniqueKeys(r, v) + return nino.CheckUniqueKeysWith(r, v, &keyCheck1) } func writeV20(w *nino.Writer, v []nino.Entry[string, int32]) { @@ -27129,7 +27166,28 @@ func readV22(r *nino.Reader) MarchKind { } func readV23(r *nino.Reader) []MapPoint { - return nino.ReadRaw(r, 4, asIsMapPoint, nil, decodeMapPoint) + if v, ok := nino.TryReadRaw[MapPoint](r, 4, asIsMapPoint, nil); ok { + return v + } + n := r.Length(4) + if n < 0 { + return nil + } + b := r.Take(n * 4) + if r.Failed() { + return nil + } + var e MapPoint + v := make([]MapPoint, 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) + for len(b) >= 4 { + e = decodeMapPoint(r, b[0:4]) + if r.Failed() { + return nil + } + v = append(v, e) + b = b[4:] + } + return v } func writeV22(w *nino.Writer, v MarchKind) { @@ -27137,7 +27195,23 @@ func writeV22(w *nino.Writer, v MarchKind) { } func writeV23(w *nino.Writer, v []MapPoint) { - nino.WriteRaw(w, v, 4, asIsMapPoint, nil, nil, encodeMapPoint) + if nino.TryWriteRaw(w, v, 4, asIsMapPoint, nil, nil) { + return + } + if v == nil { + w.NullLength() + return + } + w.Length(len(v)) + b := w.ExtendFixed(len(v), 4, true) + if b == nil { + return + } + for _, e := range v { + _ = b[3] + encodeMapPoint(b[0:4], e) + b = b[4:] + } } func readV24(r *nino.Reader) MediaPlayer { @@ -27187,11 +27261,48 @@ func writeV25(w *nino.Writer, v []*Image) { } func readV26(r *nino.Reader) []Vec3 { - return nino.ReadRaw(r, 12, asIsVec3, nil, decodeVec3) + if v, ok := nino.TryReadRaw[Vec3](r, 12, asIsVec3, nil); ok { + return v + } + n := r.Length(12) + if n < 0 { + return nil + } + b := r.Take(n * 12) + if r.Failed() { + return nil + } + var e Vec3 + v := make([]Vec3, 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) + for len(b) >= 12 { + e = decodeVec3(r, b[0:12]) + if r.Failed() { + return nil + } + v = append(v, e) + b = b[12:] + } + return v } func writeV26(w *nino.Writer, v []Vec3) { - nino.WriteRaw(w, v, 12, asIsVec3, nil, nil, encodeVec3) + if nino.TryWriteRaw(w, v, 12, asIsVec3, nil, nil) { + return + } + if v == nil { + w.NullLength() + return + } + w.Length(len(v)) + b := w.ExtendFixed(len(v), 12, true) + if b == nil { + return + } + for _, e := range v { + _ = b[11] + encodeVec3(b[0:12], e) + b = b[12:] + } } func readintoV27(r *nino.Reader, p *[]IComponent) { @@ -27440,11 +27551,11 @@ func readV37(r *nino.Reader) []nino.Entry[int32, PolymorphicFooBase] { } v = append(v, e) } - return nino.CheckUniqueKeys(r, v) + return nino.CheckUniqueKeysWith(r, v, &keyCheck1) } func readV38(r *nino.Reader) []int32 { - return nino.CheckUniqueValues(r, nino.ReadPrimitives[int32](r)) + return keyCheck1.Values(r, nino.ReadPrimitives[int32](r)) } func writeV36(w *nino.Writer, v []PolymorphicFooBase) { @@ -27607,11 +27718,48 @@ func writeV45(w *nino.Writer, v UserType) { } func readV46(r *nino.Reader) []DamageHit { - return nino.ReadRaw(r, 12, asIsDamageHit, []int{8}, decodeDamageHit) + if v, ok := nino.TryReadRaw[DamageHit](r, 12, asIsDamageHit, []int{8}); ok { + return v + } + n := r.Length(12) + if n < 0 { + return nil + } + b := r.Take(n * 12) + if r.Failed() { + return nil + } + var e DamageHit + v := make([]DamageHit, 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) + for len(b) >= 12 { + e = decodeDamageHit(r, b[0:12]) + if r.Failed() { + return nil + } + v = append(v, e) + b = b[12:] + } + return v } func writeV46(w *nino.Writer, v []DamageHit) { - nino.WriteRaw(w, v, 12, asIsDamageHit, []int{8}, []int{9, 10, 11}, encodeDamageHit) + if nino.TryWriteRaw(w, v, 12, asIsDamageHit, []int{8}, []int{9, 10, 11}) { + return + } + if v == nil { + w.NullLength() + return + } + w.Length(len(v)) + b := w.ExtendFixed(len(v), 12, true) + if b == nil { + return + } + for _, e := range v { + _ = b[11] + encodeDamageHit(b[0:12], e) + b = b[12:] + } } func readintoV47(r *nino.Reader, p *[]*Question) { @@ -27814,7 +27962,28 @@ func writeV52(w *nino.Writer, v NinoTuple2[int32, int16]) { } func readV53(r *nino.Reader) []Tile { - return nino.ReadRaw(r, 8, asIsTile, nil, decodeTile) + if v, ok := nino.TryReadRaw[Tile](r, 8, asIsTile, nil); ok { + return v + } + n := r.Length(8) + if n < 0 { + return nil + } + b := r.Take(n * 8) + if r.Failed() { + return nil + } + var e Tile + v := make([]Tile, 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) + for len(b) >= 8 { + e = decodeTile(r, b[0:8]) + if r.Failed() { + return nil + } + v = append(v, e) + b = b[8:] + } + return v } func readintoV54(r *nino.Reader, p *[]*Alliance) { @@ -27896,7 +28065,23 @@ func readintoV56(r *nino.Reader, p *[]*Army) { } func writeV53(w *nino.Writer, v []Tile) { - nino.WriteRaw(w, v, 8, asIsTile, nil, []int{2, 3}, encodeTile) + if nino.TryWriteRaw(w, v, 8, asIsTile, nil, []int{2, 3}) { + return + } + if v == nil { + w.NullLength() + return + } + w.Length(len(v)) + b := w.ExtendFixed(len(v), 8, true) + if b == nil { + return + } + for _, e := range v { + _ = b[7] + encodeTile(b[0:8], e) + b = b[8:] + } } func writeV54(w *nino.Writer, v []*Alliance) { @@ -28104,13 +28289,13 @@ func readV66(r *nino.Reader) []nino.NullableSlot[nino.Decimal] { return nil } b := r.Take(n * 24) - if len(b) != n*24 { + if r.Failed() { return nil } var e nino.NullableSlot[nino.Decimal] v := make([]nino.NullableSlot[nino.Decimal], 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) for len(b) >= 24 { - e = decodeV100(r, b[:24:24]) + e = decodeV100(r, b[0:24]) if r.Failed() { return nil } @@ -28126,12 +28311,13 @@ func writeV66(w *nino.Writer, v []nino.NullableSlot[nino.Decimal]) { return } w.Length(len(v)) - b := w.ExtendZero(len(v) * 24) - if len(b) != len(v)*24 { + b := w.ExtendFixed(len(v), 24, true) + if b == nil { return } for _, e := range v { - encodeV100(b[:24:24], e) + _ = b[23] + encodeV100(b[0:24], e) b = b[24:] } } @@ -28142,13 +28328,13 @@ func readV67(r *nino.Reader) []nino.NullableSlot[Vec3] { return nil } b := r.Take(n * 16) - if len(b) != n*16 { + if r.Failed() { return nil } var e nino.NullableSlot[Vec3] v := make([]nino.NullableSlot[Vec3], 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) for len(b) >= 16 { - e = decodeV101(r, b[:16:16]) + e = decodeV101(r, b[0:16]) if r.Failed() { return nil } @@ -28164,12 +28350,13 @@ func writeV67(w *nino.Writer, v []nino.NullableSlot[Vec3]) { return } w.Length(len(v)) - b := w.ExtendZero(len(v) * 16) - if len(b) != len(v)*16 { + b := w.ExtendFixed(len(v), 16, true) + if b == nil { return } for _, e := range v { - encodeV101(b[:16:16], e) + _ = b[15] + encodeV101(b[0:16], e) b = b[16:] } } @@ -28228,15 +28415,52 @@ func writeV70(w *nino.Writer, v []*string) { } func readV71(r *nino.Reader) []nino.NullableSlot[int32] { - return nino.CheckUniqueValues(r, nino.ReadNullableSlots[int32](r)) + return keyCheck2.Values(r, nino.ReadNullableSlots[int32](r)) } func readV72(r *nino.Reader) []InventoryItem { - return nino.ReadRaw(r, 8, asIsInventoryItem, []int{6}, decodeInventoryItem) + if v, ok := nino.TryReadRaw[InventoryItem](r, 8, asIsInventoryItem, []int{6}); ok { + return v + } + n := r.Length(8) + if n < 0 { + return nil + } + b := r.Take(n * 8) + if r.Failed() { + return nil + } + var e InventoryItem + v := make([]InventoryItem, 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) + for len(b) >= 8 { + e = decodeInventoryItem(r, b[0:8]) + if r.Failed() { + return nil + } + v = append(v, e) + b = b[8:] + } + return v } func writeV72(w *nino.Writer, v []InventoryItem) { - nino.WriteRaw(w, v, 8, asIsInventoryItem, []int{6}, []int{7}, encodeInventoryItem) + if nino.TryWriteRaw(w, v, 8, asIsInventoryItem, []int{6}, []int{7}) { + return + } + if v == nil { + w.NullLength() + return + } + w.Length(len(v)) + b := w.ExtendFixed(len(v), 8, true) + if b == nil { + return + } + for _, e := range v { + _ = b[7] + encodeInventoryItem(b[0:8], e) + b = b[8:] + } } func readV73(r *nino.Reader) (v []Waypoint) { @@ -28404,13 +28628,13 @@ func readV83(r *nino.Reader) []nino.NullableSlot[SimpleStruct] { return nil } b := r.Take(n * 16) - if len(b) != n*16 { + if r.Failed() { return nil } var e nino.NullableSlot[SimpleStruct] v := make([]nino.NullableSlot[SimpleStruct], 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) for len(b) >= 16 { - e = decodeV103(r, b[:16:16]) + e = decodeV103(r, b[0:16]) if r.Failed() { return nil } @@ -28426,12 +28650,13 @@ func writeV83(w *nino.Writer, v []nino.NullableSlot[SimpleStruct]) { return } w.Length(len(v)) - b := w.ExtendZero(len(v) * 16) - if len(b) != len(v)*16 { + b := w.ExtendFixed(len(v), 16, true) + if b == nil { return } for _, e := range v { - encodeV103(b[:16:16], e) + _ = b[15] + encodeV103(b[0:16], e) b = b[16:] } } @@ -28510,13 +28735,13 @@ func readV88(r *nino.Reader) []RawNullable { return nil } b := r.Take(n * 40) - if len(b) != n*40 { + if r.Failed() { return nil } var e RawNullable v := make([]RawNullable, 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) for len(b) >= 40 { - e = decodeRawNullable(r, b[:40:40]) + e = decodeRawNullable(r, b[0:40]) if r.Failed() { return nil } @@ -28532,12 +28757,13 @@ func writeV88(w *nino.Writer, v []RawNullable) { return } w.Length(len(v)) - b := w.ExtendZero(len(v) * 40) - if len(b) != len(v)*40 { + b := w.ExtendFixed(len(v), 40, true) + if b == nil { return } for _, e := range v { - encodeRawNullable(b[:40:40], e) + _ = b[39] + encodeRawNullable(b[0:40], e) b = b[40:] } } @@ -28628,11 +28854,48 @@ func writeV93(w *nino.Writer, v []NinoTuple5[float64, int64, float64, float32, u } func readV94(r *nino.Reader) []PaddedRaw { - return nino.ReadRaw(r, 16, asIsPaddedRaw, nil, decodePaddedRaw) + if v, ok := nino.TryReadRaw[PaddedRaw](r, 16, asIsPaddedRaw, nil); ok { + return v + } + n := r.Length(16) + if n < 0 { + return nil + } + b := r.Take(n * 16) + if r.Failed() { + return nil + } + var e PaddedRaw + v := make([]PaddedRaw, 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) + for len(b) >= 16 { + e = decodePaddedRaw(r, b[0:16]) + if r.Failed() { + return nil + } + v = append(v, e) + b = b[16:] + } + return v } func writeV94(w *nino.Writer, v []PaddedRaw) { - nino.WriteRaw(w, v, 16, asIsPaddedRaw, nil, []int{2, 3, 4, 5, 6, 7}, encodePaddedRaw) + if nino.TryWriteRaw(w, v, 16, asIsPaddedRaw, nil, []int{2, 3, 4, 5, 6, 7}) { + return + } + if v == nil { + w.NullLength() + return + } + w.Length(len(v)) + b := w.ExtendFixed(len(v), 16, true) + if b == nil { + return + } + for _, e := range v { + _ = b[15] + encodePaddedRaw(b[0:16], e) + b = b[16:] + } } func readV95(r *nino.Reader) (v []*Box[int64]) { @@ -28673,13 +28936,13 @@ func readV97(r *nino.Reader) []SimpleStruct { return nil } b := r.Take(n * 12) - if len(b) != n*12 { + if r.Failed() { return nil } var e SimpleStruct v := make([]SimpleStruct, 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) for len(b) >= 12 { - e = decodeSimpleStruct(r, b[:12:12]) + e = decodeSimpleStruct(r, b[0:12]) if r.Failed() { return nil } @@ -28695,12 +28958,13 @@ func writeV97(w *nino.Writer, v []SimpleStruct) { return } w.Length(len(v)) - b := w.ExtendZero(len(v) * 12) - if len(b) != len(v)*12 { + b := w.ExtendFixed(len(v), 12, true) + if b == nil { return } for _, e := range v { - encodeSimpleStruct(b[:12:12], e) + _ = b[11] + encodeSimpleStruct(b[0:12], e) b = b[12:] } } @@ -29626,6 +29890,12 @@ func readV105(r *nino.Reader) NinoTuple5[float64, int64, float64, float32, uint8 return v } +var keyCheck0 = nino.PrepareKeyCheck[string]() + +var keyCheck1 = nino.PrepareKeyCheck[int32]() + +var keyCheck2 = nino.PrepareKeyCheck[nino.NullableSlot[int32]]() + // NinoTuple2 is a ValueTuple or Tuple of 2 items. type NinoTuple2[T1, T2 any] struct { Item1 T1 diff --git a/runtimes/go/collections.go b/runtimes/go/collections.go index a1b717e71..9874c9e81 100644 --- a/runtimes/go/collections.go +++ b/runtimes/go/collections.go @@ -161,26 +161,35 @@ func writeFixed[T any](w *Writer, v []T, size int, encode func(b []byte, e T)) { // an element, whose bytes must be 0 or 1; and decode, for the hosts where the block is not the memory (big-endian // ones) and asIs false (a 32-bit host that aligns an int64 to 4 bytes). Never pass asIs true for a T with pointers. func ReadRaw[T any](r *Reader, size int, asIs bool, bools []int, decode func(r *Reader, b []byte) T) []T { + if v, ok := TryReadRaw[T](r, size, asIs, bools); ok { + return v + } + return readFixed(r, size, decode) +} + +// TryReadRaw is the raw-memory path of [ReadRaw]. When ok is false it leaves the reader untouched so a +// generated caller can decode each element directly on hosts where Go memory does not match the wire. +func TryReadRaw[T any](r *Reader, size int, asIs bool, bools []int) (v []T, ok bool) { var zero T - if !asIs || !littleEndian || int(unsafe.Sizeof(zero)) != size { - return readFixed(r, size, decode) + if !asIs || !littleEndian || size <= 0 || int(unsafe.Sizeof(zero)) != size { + return nil, false } n := r.Length(size) if n < 0 { - return nil + return nil, true } b := r.Take(n * size) if len(b) != n*size { - return nil + return nil, true } if len(bools) != 0 && !rawBools(b, size, bools) { r.Fail(CodeInvalidData, "invalid bool") - return nil + return nil, true } // As many bytes of memory as of data: no more than readFixed's bound. - v := make([]T, n) + v = make([]T, n) copy(unsafe.Slice((*byte)(unsafe.Pointer(unsafe.SliceData(v))), n*size), b) - return v + return v, true } // rawBools reports whether the bytes at each offset of bools in each element (size bytes) of b are 0 or 1: ORed into @@ -221,19 +230,26 @@ func rawBools(b []byte, size int, bools []int) bool { // (padding), which [writeFixed] writes as zeros and so does the block once copied. A bool whose byte is not 0 or 1 // (set through unsafe) is written as 1. func WriteRaw[T any](w *Writer, v []T, size int, asIs bool, bools, pads []int, encode func(b []byte, e T)) { - var zero T - if !asIs || !littleEndian || int(unsafe.Sizeof(zero)) != size { + if !TryWriteRaw(w, v, size, asIs, bools, pads) { writeFixed(w, v, size, encode) - return + } +} + +// TryWriteRaw is the raw-memory path of [WriteRaw]. When it returns false it leaves the writer untouched +// so a generated caller can encode each element directly on hosts where Go memory does not match the wire. +func TryWriteRaw[T any](w *Writer, v []T, size int, asIs bool, bools, pads []int) bool { + var zero T + if !asIs || !littleEndian || size <= 0 || int(unsafe.Sizeof(zero)) != size { + return false } if v == nil { w.NullLength() - return + return true } w.Length(len(v)) - b := w.Extend(len(v) * size) - if len(b) != len(v)*size { - return + b := w.ExtendFixed(len(v), size, false) + if b == nil { + return true } copy(b, unsafe.Slice((*byte)(unsafe.Pointer(unsafe.SliceData(v))), len(v)*size)) if len(pads) != 0 { @@ -242,6 +258,7 @@ func WriteRaw[T any](w *Writer, v []T, size int, asIs bool, bools, pads []int, e if len(bools) != 0 && !rawBools(b, size, bools) { normalizeRawBools(b, size, bools) } + return true } // clearPads sets the bytes at the offsets pads in each element (size bytes) of b to 0. Elements of up to 32 bytes @@ -361,16 +378,21 @@ func (w *Writer) WriteShape(dims ...int) { // CheckUniqueValues returns v, the elements of a set read in the order of the data, unless two of them are equal: then // it fails r with CodeDuplicateKey (as .NET's HashSet and SortedSet do when filled from empty) and returns nil. It -// returns nil for nil and after r failed. Generated code reads the elements with direct calls, then checks them -// once here, as [CheckUniqueKeys] does for a dictionary's keys. Numbers and strings are compared as .NET compares them +// returns nil for nil and after r failed. Numbers and strings are compared as .NET compares them // (a NaN equals every NaN), without a map, and so is a [NullableSlot] of a number, a set of T? (two nulls are equal); // other values as Go compares them (unique.go). func CheckUniqueValues[T comparable](r *Reader, v []T) []T { + return (*KeyCheck[T])(nil).Values(r, v) +} + +// Values checks the elements of a set with c and returns them in their original order. +// It has the same result and error behavior as [CheckUniqueValues]. A nil check discovers the key kind. +func (c *KeyCheck[T]) Values(r *Reader, v []T) []T { if v == nil || r.err != nil { return nil } var e T - if repeated[T](unsafe.Pointer(unsafe.SliceData(v)), len(v), int(unsafe.Sizeof(e)), &r.keys) { + if c.repeated(unsafe.Pointer(unsafe.SliceData(v)), len(v), int(unsafe.Sizeof(e)), &r.keys) { r.Fail(CodeDuplicateKey, "") return nil } @@ -398,14 +420,18 @@ func readUniqueEntries[K comparable, V any](r *Reader, minSize int, readKey func // CheckUniqueKeys returns e, the pairs of a dictionary read in the order of the data, unless two of its keys are equal: // then it fails r with CodeDuplicateKey (as .NET's dictionaries do when filled from empty) and returns nil. It -// returns nil for nil and after r failed. Generated code reads the pairs with direct calls, then checks them once -// here. Keys are compared as [CheckUniqueValues] compares elements. +// returns nil for nil and after r failed. Keys are compared as [CheckUniqueValues] compares elements. func CheckUniqueKeys[K comparable, V any](r *Reader, e []Entry[K, V]) []Entry[K, V] { + return CheckUniqueKeysWith[K, V](r, e, nil) +} + +// CheckUniqueKeysWith is [CheckUniqueKeys] with key metadata prepared before decoding. A nil check discovers the key kind. +func CheckUniqueKeysWith[K comparable, V any](r *Reader, e []Entry[K, V], c *KeyCheck[K]) []Entry[K, V] { if e == nil || r.err != nil { return nil } var pair Entry[K, V] - if repeated[K](unsafe.Pointer(unsafe.SliceData(e)), len(e), int(unsafe.Sizeof(pair)), &r.keys) { + if c.repeated(unsafe.Pointer(unsafe.SliceData(e)), len(e), int(unsafe.Sizeof(pair)), &r.keys) { r.Fail(CodeDuplicateKey, "") return nil } diff --git a/runtimes/go/fuzz_test.go b/runtimes/go/fuzz_test.go index 101ad5222..879dae976 100644 --- a/runtimes/go/fuzz_test.go +++ b/runtimes/go/fuzz_test.go @@ -160,7 +160,7 @@ func fuzzOp(t *testing.T, op byte, r *Reader, w *Writer) { s, ok := r.ReadShape(2+int(r.U8()%3), 4) if ok { items := make([]int32, s.Total) - readPrimitivesInto(r, items) + ReadPrimitivesInto(r, items) } case 19: v := r.Guid() diff --git a/runtimes/go/internal/generated/nino_types.go b/runtimes/go/internal/generated/nino_types.go index b009cda01..29c256730 100644 --- a/runtimes/go/internal/generated/nino_types.go +++ b/runtimes/go/internal/generated/nino_types.go @@ -12449,7 +12449,7 @@ func readV16(r *nino.Reader) []nino.Entry[string, DictTree] { } v = append(v, e) } - return nino.CheckUniqueKeys(r, v) + return nino.CheckUniqueKeysWith(r, v, &keyCheck0) } func writeV16(w *nino.Writer, v []nino.Entry[string, DictTree]) { @@ -12481,7 +12481,7 @@ func writeV17(w *nino.Writer, v []Tree) { } func readV18(r *nino.Reader) []nino.NullableSlot[int32] { - return nino.CheckUniqueValues(r, nino.ReadNullableSlots[int32](r)) + return keyCheck1.Values(r, nino.ReadNullableSlots[int32](r)) } func readV19(r *nino.Reader) []nino.NullableSlot[Vec2] { @@ -12490,13 +12490,13 @@ func readV19(r *nino.Reader) []nino.NullableSlot[Vec2] { return nil } b := r.Take(n * 12) - if len(b) != n*12 { + if r.Failed() { return nil } var e nino.NullableSlot[Vec2] v := make([]nino.NullableSlot[Vec2], 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) for len(b) >= 12 { - e = decodeV90(r, b[:12:12]) + e = decodeV90(r, b[0:12]) if r.Failed() { return nil } @@ -12512,12 +12512,13 @@ func writeV19(w *nino.Writer, v []nino.NullableSlot[Vec2]) { return } w.Length(len(v)) - b := w.ExtendZero(len(v) * 12) - if len(b) != len(v)*12 { + b := w.ExtendFixed(len(v), 12, true) + if b == nil { return } for _, e := range v { - encodeV90(b[:12:12], e) + _ = b[11] + encodeV90(b[0:12], e) b = b[12:] } } @@ -12537,7 +12538,7 @@ func readV20(r *nino.Reader) []nino.Entry[int32, *float64] { } v = append(v, e) } - return nino.CheckUniqueKeys(r, v) + return nino.CheckUniqueKeysWith(r, v, &keyCheck2) } func writeV20(w *nino.Writer, v []nino.Entry[int32, *float64]) { @@ -12644,13 +12645,13 @@ func readV25(r *nino.Reader) []HoldsTuples { return nil } b := r.Take(n * 48) - if len(b) != n*48 { + if r.Failed() { return nil } var e HoldsTuples v := make([]HoldsTuples, 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) for len(b) >= 48 { - e = decodeHoldsTuples(r, b[:48:48]) + e = decodeHoldsTuples(r, b[0:48]) if r.Failed() { return nil } @@ -12666,13 +12667,13 @@ func readV26(r *nino.Reader) []HoldsPairs { return nil } b := r.Take(n * 40) - if len(b) != n*40 { + if r.Failed() { return nil } var e HoldsPairs v := make([]HoldsPairs, 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) for len(b) >= 40 { - e = decodeHoldsPairs(r, b[:40:40]) + e = decodeHoldsPairs(r, b[0:40]) if r.Failed() { return nil } @@ -12688,12 +12689,13 @@ func writeV25(w *nino.Writer, v []HoldsTuples) { return } w.Length(len(v)) - b := w.ExtendZero(len(v) * 48) - if len(b) != len(v)*48 { + b := w.ExtendFixed(len(v), 48, true) + if b == nil { return } for _, e := range v { - encodeHoldsTuples(b[:48:48], e) + _ = b[47] + encodeHoldsTuples(b[0:48], e) b = b[48:] } } @@ -12704,18 +12706,40 @@ func writeV26(w *nino.Writer, v []HoldsPairs) { return } w.Length(len(v)) - b := w.ExtendZero(len(v) * 40) - if len(b) != len(v)*40 { + b := w.ExtendFixed(len(v), 40, true) + if b == nil { return } for _, e := range v { - encodeHoldsPairs(b[:40:40], e) + _ = b[39] + encodeHoldsPairs(b[0:40], e) b = b[40:] } } func readV27(r *nino.Reader) []HoldsWide { - return nino.ReadRaw(r, 48, asIsHoldsWide, nil, decodeHoldsWide) + if v, ok := nino.TryReadRaw[HoldsWide](r, 48, asIsHoldsWide, nil); ok { + return v + } + n := r.Length(48) + if n < 0 { + return nil + } + b := r.Take(n * 48) + if r.Failed() { + return nil + } + var e HoldsWide + v := make([]HoldsWide, 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) + for len(b) >= 48 { + e = decodeHoldsWide(r, b[0:48]) + if r.Failed() { + return nil + } + v = append(v, e) + b = b[48:] + } + return v } func readV28(r *nino.Reader) []nino.NullableSlot[nino.Int128] { @@ -12724,13 +12748,13 @@ func readV28(r *nino.Reader) []nino.NullableSlot[nino.Int128] { return nil } b := r.Take(n * 32) - if len(b) != n*32 { + if r.Failed() { return nil } var e nino.NullableSlot[nino.Int128] v := make([]nino.NullableSlot[nino.Int128], 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) for len(b) >= 32 { - e = decodeV93(r, b[:32:32]) + e = decodeV93(r, b[0:32]) if r.Failed() { return nil } @@ -12741,7 +12765,23 @@ func readV28(r *nino.Reader) []nino.NullableSlot[nino.Int128] { } func writeV27(w *nino.Writer, v []HoldsWide) { - nino.WriteRaw(w, v, 48, asIsHoldsWide, nil, []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, encodeHoldsWide) + if nino.TryWriteRaw(w, v, 48, asIsHoldsWide, nil, []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}) { + return + } + if v == nil { + w.NullLength() + return + } + w.Length(len(v)) + b := w.ExtendFixed(len(v), 48, true) + if b == nil { + return + } + for _, e := range v { + _ = b[47] + encodeHoldsWide(b[0:48], e) + b = b[48:] + } } func writeV28(w *nino.Writer, v []nino.NullableSlot[nino.Int128]) { @@ -12750,12 +12790,13 @@ func writeV28(w *nino.Writer, v []nino.NullableSlot[nino.Int128]) { return } w.Length(len(v)) - b := w.ExtendZero(len(v) * 32) - if len(b) != len(v)*32 { + b := w.ExtendFixed(len(v), 32, true) + if b == nil { return } for _, e := range v { - encodeV93(b[:32:32], e) + _ = b[31] + encodeV93(b[0:32], e) b = b[32:] } } @@ -12766,13 +12807,13 @@ func readV29(r *nino.Reader) []HoldsNullables { return nil } b := r.Take(n * 40) - if len(b) != n*40 { + if r.Failed() { return nil } var e HoldsNullables v := make([]HoldsNullables, 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) for len(b) >= 40 { - e = decodeHoldsNullables(r, b[:40:40]) + e = decodeHoldsNullables(r, b[0:40]) if r.Failed() { return nil } @@ -12788,12 +12829,13 @@ func writeV29(w *nino.Writer, v []HoldsNullables) { return } w.Length(len(v)) - b := w.ExtendZero(len(v) * 40) - if len(b) != len(v)*40 { + b := w.ExtendFixed(len(v), 40, true) + if b == nil { return } for _, e := range v { - encodeHoldsNullables(b[:40:40], e) + _ = b[39] + encodeHoldsNullables(b[0:40], e) b = b[40:] } } @@ -12804,13 +12846,13 @@ func readV30(r *nino.Reader) []HoldsOffset { return nil } b := r.Take(n * 24) - if len(b) != n*24 { + if r.Failed() { return nil } var e HoldsOffset v := make([]HoldsOffset, 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) for len(b) >= 24 { - e = decodeHoldsOffset(r, b[:24:24]) + e = decodeHoldsOffset(r, b[0:24]) if r.Failed() { return nil } @@ -12826,12 +12868,13 @@ func writeV30(w *nino.Writer, v []HoldsOffset) { return } w.Length(len(v)) - b := w.ExtendZero(len(v) * 24) - if len(b) != len(v)*24 { + b := w.ExtendFixed(len(v), 24, true) + if b == nil { return } for _, e := range v { - encodeHoldsOffset(b[:24:24], e) + _ = b[23] + encodeHoldsOffset(b[0:24], e) b = b[24:] } } @@ -12852,7 +12895,7 @@ func writeV31(w *nino.Writer, v *int64) { } func readV32(r *nino.Reader) []int32 { - return nino.CheckUniqueValues(r, nino.ReadPrimitives[int32](r)) + return keyCheck2.Values(r, nino.ReadPrimitives[int32](r)) } func readintoV33(r *nino.Reader, p *[]*string) { @@ -12938,7 +12981,7 @@ func readV35(r *nino.Reader) []nino.Entry[string, *string] { } v = append(v, e) } - return nino.CheckUniqueKeys(r, v) + return nino.CheckUniqueKeysWith(r, v, &keyCheck0) } func readV36(r *nino.Reader) []nino.Entry[string, *Point] { @@ -12956,7 +12999,7 @@ func readV36(r *nino.Reader) []nino.Entry[string, *Point] { } v = append(v, e) } - return nino.CheckUniqueKeys(r, v) + return nino.CheckUniqueKeysWith(r, v, &keyCheck0) } func readV37(r *nino.Reader) []nino.Entry[int32, []*string] { @@ -12974,7 +13017,7 @@ func readV37(r *nino.Reader) []nino.Entry[int32, []*string] { } v = append(v, e) } - return nino.CheckUniqueKeys(r, v) + return nino.CheckUniqueKeysWith(r, v, &keyCheck2) } func readV38(r *nino.Reader) []nino.Entry[int32, *string] { @@ -12992,7 +13035,7 @@ func readV38(r *nino.Reader) []nino.Entry[int32, *string] { } v = append(v, e) } - return nino.CheckUniqueKeys(r, v) + return nino.CheckUniqueKeysWith(r, v, &keyCheck2) } func readV39(r *nino.Reader) []nino.Entry[string, int32] { @@ -13010,7 +13053,7 @@ func readV39(r *nino.Reader) []nino.Entry[string, int32] { } v = append(v, e) } - return nino.CheckUniqueKeys(r, v) + return nino.CheckUniqueKeysWith(r, v, &keyCheck0) } func readintoV40(r *nino.Reader, p *[][]int32) { @@ -13042,11 +13085,9 @@ func readV41(r *nino.Reader) *NinoGrid[int32] { if g == nil { return nil } - for i := range g.Items { - g.Items[i] = r.I32() - if r.Failed() { - return nil - } + nino.ReadPrimitivesInto(r, g.Items) + if r.Failed() { + return nil } return g } @@ -13152,9 +13193,7 @@ func writeV41(w *nino.Writer, v *NinoGrid[int32]) { if !writeGrid(w, v, 2) { return } - for _, e := range v.Items { - w.I32(e) - } + nino.WritePrimitivesRaw(w, v.Items) } func writeV42(w *nino.Writer, v *NinoGrid[*string]) { @@ -13332,11 +13371,17 @@ func readV48(r *nino.Reader) *NinoGrid[nino.NullableSlot[int32]] { if g == nil { return nil } + b := r.Take(len(g.Items) * 8) + if r.Failed() { + return nil + } for i := range g.Items { - g.Items[i] = readV94(r) + _ = b[7] + g.Items[i] = decodeV94(r, b[0:8]) if r.Failed() { return nil } + b = b[8:] } return g } @@ -13345,8 +13390,14 @@ func writeV48(w *nino.Writer, v *NinoGrid[nino.NullableSlot[int32]]) { if !writeGrid(w, v, 2) { return } + b := w.ExtendFixed(len(v.Items), 8, true) + if b == nil { + return + } for _, e := range v.Items { - writeV94(w, e) + _ = b[7] + encodeV94(b[0:8], e) + b = b[8:] } } @@ -13388,13 +13439,13 @@ func readV52(r *nino.Reader) []nino.NinoNullable[nino.Decimal] { return nil } b := r.Take(n * 32) - if len(b) != n*32 { + if r.Failed() { return nil } var e nino.NinoNullable[nino.Decimal] v := make([]nino.NinoNullable[nino.Decimal], 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) for len(b) >= 32 { - e = decodeV13(r, b[:32:32]) + e = decodeV13(r, b[0:32]) if r.Failed() { return nil } @@ -13410,13 +13461,13 @@ func readV53(r *nino.Reader) []nino.NinoNullable[nino.Guid] { return nil } b := r.Take(n * 32) - if len(b) != n*32 { + if r.Failed() { return nil } var e nino.NinoNullable[nino.Guid] v := make([]nino.NinoNullable[nino.Guid], 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) for len(b) >= 32 { - e = decodeV50(r, b[:32:32]) + e = decodeV50(r, b[0:32]) if r.Failed() { return nil } @@ -13432,13 +13483,13 @@ func readV54(r *nino.Reader) []nino.NinoNullable[Padded] { return nil } b := r.Take(n * 32) - if len(b) != n*32 { + if r.Failed() { return nil } var e nino.NinoNullable[Padded] v := make([]nino.NinoNullable[Padded], 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) for len(b) >= 32 { - e = decodeV51(r, b[:32:32]) + e = decodeV51(r, b[0:32]) if r.Failed() { return nil } @@ -13453,17 +13504,21 @@ func readV55(r *nino.Reader) []nino.Entry[int32, nino.NinoNullable[nino.Decimal] if n < 0 { return nil } + b := r.Take(n * 36) + if r.Failed() { + return nil + } var e nino.Entry[int32, nino.NinoNullable[nino.Decimal]] v := make([]nino.Entry[int32, nino.NinoNullable[nino.Decimal]], 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) - for range n { - k := r.I32() - e = nino.Entry[int32, nino.NinoNullable[nino.Decimal]]{Key: k, Value: readV13(r)} + for len(b) >= 36 { + e = nino.Entry[int32, nino.NinoNullable[nino.Decimal]]{Key: int32(le.Uint32(b)), Value: decodeV13(r, b[4:36])} if r.Failed() { return nil } v = append(v, e) + b = b[36:] } - return nino.CheckUniqueKeys(r, v) + return nino.CheckUniqueKeysWith(r, v, &keyCheck2) } func readV56(r *nino.Reader) []NinoNullableFieldsType { @@ -13472,13 +13527,13 @@ func readV56(r *nino.Reader) []NinoNullableFieldsType { return nil } b := r.Take(n * 48) - if len(b) != n*48 { + if r.Failed() { return nil } var e NinoNullableFieldsType v := make([]NinoNullableFieldsType, 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) for len(b) >= 48 { - e = decodeNinoNullableFieldsType(r, b[:48:48]) + e = decodeNinoNullableFieldsType(r, b[0:48]) if r.Failed() { return nil } @@ -13518,12 +13573,13 @@ func writeV52(w *nino.Writer, v []nino.NinoNullable[nino.Decimal]) { return } w.Length(len(v)) - b := w.ExtendZero(len(v) * 32) - if len(b) != len(v)*32 { + b := w.ExtendFixed(len(v), 32, true) + if b == nil { return } for _, e := range v { - encodeV13(b[:32:32], e) + _ = b[31] + encodeV13(b[0:32], e) b = b[32:] } } @@ -13534,12 +13590,13 @@ func writeV53(w *nino.Writer, v []nino.NinoNullable[nino.Guid]) { return } w.Length(len(v)) - b := w.ExtendZero(len(v) * 32) - if len(b) != len(v)*32 { + b := w.ExtendFixed(len(v), 32, true) + if b == nil { return } for _, e := range v { - encodeV50(b[:32:32], e) + _ = b[31] + encodeV50(b[0:32], e) b = b[32:] } } @@ -13550,12 +13607,13 @@ func writeV54(w *nino.Writer, v []nino.NinoNullable[Padded]) { return } w.Length(len(v)) - b := w.ExtendZero(len(v) * 32) - if len(b) != len(v)*32 { + b := w.ExtendFixed(len(v), 32, true) + if b == nil { return } for _, e := range v { - encodeV51(b[:32:32], e) + _ = b[31] + encodeV51(b[0:32], e) b = b[32:] } } @@ -13566,9 +13624,16 @@ func writeV55(w *nino.Writer, v []nino.Entry[int32, nino.NinoNullable[nino.Decim return } w.Length(len(v)) - for _, e := range v { - w.I32(e.Key) - writeV13(w, e.Value) + b := w.ExtendFixed(len(v), 36, true) + if b == nil { + return + } + for i := range v { + e := &v[i] + _ = b[35] + le.PutUint32(b, uint32(e.Key)) + encodeV13(b[4:36], e.Value) + b = b[36:] } } @@ -13578,18 +13643,19 @@ func writeV56(w *nino.Writer, v []NinoNullableFieldsType) { return } w.Length(len(v)) - b := w.ExtendZero(len(v) * 48) - if len(b) != len(v)*48 { + b := w.ExtendFixed(len(v), 48, true) + if b == nil { return } for _, e := range v { - encodeNinoNullableFieldsType(b[:48:48], e) + _ = b[47] + encodeNinoNullableFieldsType(b[0:48], e) b = b[48:] } } func readV57(r *nino.Reader) []nino.NullableSlot[int64] { - return nino.CheckUniqueValues(r, nino.ReadNullableSlots[int64](r)) + return keyCheck3.Values(r, nino.ReadNullableSlots[int64](r)) } func readV58(r *nino.Reader) *NinoGrid[nino.NullableSlot[Padded]] { @@ -13597,11 +13663,17 @@ func readV58(r *nino.Reader) *NinoGrid[nino.NullableSlot[Padded]] { if g == nil { return nil } + b := r.Take(len(g.Items) * 24) + if r.Failed() { + return nil + } for i := range g.Items { - g.Items[i] = readV95(r) + _ = b[23] + g.Items[i] = decodeV95(r, b[0:24]) if r.Failed() { return nil } + b = b[24:] } return g } @@ -13645,7 +13717,7 @@ func readV60(r *nino.Reader) []nino.Entry[int32, *int64] { } v = append(v, e) } - return nino.CheckUniqueKeys(r, v) + return nino.CheckUniqueKeysWith(r, v, &keyCheck2) } func readintoV61(r *nino.Reader, p *[]nino.Entry[int32, *int32]) { @@ -13676,8 +13748,14 @@ func writeV58(w *nino.Writer, v *NinoGrid[nino.NullableSlot[Padded]]) { if !writeGrid(w, v, 2) { return } + b := w.ExtendFixed(len(v.Items), 24, true) + if b == nil { + return + } for _, e := range v.Items { - writeV95(w, e) + _ = b[23] + encodeV95(b[0:24], e) + b = b[24:] } } @@ -13777,13 +13855,13 @@ func readV69(r *nino.Reader) []nino.NullableSlot[Padded] { return nil } b := r.Take(n * 24) - if len(b) != n*24 { + if r.Failed() { return nil } var e nino.NullableSlot[Padded] v := make([]nino.NullableSlot[Padded], 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) for len(b) >= 24 { - e = decodeV95(r, b[:24:24]) + e = decodeV95(r, b[0:24]) if r.Failed() { return nil } @@ -13808,7 +13886,7 @@ func readV70(r *nino.Reader) []nino.Entry[int32, *int32] { } v = append(v, e) } - return nino.CheckUniqueKeys(r, v) + return nino.CheckUniqueKeysWith(r, v, &keyCheck2) } func writeV62(w *nino.Writer, v *float64) { @@ -13866,12 +13944,13 @@ func writeV69(w *nino.Writer, v []nino.NullableSlot[Padded]) { return } w.Length(len(v)) - b := w.ExtendZero(len(v) * 24) - if len(b) != len(v)*24 { + b := w.ExtendFixed(len(v), 24, true) + if b == nil { return } for _, e := range v { - encodeV95(b[:24:24], e) + _ = b[23] + encodeV95(b[0:24], e) b = b[24:] } } @@ -13889,11 +13968,48 @@ func writeV70(w *nino.Writer, v []nino.Entry[int32, *int32]) { } func readV71(r *nino.Reader) []Padded { - return nino.ReadRaw(r, 16, asIsPadded, nil, decodePadded) + if v, ok := nino.TryReadRaw[Padded](r, 16, asIsPadded, nil); ok { + return v + } + n := r.Length(16) + if n < 0 { + return nil + } + b := r.Take(n * 16) + if r.Failed() { + return nil + } + var e Padded + v := make([]Padded, 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) + for len(b) >= 16 { + e = decodePadded(r, b[0:16]) + if r.Failed() { + return nil + } + v = append(v, e) + b = b[16:] + } + return v } func writeV71(w *nino.Writer, v []Padded) { - nino.WriteRaw(w, v, 16, asIsPadded, nil, []int{1, 2, 3, 4, 5, 6, 7}, encodePadded) + if nino.TryWriteRaw(w, v, 16, asIsPadded, nil, []int{1, 2, 3, 4, 5, 6, 7}) { + return + } + if v == nil { + w.NullLength() + return + } + w.Length(len(v)) + b := w.ExtendFixed(len(v), 16, true) + if b == nil { + return + } + for _, e := range v { + _ = b[15] + encodePadded(b[0:16], e) + b = b[16:] + } } func readV72(r *nino.Reader) []RawOptional { @@ -13902,13 +14018,13 @@ func readV72(r *nino.Reader) []RawOptional { return nil } b := r.Take(n * 56) - if len(b) != n*56 { + if r.Failed() { return nil } var e RawOptional v := make([]RawOptional, 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) for len(b) >= 56 { - e = decodeRawOptional(r, b[:56:56]) + e = decodeRawOptional(r, b[0:56]) if r.Failed() { return nil } @@ -13932,12 +14048,13 @@ func writeV72(w *nino.Writer, v []RawOptional) { return } w.Length(len(v)) - b := w.ExtendZero(len(v) * 56) - if len(b) != len(v)*56 { + b := w.ExtendFixed(len(v), 56, true) + if b == nil { return } for _, e := range v { - encodeRawOptional(b[:56:56], e) + _ = b[55] + encodeRawOptional(b[0:56], e) b = b[56:] } } @@ -13950,11 +14067,53 @@ func writeV73(w *nino.Writer, v *RawOptional) { } func readV74(r *nino.Reader) []Vec2 { - return nino.ReadRaw(r, 8, asIsVec2, nil, decodeVec2) + if v, ok := nino.TryReadRaw[Vec2](r, 8, asIsVec2, nil); ok { + return v + } + n := r.Length(8) + if n < 0 { + return nil + } + b := r.Take(n * 8) + if r.Failed() { + return nil + } + var e Vec2 + v := make([]Vec2, 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) + for len(b) >= 8 { + e = decodeVec2(r, b[0:8]) + if r.Failed() { + return nil + } + v = append(v, e) + b = b[8:] + } + return v } func readV75(r *nino.Reader) []Mixed { - return nino.ReadRaw(r, 12, asIsMixed, nil, decodeMixed) + if v, ok := nino.TryReadRaw[Mixed](r, 12, asIsMixed, nil); ok { + return v + } + n := r.Length(12) + if n < 0 { + return nil + } + b := r.Take(n * 12) + if r.Failed() { + return nil + } + var e Mixed + v := make([]Mixed, 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) + for len(b) >= 12 { + e = decodeMixed(r, b[0:12]) + if r.Failed() { + return nil + } + v = append(v, e) + b = b[12:] + } + return v } func readintoV76(r *nino.Reader, p *[]Label) { @@ -14006,11 +14165,43 @@ func readV79(r *nino.Reader) nino.Entry[*string, Vec2] { } func writeV74(w *nino.Writer, v []Vec2) { - nino.WriteRaw(w, v, 8, asIsVec2, nil, nil, encodeVec2) + if nino.TryWriteRaw(w, v, 8, asIsVec2, nil, nil) { + return + } + if v == nil { + w.NullLength() + return + } + w.Length(len(v)) + b := w.ExtendFixed(len(v), 8, true) + if b == nil { + return + } + for _, e := range v { + _ = b[7] + encodeVec2(b[0:8], e) + b = b[8:] + } } func writeV75(w *nino.Writer, v []Mixed) { - nino.WriteRaw(w, v, 12, asIsMixed, nil, []int{1, 9, 10, 11}, encodeMixed) + if nino.TryWriteRaw(w, v, 12, asIsMixed, nil, []int{1, 9, 10, 11}) { + return + } + if v == nil { + w.NullLength() + return + } + w.Length(len(v)) + b := w.ExtendFixed(len(v), 12, true) + if b == nil { + return + } + for _, e := range v { + _ = b[11] + encodeMixed(b[0:12], e) + b = b[12:] + } } func writeV76(w *nino.Writer, v []Label) { @@ -14118,7 +14309,7 @@ func readV82(r *nino.Reader) []nino.Entry[int32, *TrackedNode] { } v = append(v, e) } - return nino.CheckUniqueKeys(r, v) + return nino.CheckUniqueKeysWith(r, v, &keyCheck2) } func writeV81(w *nino.Writer, v []*TrackedNode) { @@ -14329,7 +14520,7 @@ func readV88(r *nino.Reader) []nino.Entry[string, Animal] { } v = append(v, e) } - return nino.CheckUniqueKeys(r, v) + return nino.CheckUniqueKeysWith(r, v, &keyCheck0) } func writeV86(w *nino.Writer, v []Animal) { @@ -14473,17 +14664,20 @@ func encodeV93(b []byte, v nino.NullableSlot[nino.Int128]) { } } -func readV94(r *nino.Reader) nino.NullableSlot[int32] { - var v nino.NullableSlot[int32] - if b := r.Take(8); len(b) == 8 { - v = decodeV94(r, b) +func decodeV94(r *nino.Reader, b []byte) nino.NullableSlot[int32] { + _ = b[7] + if !r.BoolAt(b[0]) { + return nino.NullableSlot[int32]{} } - return v + return nino.NullableSlot[int32]{HasValue: true, Value: int32(le.Uint32(b[4:]))} } -func writeV94(w *nino.Writer, v nino.NullableSlot[int32]) { - if b := w.ExtendZero(8); len(b) == 8 { - encodeV94(b, v) +func encodeV94(b []byte, v nino.NullableSlot[int32]) { + _ = b[7] + if v.HasValue { + b[0] = 1 + x := v.Value + le.PutUint32(b[4:], uint32(x)) } } @@ -14538,12 +14732,12 @@ func encodeV51(b []byte, v nino.NinoNullable[Padded]) { } } -func readV95(r *nino.Reader) nino.NullableSlot[Padded] { - var v nino.NullableSlot[Padded] - if b := r.Take(24); len(b) == 24 { - v = decodeV95(r, b) +func decodeV95(r *nino.Reader, b []byte) nino.NullableSlot[Padded] { + _ = b[23] + if !r.BoolAt(b[0]) { + return nino.NullableSlot[Padded]{} } - return v + return nino.NullableSlot[Padded]{HasValue: true, Value: decodePadded(r, b[8:24])} } func readV96(r *nino.Reader) nino.Entry[int32, *int32] { @@ -14553,9 +14747,12 @@ func readV96(r *nino.Reader) nino.Entry[int32, *int32] { return v } -func writeV95(w *nino.Writer, v nino.NullableSlot[Padded]) { - if b := w.ExtendZero(24); len(b) == 24 { - encodeV95(b, v) +func encodeV95(b []byte, v nino.NullableSlot[Padded]) { + _ = b[23] + if v.HasValue { + b[0] = 1 + x := v.Value + encodePadded(b[8:24], x) } } @@ -14568,27 +14765,10 @@ func readV97(r *nino.Reader) E16 { return E16(r.I16()) } -func decodeV95(r *nino.Reader, b []byte) nino.NullableSlot[Padded] { - _ = b[23] - if !r.BoolAt(b[0]) { - return nino.NullableSlot[Padded]{} - } - return nino.NullableSlot[Padded]{HasValue: true, Value: decodePadded(r, b[8:24])} -} - func writeV97(w *nino.Writer, v E16) { w.I16(int16(v)) } -func encodeV95(b []byte, v nino.NullableSlot[Padded]) { - _ = b[23] - if v.HasValue { - b[0] = 1 - x := v.Value - encodePadded(b[8:24], x) - } -} - func readintoV84(r *nino.Reader, p *[]UnionTree) { n := r.Length(4) if n < 0 { @@ -14630,22 +14810,13 @@ func readV92(r *nino.Reader) nino.Entry[*string, *int32] { return v } -func decodeV94(r *nino.Reader, b []byte) nino.NullableSlot[int32] { - _ = b[7] - if !r.BoolAt(b[0]) { - return nino.NullableSlot[int32]{} - } - return nino.NullableSlot[int32]{HasValue: true, Value: int32(le.Uint32(b[4:]))} -} +var keyCheck0 = nino.PrepareKeyCheck[string]() -func encodeV94(b []byte, v nino.NullableSlot[int32]) { - _ = b[7] - if v.HasValue { - b[0] = 1 - x := v.Value - le.PutUint32(b[4:], uint32(x)) - } -} +var keyCheck1 = nino.PrepareKeyCheck[nino.NullableSlot[int32]]() + +var keyCheck2 = nino.PrepareKeyCheck[int32]() + +var keyCheck3 = nino.PrepareKeyCheck[nino.NullableSlot[int64]]() // NinoTuple2 is a ValueTuple or Tuple of 2 items. type NinoTuple2[T1, T2 any] struct { diff --git a/runtimes/go/internal/generated/shapes/nino_types.go b/runtimes/go/internal/generated/shapes/nino_types.go index 2a824d619..cbe24575a 100644 --- a/runtimes/go/internal/generated/shapes/nino_types.go +++ b/runtimes/go/internal/generated/shapes/nino_types.go @@ -480,6 +480,7 @@ func writeForest(w *nino.Writer, v Forest) { var ( basedIntClass nino.Class[BasedInt] emptyClass nino.Class[Empty] + fixedCollectionsClass nino.Class[FixedCollections] floatKeysClass nino.Class[FloatKeys] forestHolderClass nino.Class[ForestHolder] holderClass nino.Class[Holder] @@ -544,6 +545,7 @@ var ( func init() { basedIntClass = nino.Class[BasedInt]{Read: readBasedIntBody, Write: writeBasedIntBody, Deferrable: true} emptyClass = nino.Class[Empty]{Read: readEmptyBody, Write: writeEmptyBody, Deferrable: true} + fixedCollectionsClass = nino.Class[FixedCollections]{Read: readFixedCollectionsBody, Write: writeFixedCollectionsBody, Deferrable: true} floatKeysClass = nino.Class[FloatKeys]{Read: readFloatKeysBody, Write: writeFloatKeysBody, Deferrable: true} forestHolderClass = nino.Class[ForestHolder]{Read: readForestHolderBody, Write: writeForestHolderBody, Deferrable: true} holderClass = nino.Class[Holder]{Read: readHolderBody, Write: writeHolderBody, Deferrable: true} @@ -741,7 +743,7 @@ func (c *bagCodec[T]) readD1(r *nino.Reader) []nino.Entry[string, T] { } v = append(v, e) } - return nino.CheckUniqueKeys(r, v) + return nino.CheckUniqueKeysWith(r, v, &keyCheck0) } func (c *bagCodec[T]) writeD1(w *nino.Writer, v []nino.Entry[string, T]) { @@ -1030,6 +1032,110 @@ func readEmptyBody(r *nino.Reader, v *Empty) { func writeEmptyBody(w *nino.Writer, v *Empty) { } +// FixedCollections is `Shapes.FixedCollections`. +type FixedCollections struct { + Ids []nino.Entry[nino.Guid, Marked] `nino:"0" json:"ids" yaml:"ids"` + UniqueIds []nino.Guid `nino:"1" json:"uniqueIds" yaml:"uniqueIds"` + Grid *NinoGrid[uint8] `nino:"2" json:"grid" yaml:"grid"` + Pairs []nino.Entry[int32, int64] `nino:"3" json:"pairs" yaml:"pairs"` + Offsets []nino.DateTimeOffset `nino:"4" json:"offsets" yaml:"offsets"` +} + +func (FixedCollections) NinoLayout() string { + return "format=Positional; header=Presence; trackReferences=false; raw=false; id=0x9B5DCD24; deferrable=true; members=Ids:System.Collections.Generic.Dictionary:map(raw(16),raw(8){Id:int@0:raw(4),On:bool@4:raw(1),Kind:byte@5:raw(1),Code:short@6:raw(2)});UniqueIds:System.Collections.Generic.HashSet:seq(raw(16));Grid:byte[,]:grid(2,raw(1));Pairs:System.Collections.Generic.Dictionary:map(raw(4),raw(8));Offsets:System.DateTimeOffset[]:seq(datetimeoffset)" +} + +func (FixedCollections) NinoTypeName() string { + return "Shapes.FixedCollections" +} + +func (*FixedCollections) NinoTypeID() int32 { + return -1688351452 +} + +func ReadFixedCollections(r *nino.Reader) *FixedCollections { + if !r.Present() { + return nil + } + v := new(FixedCollections) + if d, ok := r.EnterBody(); ok { + readFixedCollectionsBody(r, v) + r.ExitBody(d) + } else { + nino.ReadClassInto(r, v, &fixedCollectionsClass) + } + return v +} + +func WriteFixedCollections(w *nino.Writer, v *FixedCollections) { + if v == nil { + w.U8(0) + return + } + w.U8(1) + if d, ok := w.EnterBody(); ok { + writeFixedCollectionsBody(w, v) + w.ExitBody(d) + } else { + nino.WriteClass(w, v, &fixedCollectionsClass) + } +} + +// ReadFixedCollectionsInto reads a value into *v, the object it points to read in place (DeserializeInto). +func ReadFixedCollectionsInto(r *nino.Reader, v **FixedCollections) { + if !r.Present() { + *v = nil + return + } + if *v == nil { + *v = new(FixedCollections) + } + if d, ok := r.EnterBody(); ok { + readFixedCollectionsBody(r, *v) + r.ExitBody(d) + } else { + nino.ReadClassInto(r, *v, &fixedCollectionsClass) + } +} + +// readFixedCollectionsClass reads the body of a FixedCollections (after its type id) into a new instance. +func readFixedCollectionsClass(r *nino.Reader) *FixedCollections { + v := new(FixedCollections) + if d, ok := r.EnterBody(); ok { + readFixedCollectionsBody(r, v) + r.ExitBody(d) + } else { + nino.ReadClassInto(r, v, &fixedCollectionsClass) + } + return v +} + +// writeFixedCollectionsClass writes the body of v (not nil, after its type id). +func writeFixedCollectionsClass(w *nino.Writer, v *FixedCollections) { + if d, ok := w.EnterBody(); ok { + writeFixedCollectionsBody(w, v) + w.ExitBody(d) + } else { + nino.WriteClass(w, v, &fixedCollectionsClass) + } +} + +func readFixedCollectionsBody(r *nino.Reader, v *FixedCollections) { + v.Ids = readV14(r) + v.UniqueIds = readV15(r) + v.Grid = readV16(r) + v.Pairs = nino.ReadPrimitiveEntries[int32, int64](r) + v.Offsets = readV17(r) +} + +func writeFixedCollectionsBody(w *nino.Writer, v *FixedCollections) { + writeV14(w, v.Ids) + writeV15(w, v.UniqueIds) + writeV16(w, v.Grid) + nino.WritePrimitiveEntries[int32, int64](w, v.Pairs) + writeV17(w, v.Offsets) +} + // FloatKeys is `Shapes.FloatKeys`. type FloatKeys struct { Map []nino.Entry[float32, int32] `nino:"0" json:"map" yaml:"map"` @@ -1339,36 +1445,36 @@ func writeHolderClass(w *nino.Writer, v *Holder) { func readHolderBody(r *nino.Reader, v *Holder) { ReadIThingInto(r, &v.Thing) - readintoV14(r, &v.Things) + readintoV18(r, &v.Things) ReadRecursiveInto(r, &v.Tree) ReadOuterInnerInto(r, &v.Inner) ReadShapesLeftItemInto(r, &v.LeftItem) ReadShapesRightItemInto(r, &v.RightItem) - v.Flags = readV15(r) - v.Gaps = readV16(r) + v.Flags = readV19(r) + v.Gaps = readV20(r) v.Names = readV9(r) v.Tags = readV13(r) - v.Utf8Tags = readV17(r) + v.Utf8Tags = readV21(r) v.Pair = readV10(r) - v.Entry = readV18(r) + v.Entry = readV22(r) v.Maybe = readV11(r) ReadKeywordsInto(r, &v.Keywords) } func writeHolderBody(w *nino.Writer, v *Holder) { WriteIThing(w, v.Thing) - writeV14(w, v.Things) + writeV18(w, v.Things) WriteRecursive(w, v.Tree) WriteOuterInner(w, v.Inner) WriteShapesLeftItem(w, v.LeftItem) WriteShapesRightItem(w, v.RightItem) - writeV15(w, v.Flags) - writeV16(w, v.Gaps) + writeV19(w, v.Flags) + writeV20(w, v.Gaps) writeV9(w, v.Names) writeV13(w, v.Tags) - writeV17(w, v.Utf8Tags) + writeV21(w, v.Utf8Tags) writeV10(w, v.Pair) - writeV18(w, v.Entry) + writeV22(w, v.Entry) writeV11(w, v.Maybe) WriteKeywords(w, v.Keywords) } @@ -1460,12 +1566,12 @@ func writeHostHolderClass(w *nino.Writer, v *HostHolder) { func readHostHolderBody(r *nino.Reader, v *HostHolder) { v.Leaves = readHostLeaves(r) - v.Gaps = readV19(r) + v.Gaps = readV23(r) } func writeHostHolderBody(w *nino.Writer, v *HostHolder) { writeHostLeaves(w, v.Leaves) - writeV19(w, v.Gaps) + writeV23(w, v.Gaps) } // IThing is a value of a slot declared as `Shapes.IThing`. @@ -1873,7 +1979,7 @@ func ReadMeasure(r *nino.Reader) Measure { r.Fail(nino.CodeInvalidData, "a union case without a value") } case -1803246716: - if value := readV20(r); value != nil { + if value := readV24(r); value != nil { v = MeasureListString{Value: value} } else { r.Fail(nino.CodeInvalidData, "a union case without a value") @@ -1930,7 +2036,7 @@ func WriteMeasure(w *nino.Writer, v Measure) { if !w.EnterStruct() { return } - writeV20(w, v.Value) + writeV24(w, v.Value) w.ExitStruct() return } @@ -2190,29 +2296,29 @@ func writeNinoNullableArgsTypeClass(w *nino.Writer, v *NinoNullableArgsType) { } func readNinoNullableArgsTypeBody(r *nino.Reader, v *NinoNullableArgsType) { - v.Enum = readV21(r) + v.Enum = readV25(r) v.Enums = nino.ReadNinoNullables[Flags](r) - v.Cell = readV22(r) + v.Cell = readV26(r) v.One = codecV4.Read(r) v.Wide = codecV5.Read(r) v.Array = codecV6.Read(r) v.List = codecV7.Read(r) v.Set = nino.ReadNinoNullables[int32](r) - v.Map = readV23(r) - v.Tuple = readV24(r) + v.Map = readV27(r) + v.Tuple = readV28(r) } func writeNinoNullableArgsTypeBody(w *nino.Writer, v *NinoNullableArgsType) { - writeV21(w, v.Enum) + writeV25(w, v.Enum) nino.WriteNinoNullables[Flags](w, v.Enums) - writeV22(w, v.Cell) + writeV26(w, v.Cell) codecV4.Write(w, v.One) codecV5.Write(w, v.Wide) codecV6.Write(w, v.Array) codecV7.Write(w, v.List) nino.WriteNinoNullables[int32](w, v.Set) - writeV23(w, v.Map) - writeV24(w, v.Tuple) + writeV27(w, v.Map) + writeV28(w, v.Tuple) } // NinoNullableRawType is `Shapes.NinoNullableRaw`. @@ -2302,12 +2408,12 @@ func writeNinoNullableRawTypeClass(w *nino.Writer, v *NinoNullableRawType) { func readNinoNullableRawTypeBody(r *nino.Reader, v *NinoNullableRawType) { v.One = readHoldsNinoNullable(r) - v.Many = readV25(r) + v.Many = readV29(r) } func writeNinoNullableRawTypeBody(w *nino.Writer, v *NinoNullableRawType) { writeHoldsNinoNullable(w, v.One) - writeV25(w, v.Many) + writeV29(w, v.Many) } // NinoNullableRawWideType is `Shapes.NinoNullableRawWide`. @@ -2397,12 +2503,12 @@ func writeNinoNullableRawWideTypeClass(w *nino.Writer, v *NinoNullableRawWideTyp func readNinoNullableRawWideTypeBody(r *nino.Reader, v *NinoNullableRawWideType) { v.One = readHoldsWideNinoNullable(r) - v.Many = readV26(r) + v.Many = readV30(r) } func writeNinoNullableRawWideTypeBody(w *nino.Writer, v *NinoNullableRawWideType) { writeHoldsWideNinoNullable(w, v.One) - writeV26(w, v.Many) + writeV30(w, v.Many) } // Node is `Shapes.Generic.Node`. @@ -2565,15 +2671,15 @@ func writeNullableGridsClass(w *nino.Writer, v *NullableGrids) { } func readNullableGridsBody(r *nino.Reader, v *NullableGrids) { - v.Grid = readV27(r) - v.Cube = readV28(r) - v.Cells = readV29(r) + v.Grid = readV31(r) + v.Cube = readV32(r) + v.Cells = readV33(r) } func writeNullableGridsBody(w *nino.Writer, v *NullableGrids) { - writeV27(w, v.Grid) - writeV28(w, v.Cube) - writeV29(w, v.Cells) + writeV31(w, v.Grid) + writeV32(w, v.Cube) + writeV33(w, v.Cells) } // NullableSlots is `Shapes.NullableSlots`. @@ -2676,12 +2782,12 @@ func readNullableSlotsBody(r *nino.Reader, v *NullableSlots) { v.Linked = nino.ReadNullableSlots[uint8](r) v.Sorted = readV5(r) v.ReadOnly = readV4(r) - readintoV30(r, &v.Nested) + readintoV34(r, &v.Nested) v.BoxedSet = codecV1.Read(r) v.BoxedNested = codecV2.Read(r) v.Map = readV7(r) v.BoxedMap = codecV3.Read(r) - readintoV31(r, &v.Tuples) + readintoV35(r, &v.Tuples) } func writeNullableSlotsBody(w *nino.Writer, v *NullableSlots) { @@ -2690,12 +2796,12 @@ func writeNullableSlotsBody(w *nino.Writer, v *NullableSlots) { nino.WriteNullableSlots[uint8](w, v.Linked) nino.WriteNullableSlots[int32](w, v.Sorted) writeV4(w, v.ReadOnly) - writeV30(w, v.Nested) + writeV34(w, v.Nested) codecV1.Write(w, v.BoxedSet) codecV2.Write(w, v.BoxedNested) writeV7(w, v.Map) codecV3.Write(w, v.BoxedMap) - writeV31(w, v.Tuples) + writeV35(w, v.Tuples) } // OffsetHolder is `Shapes.OffsetHolder`. @@ -3470,13 +3576,13 @@ func writePicksClass(w *nino.Writer, v *Picks) { func readPicksBody(r *nino.Reader, v *Picks) { ReadPickInto(r, &v.Pick) - readintoV32(r, &v.Many) + readintoV36(r, &v.Many) ReadMeasureInto(r, &v.Measure) } func writePicksBody(w *nino.Writer, v *Picks) { WritePick(w, v.Pick) - writeV32(w, v.Many) + writeV36(w, v.Many) WriteMeasure(w, v.Measure) } @@ -3556,7 +3662,7 @@ func ReadRecursiveInto(r *nino.Reader, v *Recursive) { return } v.Value = r.I32() - readintoV33(r, &v.Children) + readintoV37(r, &v.Children) r.ExitStruct() } @@ -3565,7 +3671,7 @@ func WriteRecursive(w *nino.Writer, v Recursive) { return } w.I32(v.Value) - writeV33(w, v.Children) + writeV37(w, v.Children) w.ExitStruct() } @@ -4074,7 +4180,7 @@ func readStampsBody(r *nino.Reader, v *Stamps) { v.Ids = nino.ReadBlock[nino.Guid](r) v.Signed = nino.ReadBlock[nino.Int128](r) v.Unsigned = nino.ReadBlock[nino.UInt128](r) - v.Marks = readV34(r) + v.Marks = readV38(r) } func writeStampsBody(w *nino.Writer, v *Stamps) { @@ -4085,7 +4191,7 @@ func writeStampsBody(w *nino.Writer, v *Stamps) { nino.WriteBlock[nino.Guid](w, v.Ids) nino.WriteBlock[nino.Int128](w, v.Signed) nino.WriteBlock[nino.UInt128](w, v.Unsigned) - writeV34(w, v.Marks) + writeV38(w, v.Marks) } // Strides is `Shapes.Strides`. @@ -4629,13 +4735,13 @@ func readUsesBody(r *nino.Reader, v *Uses) { v.Pair = codecV12.Read(r) v.Nested = codecV13.Read(r) v.Mixed = codecV15.Read(r) - readintoV35(r, &v.Boxes) + readintoV39(r, &v.Boxes) v.Bag = codecV16.Read(r) v.Chain = codecV17.Read(r) v.Thing = codecV18.Read(r) v.Array = codecV19.Read(r) v.Complex = codecV20.Read(r) - v.Pairs = readV36(r) + v.Pairs = readV40(r) v.Raw = codecV22.Read(r) v.Tuple = codecV23.Read(r) v.Maybe = codecV24.Read(r) @@ -4651,13 +4757,13 @@ func writeUsesBody(w *nino.Writer, v *Uses) { codecV12.Write(w, v.Pair) codecV13.Write(w, v.Nested) codecV15.Write(w, v.Mixed) - writeV35(w, v.Boxes) + writeV39(w, v.Boxes) codecV16.Write(w, v.Bag) codecV17.Write(w, v.Chain) codecV18.Write(w, v.Thing) codecV19.Write(w, v.Array) codecV20.Write(w, v.Complex) - writeV36(w, v.Pairs) + writeV40(w, v.Pairs) codecV22.Write(w, v.Raw) codecV23.Write(w, v.Tuple) codecV24.Write(w, v.Maybe) @@ -4823,13 +4929,13 @@ func readV4(r *nino.Reader) []nino.NullableSlot[TupleCell] { return nil } b := r.Take(n * 16) - if len(b) != n*16 { + if r.Failed() { return nil } var e nino.NullableSlot[TupleCell] v := make([]nino.NullableSlot[TupleCell], 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) for len(b) >= 16 { - e = decodeV37(r, b[:16:16]) + e = decodeV41(r, b[0:16]) if r.Failed() { return nil } @@ -4845,18 +4951,19 @@ func writeV4(w *nino.Writer, v []nino.NullableSlot[TupleCell]) { return } w.Length(len(v)) - b := w.ExtendZero(len(v) * 16) - if len(b) != len(v)*16 { + b := w.ExtendFixed(len(v), 16, true) + if b == nil { return } for _, e := range v { - encodeV37(b[:16:16], e) + _ = b[15] + encodeV41(b[0:16], e) b = b[16:] } } func readV5(r *nino.Reader) []nino.NullableSlot[int32] { - return nino.CheckUniqueValues(r, nino.ReadNullableSlots[int32](r)) + return keyCheck1.Values(r, nino.ReadNullableSlots[int32](r)) } func readV6(r *nino.Reader) (v [][]nino.NullableSlot[int64]) { @@ -4884,13 +4991,13 @@ func readV7(r *nino.Reader) []nino.Entry[int32, *int64] { v := make([]nino.Entry[int32, *int64], 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) for range n { k := r.I32() - e = nino.Entry[int32, *int64]{Key: k, Value: readV38(r)} + e = nino.Entry[int32, *int64]{Key: k, Value: readV42(r)} if r.Failed() { return nil } v = append(v, e) } - return nino.CheckUniqueKeys(r, v) + return nino.CheckUniqueKeysWith(r, v, &keyCheck2) } func writeV7(w *nino.Writer, v []nino.Entry[int32, *int64]) { @@ -4901,7 +5008,7 @@ func writeV7(w *nino.Writer, v []nino.Entry[int32, *int64]) { w.Length(len(v)) for _, e := range v { w.I32(e.Key) - writeV38(w, e.Value) + writeV42(w, e.Value) } } @@ -4939,13 +5046,13 @@ func readV8(r *nino.Reader) []nino.NinoNullable[TupleCell] { return nil } b := r.Take(n * 24) - if len(b) != n*24 { + if r.Failed() { return nil } var e nino.NinoNullable[TupleCell] v := make([]nino.NinoNullable[TupleCell], 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) for len(b) >= 24 { - e = decodeV22(r, b[:24:24]) + e = decodeV26(r, b[0:24]) if r.Failed() { return nil } @@ -4961,12 +5068,13 @@ func writeV8(w *nino.Writer, v []nino.NinoNullable[TupleCell]) { return } w.Length(len(v)) - b := w.ExtendZero(len(v) * 24) - if len(b) != len(v)*24 { + b := w.ExtendFixed(len(v), 24, true) + if b == nil { return } for _, e := range v { - encodeV22(b[:24:24], e) + _ = b[23] + encodeV26(b[0:24], e) b = b[24:] } } @@ -4986,7 +5094,7 @@ func readV9(r *nino.Reader) []nino.Entry[int32, *string] { } v = append(v, e) } - return nino.CheckUniqueKeys(r, v) + return nino.CheckUniqueKeysWith(r, v, &keyCheck2) } func writeV9(w *nino.Writer, v []nino.Entry[int32, *string]) { @@ -5061,6 +5169,121 @@ func writeV13(w *nino.Writer, v []*string) { nino.WriteStringPtrs(w, v) } +func readV14(r *nino.Reader) []nino.Entry[nino.Guid, Marked] { + n := r.Length(24) + if n < 0 { + return nil + } + b := r.Take(n * 24) + if r.Failed() { + return nil + } + var e nino.Entry[nino.Guid, Marked] + v := make([]nino.Entry[nino.Guid, Marked], 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) + for len(b) >= 24 { + e = nino.Entry[nino.Guid, Marked]{Key: nino.Guid(b[0:16]), Value: decodeMarked(r, b[16:24])} + if r.Failed() { + return nil + } + v = append(v, e) + b = b[24:] + } + return nino.CheckUniqueKeysWith(r, v, &keyCheck3) +} + +func readV15(r *nino.Reader) []nino.Guid { + return keyCheck3.Values(r, nino.ReadBlock[nino.Guid](r)) +} + +func readV16(r *nino.Reader) *NinoGrid[uint8] { + g := readGrid[uint8](r, 2, 1) + if g == nil { + return nil + } + nino.ReadPrimitivesInto(r, g.Items) + if r.Failed() { + return nil + } + return g +} + +func readV17(r *nino.Reader) []nino.DateTimeOffset { + n := r.Length(10) + if n < 0 { + return nil + } + b := r.Take(n * 10) + if r.Failed() { + return nil + } + var e nino.DateTimeOffset + v := make([]nino.DateTimeOffset, 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) + for len(b) >= 10 { + e = r.DateTimeOffsetAt(b[0:10]) + if r.Failed() { + return nil + } + v = append(v, e) + b = b[10:] + } + return v +} + +func writeV14(w *nino.Writer, v []nino.Entry[nino.Guid, Marked]) { + if v == nil { + w.NullLength() + return + } + w.Length(len(v)) + b := w.ExtendFixed(len(v), 24, true) + if b == nil { + return + } + for i := range v { + e := &v[i] + _ = b[23] + copy(b, e.Key[:]) + encodeMarked(b[16:24], e.Value) + b = b[24:] + } +} + +func writeV15(w *nino.Writer, v []nino.Guid) { + nino.WriteBlock(w, v) +} + +func writeV16(w *nino.Writer, v *NinoGrid[uint8]) { + if !writeGrid(w, v, 2) { + return + } + nino.WritePrimitivesRaw(w, v.Items) +} + +func writeV17(w *nino.Writer, v []nino.DateTimeOffset) { + if v == nil { + w.NullLength() + return + } + w.Length(len(v)) + for i, e := range v { + if !e.Valid() { + for _, e := range v[:i+1] { + w.DateTimeOffset(e) + } + return + } + } + b := w.ExtendFixed(len(v), 10, false) + if b == nil { + return + } + for _, e := range v { + _ = b[9] + e.Put(b[0:10]) + b = b[10:] + } +} + func readintoV3(r *nino.Reader, p *[]Forest) { n := r.Length(4) if n < 0 { @@ -5085,7 +5308,7 @@ func readintoV3(r *nino.Reader, p *[]Forest) { *p = v } -func readintoV14(r *nino.Reader, p *[]IThing) { +func readintoV18(r *nino.Reader, p *[]IThing) { n := r.Length(4) if n < 0 { *p = nil @@ -5112,15 +5335,36 @@ func readintoV14(r *nino.Reader, p *[]IThing) { *p = v } -func readV15(r *nino.Reader) Flags { +func readV19(r *nino.Reader) Flags { return Flags(r.I64()) } -func readV16(r *nino.Reader) []Gappy { - return nino.ReadRaw(r, 8, asIsGappy, nil, decodeGappy) +func readV20(r *nino.Reader) []Gappy { + if v, ok := nino.TryReadRaw[Gappy](r, 8, asIsGappy, nil); ok { + return v + } + n := r.Length(8) + if n < 0 { + return nil + } + b := r.Take(n * 8) + if r.Failed() { + return nil + } + var e Gappy + v := make([]Gappy, 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) + for len(b) >= 8 { + e = decodeGappy(r, b[0:8]) + if r.Failed() { + return nil + } + v = append(v, e) + b = b[8:] + } + return v } -func readV17(r *nino.Reader) []*string { +func readV21(r *nino.Reader) []*string { n := r.Length(1) if n < 0 { return nil @@ -5137,14 +5381,14 @@ func readV17(r *nino.Reader) []*string { return nino.CheckUniqueStrings(r, v) } -func readV18(r *nino.Reader) nino.Entry[*string, int32] { +func readV22(r *nino.Reader) nino.Entry[*string, int32] { var v nino.Entry[*string, int32] v.Key = r.StringPtr() v.Value = r.I32() return v } -func writeV14(w *nino.Writer, v []IThing) { +func writeV18(w *nino.Writer, v []IThing) { if v == nil { w.NullLength() return @@ -5155,15 +5399,31 @@ func writeV14(w *nino.Writer, v []IThing) { } } -func writeV15(w *nino.Writer, v Flags) { +func writeV19(w *nino.Writer, v Flags) { w.I64(int64(v)) } -func writeV16(w *nino.Writer, v []Gappy) { - nino.WriteRaw(w, v, 8, asIsGappy, nil, []int{1, 2, 3}, encodeGappy) +func writeV20(w *nino.Writer, v []Gappy) { + if nino.TryWriteRaw(w, v, 8, asIsGappy, nil, []int{1, 2, 3}) { + return + } + if v == nil { + w.NullLength() + return + } + w.Length(len(v)) + b := w.ExtendFixed(len(v), 8, true) + if b == nil { + return + } + for _, e := range v { + _ = b[7] + encodeGappy(b[0:8], e) + b = b[8:] + } } -func writeV17(w *nino.Writer, v []*string) { +func writeV21(w *nino.Writer, v []*string) { if v == nil { w.NullLength() return @@ -5174,24 +5434,24 @@ func writeV17(w *nino.Writer, v []*string) { } } -func writeV18(w *nino.Writer, v nino.Entry[*string, int32]) { +func writeV22(w *nino.Writer, v nino.Entry[*string, int32]) { w.StringPtr(v.Key) w.I32(v.Value) } -func readV19(r *nino.Reader) []nino.NullableSlot[nino.Int128] { +func readV23(r *nino.Reader) []nino.NullableSlot[nino.Int128] { n := r.Length(32) if n < 0 { return nil } b := r.Take(n * 32) - if len(b) != n*32 { + if r.Failed() { return nil } var e nino.NullableSlot[nino.Int128] v := make([]nino.NullableSlot[nino.Int128], 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) for len(b) >= 32 { - e = decodeV39(r, b[:32:32]) + e = decodeV43(r, b[0:32]) if r.Failed() { return nil } @@ -5201,114 +5461,126 @@ func readV19(r *nino.Reader) []nino.NullableSlot[nino.Int128] { return v } -func writeV19(w *nino.Writer, v []nino.NullableSlot[nino.Int128]) { +func writeV23(w *nino.Writer, v []nino.NullableSlot[nino.Int128]) { if v == nil { w.NullLength() return } w.Length(len(v)) - b := w.ExtendZero(len(v) * 32) - if len(b) != len(v)*32 { + b := w.ExtendFixed(len(v), 32, true) + if b == nil { return } for _, e := range v { - encodeV39(b[:32:32], e) + _ = b[31] + encodeV43(b[0:32], e) b = b[32:] } } -func readV20(r *nino.Reader) (v []*string) { - readintoV20(r, &v) +func readV24(r *nino.Reader) (v []*string) { + readintoV24(r, &v) return v } -func writeV20(w *nino.Writer, v []*string) { +func writeV24(w *nino.Writer, v []*string) { nino.WriteStringPtrs(w, v) } -func readV21(r *nino.Reader) nino.NinoNullable[Flags] { +func readV25(r *nino.Reader) nino.NinoNullable[Flags] { var v nino.NinoNullable[Flags] if b := r.Take(16); len(b) == 16 { - v = decodeV21(r, b) + v = decodeV25(r, b) } return v } -func readV22(r *nino.Reader) nino.NinoNullable[TupleCell] { +func readV26(r *nino.Reader) nino.NinoNullable[TupleCell] { var v nino.NinoNullable[TupleCell] if b := r.Take(24); len(b) == 24 { - v = decodeV22(r, b) + v = decodeV26(r, b) } return v } -func readV23(r *nino.Reader) []nino.Entry[int32, nino.NinoNullable[float64]] { +func readV27(r *nino.Reader) []nino.Entry[int32, nino.NinoNullable[float64]] { n := r.Length(20) if n < 0 { return nil } + b := r.Take(n * 20) + if r.Failed() { + return nil + } var e nino.Entry[int32, nino.NinoNullable[float64]] v := make([]nino.Entry[int32, nino.NinoNullable[float64]], 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) - for range n { - k := r.I32() - e = nino.Entry[int32, nino.NinoNullable[float64]]{Key: k, Value: readV40(r)} + for len(b) >= 20 { + e = nino.Entry[int32, nino.NinoNullable[float64]]{Key: int32(le.Uint32(b)), Value: decodeV44(r, b[4:20])} if r.Failed() { return nil } v = append(v, e) + b = b[20:] } - return nino.CheckUniqueKeys(r, v) + return nino.CheckUniqueKeysWith(r, v, &keyCheck2) } -func readV24(r *nino.Reader) NinoTuple2[uint8, nino.NinoNullable[nino.Guid]] { +func readV28(r *nino.Reader) NinoTuple2[uint8, nino.NinoNullable[nino.Guid]] { var v NinoTuple2[uint8, nino.NinoNullable[nino.Guid]] v.Item1 = r.U8() - v.Item2 = readV41(r) + v.Item2 = readV45(r) return v } -func writeV21(w *nino.Writer, v nino.NinoNullable[Flags]) { +func writeV25(w *nino.Writer, v nino.NinoNullable[Flags]) { if b := w.ExtendZero(16); len(b) == 16 { - encodeV21(b, v) + encodeV25(b, v) } } -func writeV22(w *nino.Writer, v nino.NinoNullable[TupleCell]) { +func writeV26(w *nino.Writer, v nino.NinoNullable[TupleCell]) { if b := w.ExtendZero(24); len(b) == 24 { - encodeV22(b, v) + encodeV26(b, v) } } -func writeV23(w *nino.Writer, v []nino.Entry[int32, nino.NinoNullable[float64]]) { +func writeV27(w *nino.Writer, v []nino.Entry[int32, nino.NinoNullable[float64]]) { if v == nil { w.NullLength() return } w.Length(len(v)) - for _, e := range v { - w.I32(e.Key) - writeV40(w, e.Value) + b := w.ExtendFixed(len(v), 20, true) + if b == nil { + return + } + for i := range v { + e := &v[i] + _ = b[19] + le.PutUint32(b, uint32(e.Key)) + encodeV44(b[4:20], e.Value) + b = b[20:] } } -func writeV24(w *nino.Writer, v NinoTuple2[uint8, nino.NinoNullable[nino.Guid]]) { +func writeV28(w *nino.Writer, v NinoTuple2[uint8, nino.NinoNullable[nino.Guid]]) { w.U8(v.Item1) - writeV41(w, v.Item2) + writeV45(w, v.Item2) } -func readV25(r *nino.Reader) []HoldsNinoNullable { +func readV29(r *nino.Reader) []HoldsNinoNullable { n := r.Length(12) if n < 0 { return nil } b := r.Take(n * 12) - if len(b) != n*12 { + if r.Failed() { return nil } var e HoldsNinoNullable v := make([]HoldsNinoNullable, 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) for len(b) >= 12 { - e = decodeHoldsNinoNullable(r, b[:12:12]) + e = decodeHoldsNinoNullable(r, b[0:12]) if r.Failed() { return nil } @@ -5318,35 +5590,36 @@ func readV25(r *nino.Reader) []HoldsNinoNullable { return v } -func writeV25(w *nino.Writer, v []HoldsNinoNullable) { +func writeV29(w *nino.Writer, v []HoldsNinoNullable) { if v == nil { w.NullLength() return } w.Length(len(v)) - b := w.ExtendZero(len(v) * 12) - if len(b) != len(v)*12 { + b := w.ExtendFixed(len(v), 12, true) + if b == nil { return } for _, e := range v { - encodeHoldsNinoNullable(b[:12:12], e) + _ = b[11] + encodeHoldsNinoNullable(b[0:12], e) b = b[12:] } } -func readV26(r *nino.Reader) []HoldsWideNinoNullable { +func readV30(r *nino.Reader) []HoldsWideNinoNullable { n := r.Length(40) if n < 0 { return nil } b := r.Take(n * 40) - if len(b) != n*40 { + if r.Failed() { return nil } var e HoldsWideNinoNullable v := make([]HoldsWideNinoNullable, 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) for len(b) >= 40 { - e = decodeHoldsWideNinoNullable(r, b[:40:40]) + e = decodeHoldsWideNinoNullable(r, b[0:40]) if r.Failed() { return nil } @@ -5356,92 +5629,129 @@ func readV26(r *nino.Reader) []HoldsWideNinoNullable { return v } -func writeV26(w *nino.Writer, v []HoldsWideNinoNullable) { +func writeV30(w *nino.Writer, v []HoldsWideNinoNullable) { if v == nil { w.NullLength() return } w.Length(len(v)) - b := w.ExtendZero(len(v) * 40) - if len(b) != len(v)*40 { + b := w.ExtendFixed(len(v), 40, true) + if b == nil { return } for _, e := range v { - encodeHoldsWideNinoNullable(b[:40:40], e) + _ = b[39] + encodeHoldsWideNinoNullable(b[0:40], e) b = b[40:] } } -func readV27(r *nino.Reader) *NinoGrid[nino.NullableSlot[int32]] { +func readV31(r *nino.Reader) *NinoGrid[nino.NullableSlot[int32]] { g := readGrid[nino.NullableSlot[int32]](r, 2, 8) if g == nil { return nil } + b := r.Take(len(g.Items) * 8) + if r.Failed() { + return nil + } for i := range g.Items { - g.Items[i] = readV42(r) + _ = b[7] + g.Items[i] = decodeV46(r, b[0:8]) if r.Failed() { return nil } + b = b[8:] } return g } -func readV28(r *nino.Reader) *NinoGrid[nino.NullableSlot[int64]] { +func readV32(r *nino.Reader) *NinoGrid[nino.NullableSlot[int64]] { g := readGrid[nino.NullableSlot[int64]](r, 3, 16) if g == nil { return nil } + b := r.Take(len(g.Items) * 16) + if r.Failed() { + return nil + } for i := range g.Items { - g.Items[i] = readV43(r) + _ = b[15] + g.Items[i] = decodeV47(r, b[0:16]) if r.Failed() { return nil } + b = b[16:] } return g } -func readV29(r *nino.Reader) *NinoGrid[nino.NullableSlot[TupleCell]] { +func readV33(r *nino.Reader) *NinoGrid[nino.NullableSlot[TupleCell]] { g := readGrid[nino.NullableSlot[TupleCell]](r, 2, 16) if g == nil { return nil } + b := r.Take(len(g.Items) * 16) + if r.Failed() { + return nil + } for i := range g.Items { - g.Items[i] = readV37(r) + _ = b[15] + g.Items[i] = decodeV41(r, b[0:16]) if r.Failed() { return nil } + b = b[16:] } return g } -func writeV27(w *nino.Writer, v *NinoGrid[nino.NullableSlot[int32]]) { +func writeV31(w *nino.Writer, v *NinoGrid[nino.NullableSlot[int32]]) { if !writeGrid(w, v, 2) { return } + b := w.ExtendFixed(len(v.Items), 8, true) + if b == nil { + return + } for _, e := range v.Items { - writeV42(w, e) + _ = b[7] + encodeV46(b[0:8], e) + b = b[8:] } } -func writeV28(w *nino.Writer, v *NinoGrid[nino.NullableSlot[int64]]) { +func writeV32(w *nino.Writer, v *NinoGrid[nino.NullableSlot[int64]]) { if !writeGrid(w, v, 3) { return } + b := w.ExtendFixed(len(v.Items), 16, true) + if b == nil { + return + } for _, e := range v.Items { - writeV43(w, e) + _ = b[15] + encodeV47(b[0:16], e) + b = b[16:] } } -func writeV29(w *nino.Writer, v *NinoGrid[nino.NullableSlot[TupleCell]]) { +func writeV33(w *nino.Writer, v *NinoGrid[nino.NullableSlot[TupleCell]]) { if !writeGrid(w, v, 2) { return } + b := w.ExtendFixed(len(v.Items), 16, true) + if b == nil { + return + } for _, e := range v.Items { - writeV37(w, e) + _ = b[15] + encodeV41(b[0:16], e) + b = b[16:] } } -func readintoV30(r *nino.Reader, p *[][]nino.NullableSlot[int32]) { +func readintoV34(r *nino.Reader, p *[][]nino.NullableSlot[int32]) { n := r.Length(4) if n < 0 { *p = nil @@ -5465,7 +5775,7 @@ func readintoV30(r *nino.Reader, p *[][]nino.NullableSlot[int32]) { *p = v } -func readintoV31(r *nino.Reader, p *[]NinoTuple2[int32, *int32]) { +func readintoV35(r *nino.Reader, p *[]NinoTuple2[int32, *int32]) { n := r.Length(5) if n < 0 { *p = nil @@ -5479,7 +5789,7 @@ func readintoV31(r *nino.Reader, p *[]NinoTuple2[int32, *int32]) { } var e NinoTuple2[int32, *int32] for range n { - e = readV44(r) + e = readV48(r) if r.Failed() { *p = nil return @@ -5489,7 +5799,7 @@ func readintoV31(r *nino.Reader, p *[]NinoTuple2[int32, *int32]) { *p = v } -func writeV30(w *nino.Writer, v [][]nino.NullableSlot[int32]) { +func writeV34(w *nino.Writer, v [][]nino.NullableSlot[int32]) { if v == nil { w.NullLength() return @@ -5500,18 +5810,18 @@ func writeV30(w *nino.Writer, v [][]nino.NullableSlot[int32]) { } } -func writeV31(w *nino.Writer, v []NinoTuple2[int32, *int32]) { +func writeV35(w *nino.Writer, v []NinoTuple2[int32, *int32]) { if v == nil { w.NullLength() return } w.Length(len(v)) for _, e := range v { - writeV44(w, e) + writeV48(w, e) } } -func readintoV32(r *nino.Reader, p *[]Pick) { +func readintoV36(r *nino.Reader, p *[]Pick) { n := r.Length(4) if n < 0 { *p = nil @@ -5538,7 +5848,7 @@ func readintoV32(r *nino.Reader, p *[]Pick) { *p = v } -func writeV32(w *nino.Writer, v []Pick) { +func writeV36(w *nino.Writer, v []Pick) { if v == nil { w.NullLength() return @@ -5549,7 +5859,7 @@ func writeV32(w *nino.Writer, v []Pick) { } } -func readintoV33(r *nino.Reader, p *[]Recursive) { +func readintoV37(r *nino.Reader, p *[]Recursive) { n := r.Length(8) if n < 0 { *p = nil @@ -5576,7 +5886,7 @@ func readintoV33(r *nino.Reader, p *[]Recursive) { *p = v } -func writeV33(w *nino.Writer, v []Recursive) { +func writeV37(w *nino.Writer, v []Recursive) { if v == nil { w.NullLength() return @@ -5587,15 +5897,52 @@ func writeV33(w *nino.Writer, v []Recursive) { } } -func readV34(r *nino.Reader) []Marked { - return nino.ReadRaw(r, 8, asIsMarked, []int{4}, decodeMarked) +func readV38(r *nino.Reader) []Marked { + if v, ok := nino.TryReadRaw[Marked](r, 8, asIsMarked, []int{4}); ok { + return v + } + n := r.Length(8) + if n < 0 { + return nil + } + b := r.Take(n * 8) + if r.Failed() { + return nil + } + var e Marked + v := make([]Marked, 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) + for len(b) >= 8 { + e = decodeMarked(r, b[0:8]) + if r.Failed() { + return nil + } + v = append(v, e) + b = b[8:] + } + return v } -func writeV34(w *nino.Writer, v []Marked) { - nino.WriteRaw(w, v, 8, asIsMarked, []int{4}, nil, encodeMarked) +func writeV38(w *nino.Writer, v []Marked) { + if nino.TryWriteRaw(w, v, 8, asIsMarked, []int{4}, nil) { + return + } + if v == nil { + w.NullLength() + return + } + w.Length(len(v)) + b := w.ExtendFixed(len(v), 8, true) + if b == nil { + return + } + for _, e := range v { + _ = b[7] + encodeMarked(b[0:8], e) + b = b[8:] + } } -func readintoV35(r *nino.Reader, p *[]*Box[int32]) { +func readintoV39(r *nino.Reader, p *[]*Box[int32]) { n := r.Length(1) if n < 0 { *p = nil @@ -5619,8 +5966,8 @@ func readintoV35(r *nino.Reader, p *[]*Box[int32]) { *p = v } -func readV36(r *nino.Reader) []nino.Entry[string, Pair[int32, int32]] { - n := r.Length(1) +func readV40(r *nino.Reader) []nino.Entry[string, Pair[int32, int32]] { + n := r.Length(9) if n < 0 { return nil } @@ -5634,10 +5981,10 @@ func readV36(r *nino.Reader) []nino.Entry[string, Pair[int32, int32]] { } v = append(v, e) } - return nino.CheckUniqueKeys(r, v) + return nino.CheckUniqueKeysWith(r, v, &keyCheck0) } -func writeV35(w *nino.Writer, v []*Box[int32]) { +func writeV39(w *nino.Writer, v []*Box[int32]) { if v == nil { w.NullLength() return @@ -5648,7 +5995,7 @@ func writeV35(w *nino.Writer, v []*Box[int32]) { } } -func writeV36(w *nino.Writer, v []nino.Entry[string, Pair[int32, int32]]) { +func writeV40(w *nino.Writer, v []nino.Entry[string, Pair[int32, int32]]) { if v == nil { w.NullLength() return @@ -5660,7 +6007,7 @@ func writeV36(w *nino.Writer, v []nino.Entry[string, Pair[int32, int32]]) { } } -func decodeV37(r *nino.Reader, b []byte) nino.NullableSlot[TupleCell] { +func decodeV41(r *nino.Reader, b []byte) nino.NullableSlot[TupleCell] { _ = b[15] if !r.BoolAt(b[0]) { return nino.NullableSlot[TupleCell]{} @@ -5668,7 +6015,7 @@ func decodeV37(r *nino.Reader, b []byte) nino.NullableSlot[TupleCell] { return nino.NullableSlot[TupleCell]{HasValue: true, Value: decodeTupleCell(r, b[4:16])} } -func encodeV37(b []byte, v nino.NullableSlot[TupleCell]) { +func encodeV41(b []byte, v nino.NullableSlot[TupleCell]) { _ = b[15] if v.HasValue { b[0] = 1 @@ -5691,7 +6038,7 @@ func readintoV6(r *nino.Reader, p *[][]nino.NullableSlot[int64]) { } var e []nino.NullableSlot[int64] for range n { - e = readV45(r) + e = readV49(r) if r.Failed() { *p = nil return @@ -5701,7 +6048,7 @@ func readintoV6(r *nino.Reader, p *[][]nino.NullableSlot[int64]) { *p = v } -func readV38(r *nino.Reader) *int64 { +func readV42(r *nino.Reader) *int64 { if !r.Present() { return nil } @@ -5709,14 +6056,14 @@ func readV38(r *nino.Reader) *int64 { return &x } -func writeV38(w *nino.Writer, v *int64) { +func writeV42(w *nino.Writer, v *int64) { w.Present(v != nil) if v != nil { w.I64(*v) } } -func decodeV22(r *nino.Reader, b []byte) nino.NinoNullable[TupleCell] { +func decodeV26(r *nino.Reader, b []byte) nino.NinoNullable[TupleCell] { _ = b[23] if !r.NinoNullableAt(b[0:12], b[12:24]) { return nino.NinoNullable[TupleCell]{} @@ -5724,7 +6071,7 @@ func decodeV22(r *nino.Reader, b []byte) nino.NinoNullable[TupleCell] { return nino.NinoNullable[TupleCell]{HasValue: true, Value: decodeTupleCell(r, b[12:24])} } -func encodeV22(b []byte, v nino.NinoNullable[TupleCell]) { +func encodeV26(b []byte, v nino.NinoNullable[TupleCell]) { _ = b[23] if v.HasValue { b[0] = 1 @@ -5733,7 +6080,7 @@ func encodeV22(b []byte, v nino.NinoNullable[TupleCell]) { } } -func decodeV39(r *nino.Reader, b []byte) nino.NullableSlot[nino.Int128] { +func decodeV43(r *nino.Reader, b []byte) nino.NullableSlot[nino.Int128] { _ = b[31] if !r.BoolAt(b[0]) { return nino.NullableSlot[nino.Int128]{} @@ -5741,7 +6088,7 @@ func decodeV39(r *nino.Reader, b []byte) nino.NullableSlot[nino.Int128] { return nino.NullableSlot[nino.Int128]{HasValue: true, Value: nino.Int128{Lo: le.Uint64(b[16:]), Hi: le.Uint64(b[24:])}} } -func encodeV39(b []byte, v nino.NullableSlot[nino.Int128]) { +func encodeV43(b []byte, v nino.NullableSlot[nino.Int128]) { _ = b[31] if v.HasValue { b[0] = 1 @@ -5751,7 +6098,7 @@ func encodeV39(b []byte, v nino.NullableSlot[nino.Int128]) { } } -func readintoV20(r *nino.Reader, p *[]*string) { +func readintoV24(r *nino.Reader, p *[]*string) { n := r.Length(1) if n < 0 { *p = nil @@ -5775,7 +6122,7 @@ func readintoV20(r *nino.Reader, p *[]*string) { *p = v } -func decodeV21(r *nino.Reader, b []byte) nino.NinoNullable[Flags] { +func decodeV25(r *nino.Reader, b []byte) nino.NinoNullable[Flags] { _ = b[15] if !r.NinoNullableAt(b[0:8], b[8:16]) { return nino.NinoNullable[Flags]{} @@ -5783,23 +6130,23 @@ func decodeV21(r *nino.Reader, b []byte) nino.NinoNullable[Flags] { return nino.NinoNullable[Flags]{HasValue: true, Value: Flags(int64(le.Uint64(b[8:])))} } -func readV40(r *nino.Reader) nino.NinoNullable[float64] { - var v nino.NinoNullable[float64] - if b := r.Take(16); len(b) == 16 { - v = decodeV40(r, b) +func decodeV44(r *nino.Reader, b []byte) nino.NinoNullable[float64] { + _ = b[15] + if !r.NinoNullableAt(b[0:8], b[8:16]) { + return nino.NinoNullable[float64]{} } - return v + return nino.NinoNullable[float64]{HasValue: true, Value: math.Float64frombits(le.Uint64(b[8:]))} } -func readV41(r *nino.Reader) nino.NinoNullable[nino.Guid] { +func readV45(r *nino.Reader) nino.NinoNullable[nino.Guid] { var v nino.NinoNullable[nino.Guid] if b := r.Take(32); len(b) == 32 { - v = decodeV41(r, b) + v = decodeV45(r, b) } return v } -func encodeV21(b []byte, v nino.NinoNullable[Flags]) { +func encodeV25(b []byte, v nino.NinoNullable[Flags]) { _ = b[15] if v.HasValue { b[0] = 1 @@ -5808,85 +6155,72 @@ func encodeV21(b []byte, v nino.NinoNullable[Flags]) { } } -func writeV40(w *nino.Writer, v nino.NinoNullable[float64]) { - if b := w.ExtendZero(16); len(b) == 16 { - encodeV40(b, v) +func encodeV44(b []byte, v nino.NinoNullable[float64]) { + _ = b[15] + if v.HasValue { + b[0] = 1 + x := v.Value + le.PutUint64(b[8:], math.Float64bits(x)) } } -func writeV41(w *nino.Writer, v nino.NinoNullable[nino.Guid]) { +func writeV45(w *nino.Writer, v nino.NinoNullable[nino.Guid]) { if b := w.ExtendZero(32); len(b) == 32 { - encodeV41(b, v) - } -} - -func readV42(r *nino.Reader) nino.NullableSlot[int32] { - var v nino.NullableSlot[int32] - if b := r.Take(8); len(b) == 8 { - v = decodeV42(r, b) + encodeV45(b, v) } - return v } -func readV43(r *nino.Reader) nino.NullableSlot[int64] { - var v nino.NullableSlot[int64] - if b := r.Take(16); len(b) == 16 { - v = decodeV43(r, b) - } - return v -} - -func readV37(r *nino.Reader) nino.NullableSlot[TupleCell] { - var v nino.NullableSlot[TupleCell] - if b := r.Take(16); len(b) == 16 { - v = decodeV37(r, b) +func decodeV46(r *nino.Reader, b []byte) nino.NullableSlot[int32] { + _ = b[7] + if !r.BoolAt(b[0]) { + return nino.NullableSlot[int32]{} } - return v + return nino.NullableSlot[int32]{HasValue: true, Value: int32(le.Uint32(b[4:]))} } -func writeV42(w *nino.Writer, v nino.NullableSlot[int32]) { - if b := w.ExtendZero(8); len(b) == 8 { - encodeV42(b, v) +func decodeV47(r *nino.Reader, b []byte) nino.NullableSlot[int64] { + _ = b[15] + if !r.BoolAt(b[0]) { + return nino.NullableSlot[int64]{} } + return nino.NullableSlot[int64]{HasValue: true, Value: int64(le.Uint64(b[8:]))} } -func writeV43(w *nino.Writer, v nino.NullableSlot[int64]) { - if b := w.ExtendZero(16); len(b) == 16 { - encodeV43(b, v) +func encodeV46(b []byte, v nino.NullableSlot[int32]) { + _ = b[7] + if v.HasValue { + b[0] = 1 + x := v.Value + le.PutUint32(b[4:], uint32(x)) } } -func writeV37(w *nino.Writer, v nino.NullableSlot[TupleCell]) { - if b := w.ExtendZero(16); len(b) == 16 { - encodeV37(b, v) +func encodeV47(b []byte, v nino.NullableSlot[int64]) { + _ = b[15] + if v.HasValue { + b[0] = 1 + x := v.Value + le.PutUint64(b[8:], uint64(x)) } } -func readV44(r *nino.Reader) NinoTuple2[int32, *int32] { +func readV48(r *nino.Reader) NinoTuple2[int32, *int32] { var v NinoTuple2[int32, *int32] v.Item1 = r.I32() v.Item2 = readV11(r) return v } -func writeV44(w *nino.Writer, v NinoTuple2[int32, *int32]) { +func writeV48(w *nino.Writer, v NinoTuple2[int32, *int32]) { w.I32(v.Item1) writeV11(w, v.Item2) } -func readV45(r *nino.Reader) []nino.NullableSlot[int64] { - return nino.CheckUniqueValues(r, nino.ReadNullableSlots[int64](r)) -} - -func decodeV40(r *nino.Reader, b []byte) nino.NinoNullable[float64] { - _ = b[15] - if !r.NinoNullableAt(b[0:8], b[8:16]) { - return nino.NinoNullable[float64]{} - } - return nino.NinoNullable[float64]{HasValue: true, Value: math.Float64frombits(le.Uint64(b[8:]))} +func readV49(r *nino.Reader) []nino.NullableSlot[int64] { + return keyCheck4.Values(r, nino.ReadNullableSlots[int64](r)) } -func decodeV41(r *nino.Reader, b []byte) nino.NinoNullable[nino.Guid] { +func decodeV45(r *nino.Reader, b []byte) nino.NinoNullable[nino.Guid] { _ = b[31] if !r.NinoNullableAt(b[0:16], b[16:32]) { return nino.NinoNullable[nino.Guid]{} @@ -5894,16 +6228,7 @@ func decodeV41(r *nino.Reader, b []byte) nino.NinoNullable[nino.Guid] { return nino.NinoNullable[nino.Guid]{HasValue: true, Value: nino.Guid(b[16:32])} } -func encodeV40(b []byte, v nino.NinoNullable[float64]) { - _ = b[15] - if v.HasValue { - b[0] = 1 - x := v.Value - le.PutUint64(b[8:], math.Float64bits(x)) - } -} - -func encodeV41(b []byte, v nino.NinoNullable[nino.Guid]) { +func encodeV45(b []byte, v nino.NinoNullable[nino.Guid]) { _ = b[31] if v.HasValue { b[0] = 1 @@ -5912,39 +6237,15 @@ func encodeV41(b []byte, v nino.NinoNullable[nino.Guid]) { } } -func decodeV42(r *nino.Reader, b []byte) nino.NullableSlot[int32] { - _ = b[7] - if !r.BoolAt(b[0]) { - return nino.NullableSlot[int32]{} - } - return nino.NullableSlot[int32]{HasValue: true, Value: int32(le.Uint32(b[4:]))} -} +var keyCheck0 = nino.PrepareKeyCheck[string]() -func decodeV43(r *nino.Reader, b []byte) nino.NullableSlot[int64] { - _ = b[15] - if !r.BoolAt(b[0]) { - return nino.NullableSlot[int64]{} - } - return nino.NullableSlot[int64]{HasValue: true, Value: int64(le.Uint64(b[8:]))} -} +var keyCheck1 = nino.PrepareKeyCheck[nino.NullableSlot[int32]]() -func encodeV42(b []byte, v nino.NullableSlot[int32]) { - _ = b[7] - if v.HasValue { - b[0] = 1 - x := v.Value - le.PutUint32(b[4:], uint32(x)) - } -} +var keyCheck2 = nino.PrepareKeyCheck[int32]() -func encodeV43(b []byte, v nino.NullableSlot[int64]) { - _ = b[15] - if v.HasValue { - b[0] = 1 - x := v.Value - le.PutUint64(b[8:], uint64(x)) - } -} +var keyCheck3 = nino.PrepareKeyCheck[nino.Guid]() + +var keyCheck4 = nino.PrepareKeyCheck[nino.NullableSlot[int64]]() // NinoTuple2 is a ValueTuple or Tuple of 2 items. type NinoTuple2[T1, T2 any] struct { @@ -6087,6 +6388,8 @@ func NinoCodecOf(name string) (NinoCodec, bool) { return codecOf(ReadBasedInt, ReadBasedIntInto, WriteBasedInt), true case "Shapes.Empty": return codecOf(ReadEmpty, ReadEmptyInto, WriteEmpty), true + case "Shapes.FixedCollections": + return codecOf(ReadFixedCollections, ReadFixedCollectionsInto, WriteFixedCollections), true case "Shapes.FloatKeys": return codecOf(ReadFloatKeys, ReadFloatKeysInto, WriteFloatKeys), true case "Shapes.ForestHolder": diff --git a/runtimes/go/internal/generated/shapes/shapes_test.go b/runtimes/go/internal/generated/shapes/shapes_test.go index d90f3914e..6522aafe9 100644 --- a/runtimes/go/internal/generated/shapes/shapes_test.go +++ b/runtimes/go/internal/generated/shapes/shapes_test.go @@ -99,6 +99,73 @@ func TestBlockShapesRoundTrip(t *testing.T) { } } +func TestFixedCollections(t *testing.T) { + ids := []nino.Guid{{1}, {2}, {3}} + want := &FixedCollections{ + Ids: []nino.Entry[nino.Guid, Marked]{ + {Key: ids[0], Value: Marked{Id: 1, On: true, Kind: 2, Code: -3}}, + {Key: ids[1], Value: Marked{Id: -4, Kind: 5, Code: 6}}, + }, + UniqueIds: ids, + Grid: &NinoGrid[uint8]{Lengths: []int{1, 2}, Items: []uint8{0x80, 0xFF}}, + Pairs: []nino.Entry[int32, int64]{{Key: 7, Value: -9}}, + Offsets: []nino.DateTimeOffset{{UtcTicks: 638712864000000000, OffsetMinutes: -60}, {}}, + } + got, err := nino.Serialize(want, WriteFixedCollections) + if err != nil { + t.Fatal(err) + } + scalar, err := nino.Serialize(want, func(w *nino.Writer, v *FixedCollections) { + w.Present(true) + w.Length(len(v.Ids)) + for _, e := range v.Ids { + w.Guid(e.Key) + w.I32(e.Value.Id) + w.Bool(e.Value.On) + w.U8(e.Value.Kind) + w.I16(e.Value.Code) + } + writeEach(w, v.UniqueIds, (*nino.Writer).Guid) + w.WriteShape(v.Grid.Lengths...) + for _, e := range v.Grid.Items { + w.U8(e) + } + w.Length(len(v.Pairs)) + for _, e := range v.Pairs { + w.I32(e.Key) + w.I64(e.Value) + } + writeEach(w, v.Offsets, (*nino.Writer).DateTimeOffset) + }) + if err != nil || !reflect.DeepEqual(got, scalar) { + t.Fatalf("fixed bytes %x, scalar bytes %x (%v)", got, scalar, err) + } + if v, err := nino.DeserializeExact(got, ReadFixedCollections); err != nil || !reflect.DeepEqual(v, want) { + t.Fatalf("read back %+v (%v)", v, err) + } + const mapStart, pair = 5, 16 + 8 + bad := append([]byte(nil), got...) + copy(bad[mapStart+pair:mapStart+pair+16], bad[mapStart:mapStart+16]) + if _, err := nino.DeserializeExact(bad, ReadFixedCollections); !errors.Is(err, nino.ErrDuplicateKey) { + t.Fatalf("read duplicate Guid key: %v", err) + } + copy(bad, got) + bad[mapStart+16+4] = 2 + if _, err := nino.DeserializeExact(bad, ReadFixedCollections); !errors.Is(err, nino.ErrInvalidData) { + t.Fatalf("read invalid bool in raw map value: %v", err) + } + // The second DateTimeOffset has its UTC ticks at zero, so an offset of -1 minute is invalid. + copy(bad, got) + bad[len(bad)-2], bad[len(bad)-1] = 0xFF, 0xFF + if _, err := nino.DeserializeExact(bad, ReadFixedCollections); !errors.Is(err, nino.ErrInvalidData) { + t.Fatalf("read invalid DateTimeOffset: %v", err) + } + want.Offsets[1].OffsetMinutes = -1 + if _, err := nino.Serialize(want, WriteFixedCollections); !errors.Is(err, nino.ErrInvalidValue) { + t.Fatalf("wrote invalid DateTimeOffset: %v", err) + } +} + // Generic types: closed uses read and written with the codecs built from those of their arguments. func TestGenericShapesRoundTrip(t *testing.T) { s := func(v string) *string { return &v } diff --git a/runtimes/go/internal/sample/codec_values.go b/runtimes/go/internal/sample/codec_values.go index 9d8d0da49..4326bfa43 100644 --- a/runtimes/go/internal/sample/codec_values.go +++ b/runtimes/go/internal/sample/codec_values.go @@ -425,9 +425,9 @@ func readStructsBody(r *nino.Reader, v *Structs) { v.Sized = readSized(r) v.Nested = readNested(r) v.Label = readLabel(r) - v.VecArray = nino.ReadRaw(r, 8, asIsVec2, nil, decodeVec2) - v.PaddedList = nino.ReadRaw(r, 16, asIsPadded, nil, decodePadded) - v.MixedArray = nino.ReadRaw(r, 12, asIsMixed, nil, decodeMixed) + v.VecArray = readVec2s(r) + v.PaddedList = readPaddeds(r) + v.MixedArray = readMixeds(r) v.Labels = readLabels(r) v.RawTuple.Item1 = r.U8() v.RawTuple.Item2 = r.I64() @@ -445,7 +445,7 @@ func writeStructsBody(w *nino.Writer, v *Structs) { writeSized(w, v.Sized) writeNested(w, v.Nested) writeLabel(w, v.Label) - nino.WriteRaw(w, v.VecArray, 8, asIsVec2, nil, nil, encodeVec2) + writeVec2s(w, v.VecArray) writePaddeds(w, v.PaddedList) writeMixeds(w, v.MixedArray) writeLabels(w, v.Labels) diff --git a/runtimes/go/internal/sample/loops.go b/runtimes/go/internal/sample/loops.go index a0ad6a27c..7af2810ea 100644 --- a/runtimes/go/internal/sample/loops.go +++ b/runtimes/go/internal/sample/loops.go @@ -190,7 +190,30 @@ func readLabels(r *nino.Reader) []Label { return v } +func readMixeds(r *nino.Reader) []Mixed { + if v, ok := nino.TryReadRaw[Mixed](r, 12, asIsMixed, nil); ok { + return v + } + n := r.Length(12) + if n < 0 { + return nil + } + b := r.Take(n * 12) + if len(b) != n*12 { + return nil + } + v := make([]Mixed, 0, r.SliceCap(n, int(unsafe.Sizeof(Mixed{})))) + for len(b) >= 12 { + v = append(v, decodeMixed(r, b[:12:12])) + b = b[12:] + } + return v +} + func readPaddeds(r *nino.Reader) []Padded { + if v, ok := nino.TryReadRaw[Padded](r, 16, asIsPadded, nil); ok { + return v + } n := r.Length(16) if n < 0 { return nil @@ -199,19 +222,34 @@ func readPaddeds(r *nino.Reader) []Padded { if len(b) != n*16 { return nil } - var e Padded - v := make([]Padded, 0, r.SliceCap(n, int(unsafe.Sizeof(e)))) + v := make([]Padded, 0, r.SliceCap(n, int(unsafe.Sizeof(Padded{})))) for len(b) >= 16 { - e = decodePadded(r, b[:16:16]) - if r.Failed() { - return nil - } - v = append(v, e) + v = append(v, decodePadded(r, b[:16:16])) b = b[16:] } return v } +func readVec2s(r *nino.Reader) []Vec2 { + if v, ok := nino.TryReadRaw[Vec2](r, 8, asIsVec2, nil); ok { + return v + } + n := r.Length(8) + if n < 0 { + return nil + } + b := r.Take(n * 8) + if len(b) != n*8 { + return nil + } + v := make([]Vec2, 0, r.SliceCap(n, int(unsafe.Sizeof(Vec2{})))) + for len(b) >= 8 { + v = append(v, decodeVec2(r, b[:8:8])) + b = b[8:] + } + return v +} + func readPoints(r *nino.Reader) []*Point { n := r.Length(1) if n < 0 { @@ -590,6 +628,25 @@ func writePaddeds(w *nino.Writer, v []Padded) { } } +func writeVec2s(w *nino.Writer, v []Vec2) { + if nino.TryWriteRaw(w, v, 8, asIsVec2, nil, nil) { + return + } + if v == nil { + w.NullLength() + return + } + w.Length(len(v)) + b := w.ExtendFixed(len(v), 8, false) + if b == nil { + return + } + for _, e := range v { + encodeVec2(b[:8:8], e) + b = b[8:] + } +} + func writePoints(w *nino.Writer, v []*Point) { if v == nil { w.NullLength() diff --git a/runtimes/go/raw.go b/runtimes/go/raw.go index 6fb73becf..14c18aecf 100644 --- a/runtimes/go/raw.go +++ b/runtimes/go/raw.go @@ -29,8 +29,8 @@ func ReadPrimitives[T Primitive](r *Reader) []T { return v } -// readPrimitivesInto reads len(dst) primitives (a block without a length) into dst. -func readPrimitivesInto[T Primitive](r *Reader, dst []T) { +// ReadPrimitivesInto reads len(dst) primitives, a block without a length, into dst. +func ReadPrimitivesInto[T Primitive](r *Reader, dst []T) { var zero T size := int(unsafe.Sizeof(zero)) b := r.Take(len(dst) * size) @@ -47,11 +47,11 @@ func WritePrimitives[T Primitive](w *Writer, v []T) { return } w.Length(len(v)) - writePrimitivesRaw(w, v) + WritePrimitivesRaw(w, v) } -// writePrimitivesRaw writes primitives as one block, without a length. -func writePrimitivesRaw[T Primitive](w *Writer, v []T) { +// WritePrimitivesRaw writes primitives as one block without a length. +func WritePrimitivesRaw[T Primitive](w *Writer, v []T) { var zero T size := int(unsafe.Sizeof(zero)) b := w.Extend(len(v) * size) @@ -219,21 +219,30 @@ func normalizeBools(b []byte) { func ReadPrimitiveEntries[K, V Primitive](r *Reader) []Entry[K, V] { var e Entry[K, V] size := int(unsafe.Sizeof(e)) - wire := int(unsafe.Sizeof(e.Key) + unsafe.Sizeof(e.Value)) - if !littleEndian || size != wire { - return readUniqueEntries(r, wire, readPrimitive[K], readPrimitive[V]) - } - n := r.Length(size) + ks := int(unsafe.Sizeof(e.Key)) + wire := ks + int(unsafe.Sizeof(e.Value)) + n := r.Length(wire) if n < 0 { return nil } - b := r.Take(n * size) - if len(b) != n*size { + b := r.Take(n * wire) + if len(b) != n*wire { return nil } - v := make([]Entry[K, V], n) - copy(unsafe.Slice((*byte)(unsafe.Pointer(unsafe.SliceData(v))), n*size), b) - if repeated[K](unsafe.Pointer(unsafe.SliceData(v)), n, size, &r.keys) { + var v []Entry[K, V] + if littleEndian && size == wire { + v = make([]Entry[K, V], n) + copy(unsafe.Slice((*byte)(unsafe.Pointer(unsafe.SliceData(v))), n*wire), b) + } else { + v = make([]Entry[K, V], 0, r.SliceCap(n, size)) + for len(b) >= wire { + v = append(v, Entry[K, V]{Key: loadPrimitive[K](b), Value: loadPrimitive[V](b[ks:])}) + b = b[wire:] + } + } + // Division by two distinguishes integer and floating-point shapes at compile time. + floatKey := K(1)/K(2) != 0 + if n > 1 && repeatedBits(unsafe.Pointer(unsafe.SliceData(v)), n, size, ks, floatKey, &r.keys) { r.Fail(CodeDuplicateKey, "") return nil } @@ -243,22 +252,28 @@ func ReadPrimitiveEntries[K, V Primitive](r *Reader) []Entry[K, V] { // WritePrimitiveEntries writes a dictionary of primitive keys and values as its pairs, in order (nil is null): one // block copied from memory where [ReadPrimitiveEntries] reads one, else one pair at a time. func WritePrimitiveEntries[K, V Primitive](w *Writer, e []Entry[K, V]) { - var p Entry[K, V] - size := int(unsafe.Sizeof(p)) - if !littleEndian || size != int(unsafe.Sizeof(p.Key)+unsafe.Sizeof(p.Value)) { - writeEntries(w, e, writePrimitive[K], writePrimitive[V]) - return - } if e == nil { w.NullLength() return } + var p Entry[K, V] + size := int(unsafe.Sizeof(p)) + ks := int(unsafe.Sizeof(p.Key)) + wire := ks + int(unsafe.Sizeof(p.Value)) w.Length(len(e)) - b := w.Extend(len(e) * size) - if len(b) != len(e)*size { + b := w.Extend(len(e) * wire) + if len(b) != len(e)*wire { return } - copy(b, unsafe.Slice((*byte)(unsafe.Pointer(unsafe.SliceData(e))), len(e)*size)) + if littleEndian && size == wire { + copy(b, unsafe.Slice((*byte)(unsafe.Pointer(unsafe.SliceData(e))), len(e)*wire)) + return + } + for _, pair := range e { + storePrimitive(b, pair.Key) + storePrimitive(b[ks:], pair.Value) + b = b[wire:] + } } // ReadPrimitiveMap reads a dictionary of primitive keys and values into a map (nil for null): a key read twice @@ -354,12 +369,12 @@ func storePrimitive[T Primitive](b []byte, v T) { // readPrimitive reads one primitive in little-endian order. func readPrimitive[T Primitive](r *Reader) T { var v [1]T - readPrimitivesInto(r, v[:]) + ReadPrimitivesInto(r, v[:]) return v[0] } // writePrimitive writes one primitive in little-endian order. func writePrimitive[T Primitive](w *Writer, x T) { v := [1]T{x} - writePrimitivesRaw(w, v[:]) + WritePrimitivesRaw(w, v[:]) } diff --git a/runtimes/go/types_time.go b/runtimes/go/types_time.go index 3acd3a166..abada11b2 100644 --- a/runtimes/go/types_time.go +++ b/runtimes/go/types_time.go @@ -168,7 +168,16 @@ func DateTimeOffsetOf(t time.Time) (DateTimeOffset, bool) { // DateTimeOffset reads a DateTimeOffset; one .NET cannot hold fails with CodeInvalidData, as in .NET. func (r *Reader) DateTimeOffset() DateTimeOffset { - o := DateTimeOffsetAt(r.Take(DateTimeOffsetSize)) + return r.DateTimeOffsetAt(r.Take(DateTimeOffsetSize)) +} + +// DateTimeOffsetAt checks and decodes a DateTimeOffset from a block taken by the caller. +func (r *Reader) DateTimeOffsetAt(b []byte) DateTimeOffset { + if len(b) < DateTimeOffsetSize { + r.eof() + return DateTimeOffset{} + } + o := DateTimeOffsetAt(b) if !o.Valid() { r.Fail(CodeInvalidData, "invalid DateTimeOffset") return DateTimeOffset{} @@ -197,6 +206,11 @@ func (w *Writer) DateTimeOffset(o DateTimeOffset) { if len(b) < DateTimeOffsetSize { return } + o.Put(b) +} + +// Put writes o into an existing block of at least DateTimeOffsetSize bytes. The caller checks Valid first. +func (o DateTimeOffset) Put(b []byte) { binary.LittleEndian.PutUint64(b, uint64(o.UtcTicks)) binary.LittleEndian.PutUint16(b[8:], uint16(o.OffsetMinutes)) } diff --git a/runtimes/go/unique.go b/runtimes/go/unique.go index 539aad0a8..ce7e8c356 100644 --- a/runtimes/go/unique.go +++ b/runtimes/go/unique.go @@ -5,6 +5,7 @@ import ( "math/bits" "reflect" "slices" + "sync" "unsafe" ) @@ -17,7 +18,7 @@ import ( // hash seeded per process: integers multiplied by a random odd number, strings through hash/maphash. Data cannot choose // keys that share a slot without knowing the seed, and a key that still probes past maxProbes slots sends the whole // check to a path whose cost the data cannot raise: a sort for numbers (pdqsort falls back to heapsort), a Go map -// (seeded too) for strings. Other comparable keys go through a Go map. +// (seeded too) for strings and bytewise keys. Other comparable keys go through a Go map. // maxProbes bounds the slots one key may probe in a table before the check falls back (see above). With the table at // most half full and a seeded hash, honest data almost never comes near it. @@ -39,6 +40,25 @@ type keyKind struct { slot uintptr } +// KeyCheck holds the duplicate-check metadata for one key type. Generated codecs prepare it once. +// A zero or nil check discovers the key kind as [CheckUniqueValues] and [CheckUniqueKeys] do. +type KeyCheck[K comparable] struct { + _ [0]K // A conversion cannot carry offsets or strides to a different key type. + kind keyKind + bytewiseSize int + prepared bool +} + +// PrepareKeyCheck discovers the duplicate-check metadata for K before decoding. +func PrepareKeyCheck[K comparable]() KeyCheck[K] { + kind := kindOf[K]() + c := KeyCheck[K]{kind: kind, prepared: true} + if kind == (keyKind{}) { + c.bytewiseSize = bytewiseKeySize[K]() + } + return c +} + // kindOf returns how keys of type K are compared. func kindOf[K comparable]() keyKind { t := reflect.TypeFor[K]() @@ -78,11 +98,17 @@ func kindOfType(t reflect.Type) keyKind { // repeated reports whether two of the n keys of type K, the first at p and each stride bytes after the one before, // are equal (see the top of this file). scratch is the reader's memory for the tables (see table). -func repeated[K comparable](p unsafe.Pointer, n, stride int, scratch *[]uint64) bool { +func (c *KeyCheck[K]) repeated(p unsafe.Pointer, n, stride int, scratch *[]uint64) bool { if n < 2 { return false } - switch k := kindOf[K](); { + var k keyKind + if c != nil && c.prepared { + k = c.kind + } else { + k = kindOf[K]() + } + switch { case k.slot != 0: return repeatedSlots(p, n, stride, k, scratch) case k.size != 0: @@ -90,7 +116,7 @@ func repeated[K comparable](p unsafe.Pointer, n, stride int, scratch *[]uint64) case k.text: return repeatedStrings(p, n, stride, false, scratch) } - return repeatedValues[K](p, n, stride) + return c.repeatedOtherKeys(p, n, stride, scratch) } // repeatedSlots is repeated for NullableSlots of a number (k): two nulls are equal, and the values present are @@ -415,3 +441,111 @@ func repeatedNaN[K comparable](k K, nan *bool) bool { *nan = true return false } + +var bytewiseKeySizes sync.Map // reflect.Type -> int, 0 for keys that need Go equality + +// bytewiseKeySize caches the result of walking a composite key's fields. Numeric and text keys +// take their existing paths before they get here. +func bytewiseKeySize[K comparable]() int { + t := reflect.TypeFor[K]() + switch t.Kind() { + case reflect.Array, reflect.Struct: + default: + return 0 + } + if size, ok := bytewiseKeySizes.Load(t); ok { + return size.(int) + } + size := 0 + if bytewiseKey(t) { + size = int(t.Size()) + } + actual, _ := bytewiseKeySizes.LoadOrStore(t, size) + return actual.(int) +} + +// bytewiseKey proves that equality is a comparison of every byte, including all fields of a nested value. +// Floats, blank fields, padding and pointers rule it out. DateTime, DateTimeOffset, Half and Decimal carry +// more than one representation of some values in .NET. +func bytewiseKey(t reflect.Type) bool { + switch t { + case reflect.TypeFor[DateTime](), reflect.TypeFor[DateTimeOffset](), reflect.TypeFor[Half](), reflect.TypeFor[Decimal](): + return false + } + switch t.Kind() { + case reflect.Bool, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int, + reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: + return true + case reflect.Array: + return bytewiseKey(t.Elem()) + case reflect.Struct: + var end uintptr + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + if f.Name == "_" || f.Offset != end || !bytewiseKey(f.Type) { + return false + } + end += f.Type.Size() + } + return end == t.Size() + } + return false +} + +// repeatedOtherKeys keeps bytewise key handling off the scalar and string paths. +// +//go:noinline +func (c *KeyCheck[K]) repeatedOtherKeys(p unsafe.Pointer, n, stride int, scratch *[]uint64) bool { + var size int + if c != nil && c.prepared { + size = c.bytewiseSize + } else { + size = bytewiseKeySize[K]() + } + if size != 0 && n <= 1<<(bits.UintSize-6) && int64(n) < 1<<31 { + if result, bounded := repeatedBytewise(p, n, stride, size, scratch); bounded { + return result + } + } + return repeatedValues[K](p, n, stride) +} + +// repeatedBytewise uses the reader's seeded, probe-bounded table and a fixed-width view of each key. +// The caller has proved that the key covers its full memory representation and contains no pointers. +func repeatedBytewise(p unsafe.Pointer, n, stride, size int, scratch *[]uint64) (repeated, bounded bool) { + if n <= 16 { + for i := 1; i < n; i++ { + key := unsafe.String((*byte)(unsafe.Add(p, i*stride)), size) + for j := 0; j < i; j++ { + if key == unsafe.String((*byte)(unsafe.Add(p, j*stride)), size) { + return true, true + } + } + } + return false, true + } + t := table(scratch, tableBits(n)) + mask := uint64(len(t) - 1) + for i := 0; i < n; i++ { + key := unsafe.String((*byte)(unsafe.Add(p, i*stride)), size) + h := maphash.String(hashSeed, key) + tag := h &^ 0xFFFFFFFF + for at, probes := h, 0; ; at, probes = at+1, probes+1 { + slot := t[at&mask] + if slot == 0 { + t[at&mask] = tag | uint64(i+1) + break + } + if slot&^0xFFFFFFFF == tag { + other := unsafe.Add(p, int(uint32(slot)-1)*stride) + if key == unsafe.String((*byte)(other), size) { + return true, true + } + } + if probes == maxProbes { + return false, false + } + } + } + return false, true +} diff --git a/runtimes/go/unique_test.go b/runtimes/go/unique_test.go index c1c3d9a5a..b2c5f7a9d 100644 --- a/runtimes/go/unique_test.go +++ b/runtimes/go/unique_test.go @@ -127,6 +127,67 @@ func TestUniqueIntegerKeys(t *testing.T) { (*Writer).String, (*Reader).String, 1) } +func TestUniqueBytewiseKeys(t *testing.T) { + type padded struct { + A byte + B uint64 + } + type nested struct { + Id Guid + Hi [2]uint64 + } + if bytewiseKeySize[Guid]() != 16 || bytewiseKeySize[Int128]() != 16 || bytewiseKeySize[nested]() != 32 { + t.Fatal("packed pointer-free keys did not use the bytewise check") + } + if bytewiseKeySize[padded]() != 0 || bytewiseKeySize[Decimal]() != 0 || + bytewiseKeySize[struct{ F float64 }]() != 0 || bytewiseKeySize[struct{ P *int }]() != 0 || + bytewiseKeySize[DateTimeOffset]() != 0 { + t.Fatal("noncanonical or pointer-bearing key used the bytewise check") + } + for _, n := range []int{2, 16, 17, 1024} { + keys := make([]Guid, n) + for i := range keys { + keys[i][0], keys[i][15] = byte(i), byte(i>>8) + } + checkUnique(t, keys, (*Writer).Guid, (*Reader).Guid, 16) + keys[n-1] = keys[0] + checkUnique(t, keys, (*Writer).Guid, (*Reader).Guid, 16) + } +} + +func TestPreparedKeyCheck(t *testing.T) { + check := PrepareKeyCheck[Guid]() + keys := make([]Guid, 32) + entries := make([]Entry[Guid, uint64], len(keys)) + for i := range keys { + keys[i][0] = byte(i) + entries[i] = Entry[Guid, uint64]{keys[i], uint64(i)} + } + r := NewReader(nil) + if !slices.Equal(check.Values(r, keys), keys) || !slices.Equal(CheckUniqueKeysWith(r, entries, &check), entries) || r.Failed() { + t.Fatalf("distinct prepared keys: %v", r.Err()) + } + keys[len(keys)-1] = keys[0] + entries[len(entries)-1].Key = keys[0] + r = NewReader(nil) + if v := check.Values(r, keys); v != nil || !r.Failed() { + t.Fatal("prepared set accepted a duplicate") + } + r = NewReader(nil) + if v := CheckUniqueKeysWith(r, entries, &check); v != nil || !r.Failed() { + t.Fatal("prepared dictionary accepted a duplicate") + } + + type namedFloat float64 + values := []namedFloat{namedFloat(math.NaN()), namedFloat(math.Float64frombits(0x7ff8000000000002))} + for _, check := range []KeyCheck[namedFloat]{PrepareKeyCheck[namedFloat](), {}} { + r = NewReader(nil) + if v := check.Values(r, values); v != nil || !r.Failed() { + t.Fatal("float NaN payloads must compare equal") + } + } +} + // TestUniqueLargeSets covers larger sets: distinct keys, one repeated pair at both ends and in // the middle, keys that differ only in their highest byte, and random keys. func TestUniqueLargeSets(t *testing.T) { @@ -284,7 +345,7 @@ func TestPrimitiveEntries(t *testing.T) { primitiveEntries(t, func(i int) uint8 { return uint8(i) }, func(i int) int8 { return int8(i) }) primitiveEntries(t, func(i int) uint16 { return uint16(i * 7) }, func(i int) uint16 { return uint16(i) }) primitiveEntries(t, func(i int) int64 { return int64(i) << 40 }, func(i int) float64 { return float64(i) / 3 }) - // Float keys keep the map: -0 and +0 are one key. + // Float keys compare as .NET does: -0 and +0 are one key. primitiveEntries(t, func(i int) float32 { if i == 0 { return float32(math.Copysign(0, -1)) @@ -301,6 +362,7 @@ func TestPrimitiveEntries(t *testing.T) { // TestUniqueFloatsAsDotNet: floating-point elements and keys are equal as .NET's double.Equals has it: any two NaNs // (whatever their payload), and -0 with 0, where Go's == and maps keep NaNs apart. func TestUniqueFloatsAsDotNet(t *testing.T) { + type namedFloat float64 quiet, payload := math.NaN(), math.Float64frombits(0x7FF0000000000001) for _, n := range []int{2, 16, 17, 300} { base := make([]float64, n) @@ -318,6 +380,11 @@ func TestUniqueFloatsAsDotNet(t *testing.T) { if r = NewReader(nil); CheckUniqueKeys(r, e) != nil || r.Err() == nil { t.Fatalf("keys %v and %v: accepted", pair[0], pair[1]) } + w := NewWriter(0) + WritePrimitiveEntries(w, []Entry[namedFloat, int32]{{namedFloat(pair[0]), 1}, {namedFloat(pair[1]), 2}}) + if r = NewReader(w.Bytes()); ReadPrimitiveEntries[namedFloat, int32](r) != nil || r.Err() == nil { + t.Fatalf("primitive keys %v and %v: accepted", pair[0], pair[1]) + } f := make([]float32, n) for i := range f { f[i] = float32(v[i]) diff --git a/runtimes/go/writer.go b/runtimes/go/writer.go index b419f257c..8953b6af0 100644 --- a/runtimes/go/writer.go +++ b/runtimes/go/writer.go @@ -83,6 +83,22 @@ func (w *Writer) ExtendZero(n int) []byte { return b } +// ExtendFixed reserves one block for count elements of size bytes each. It clears the block when zero is true. +func (w *Writer) ExtendFixed(count, size int, zero bool) []byte { + if w.err != nil { + return nil + } + if count < 0 || size <= 0 || count > (int(^uint(0)>>1)-len(w.buf))/size { + w.Fail(CodeTooLarge, "fixed-size block") + return nil + } + b := w.Extend(count * size) + if zero { + clear(b) + } + return b +} + //go:noinline func (w *Writer) grow(n int) { need := len(w.buf) + n diff --git a/runtimes/rust/AGENTS.md b/runtimes/rust/AGENTS.md index a9aec334a..e57807579 100644 --- a/runtimes/rust/AGENTS.md +++ b/runtimes/rust/AGENTS.md @@ -26,7 +26,14 @@ src/ writer.rs Writer: appends to a Vec error.rs the one error type (Error, ErrorKind) traits.rs the traits generated code implements and calls (NinoRead, NinoWrite, bodies) - impls.rs NinoRead / NinoWrite for primitives, strings, Option, Box, tuples, std collections + impls.rs shared codec helpers, ordered keys, deferred steps and the ordered codec fragments + impls/numbers.rs primitive numbers and booleans, including their fixed-size blocks + impls/strings.rs String and str + impls/wrappers.rs Option and Box + impls/sequences.rs Vec, slices and VecDeque + impls/sets.rs HashSet, BTreeSet and shared set helpers + impls/maps.rs HashMap, BTreeMap and the map! reader shared with IndexMap + impls/tuples.rs tuples and pairs types.rs the .NET value types as plain Rust types keeping their exact bits types/time.rs DateTime, TimeSpan, DateOnly, TimeOnly, DateTimeOffset: ticks and .NET's ranges strings.rs string headers and the default encoding's writer @@ -107,11 +114,14 @@ Generated files: `tests/generated/*` is rewritten by `NINO_UPDATE_GENERATED=1 do (`type_consts!`); anything the wire format cannot express is a compile error naming the field, with a case in `tests/compile_fail/`. Give a new attribute a corpus or derive test. -- Before committing: `cargo fmt --all --check`, `cargo clippy --workspace --all-features --all-targets -- -D warnings` -- Write a macro call's arguments one per line once they hold a bound (`HashMap,` / `fill_hash_map,` / `Eq + Hash`): the rustfmt in CI's `stable` toolchain (November 2026) splits them, while rustfmt 1.9.0 accepts both forms, so a local check passed and main's Runtimes run failed on `map!` in `impls.rs` and `convert.rs` (5a03c0a5). +- Before committing: `cargo fmt --all --check`, `rustfmt --edition 2021 --check src/impls/*.rs` for the included + fragments, `cargo clippy --workspace --all-features --all-targets -- -D warnings`, and `cargo test --workspace --all-features` with `NINO_CORPUS` set (the conformance, derive and fuzz tests skip without a corpus), then `cargo test -p nino-serialization --lib --test spec --test values` without features, as runtimes.yml does: a test there that uses the derive or another feature goes behind `#[cfg(feature = "...")]` (round 104's `canonical_layout_int128_field` broke that job). `tests/conformance/types.rs` is generated by `tests/conformance/gen.py`; edit the generator. Builds share one `CARGO_TARGET_DIR`: Rust targets are large. +- Write a macro call's arguments one per line once they hold a bound (`HashMap,` / `fill_hash_map,` / `Eq + Hash`). + The rustfmt in CI's `stable` toolchain (November 2026) splits them, while rustfmt 1.9.0 accepts both forms. + A local check passed and main's Runtimes run failed on `map!` in `impls.rs` and `convert.rs` (5a03c0a5). diff --git a/runtimes/rust/README.md b/runtimes/rust/README.md index 923d2e99a..d84d62611 100644 --- a/runtimes/rust/README.md +++ b/runtimes/rust/README.md @@ -273,6 +273,7 @@ still parse from these strings (`FromStr`) and print to them (`Display`). ```sh cargo fmt --all --check +rustfmt --edition 2021 --check src/impls/*.rs cargo clippy --workspace --all-features --all-targets -- -D warnings cargo test --workspace --all-features ``` diff --git a/runtimes/rust/bench/src/model.rs b/runtimes/rust/bench/src/model.rs index 0de0c16e8..a2b1888b4 100644 --- a/runtimes/rust/bench/src/model.rs +++ b/runtimes/rust/bench/src/model.rs @@ -9048,19 +9048,13 @@ impl UnionTagged { } impl NinoRead for UnionTagged { const MIN_SIZE: usize = 4; + #[inline] fn read(r: &mut nino::Reader<'_>) -> nino::Result { - let mut v = Self::Empty; - v.read_into(r)?; - Ok(v) - } - fn read_into(&mut self, r: &mut nino::Reader<'_>) -> nino::Result<()> { let id = r.i32()?; if id == 0 { - *self = Self::Empty; - return Ok(()); + return Ok(Self::Empty); } - *self = Self::read_case(r, id)?; - Ok(()) + Self::read_case(r, id) } } impl NinoWrite for UnionTagged { @@ -9132,10 +9126,12 @@ impl UnionValue { } 791437675 => Self::UnionPoint(r.read()?), 635318394 => { + let mark = r.defer_mark(); let value: Option> = r.read()?; if value.is_none() { return Err(nino::Error::new(nino::ErrorKind::UnexpectedNull, id)); } + r.defer_trail(mark, nino::Step::Field(|p| p.downcast_mut::()?.case_value())); Self::UnionItem(value) } _ => return Err(nino::Error::new(nino::ErrorKind::UnknownTypeId, id)), @@ -9145,25 +9141,17 @@ impl UnionValue { impl NinoRead for UnionValue { const MAY_DEFER: bool = true; const MIN_SIZE: usize = 4; + #[inline] fn read(r: &mut nino::Reader<'_>) -> nino::Result { - let mut v = Self::Empty; - v.read_into(r)?; - Ok(v) - } - fn read_into(&mut self, r: &mut nino::Reader<'_>) -> nino::Result<()> { let id = r.i32()?; if id == 0 { - *self = Self::Empty; - return Ok(()); + return Ok(Self::Empty); } // A case can hold the union again: each level counts toward the depth limit. r.enter_struct()?; - let mark = r.defer_mark(); let value = Self::read_case(r, id); r.exit_struct(); - *self = value?; - r.defer_trail(mark, nino::Step::Field(|p| p.downcast_mut::()?.case_value())); - Ok(()) + value } } impl NinoWrite for UnionValue { diff --git a/runtimes/rust/fuzz/Cargo.lock b/runtimes/rust/fuzz/Cargo.lock index 907265f82..c8b35d704 100644 --- a/runtimes/rust/fuzz/Cargo.lock +++ b/runtimes/rust/fuzz/Cargo.lock @@ -116,7 +116,7 @@ dependencies = [ [[package]] name = "nino-serialization" -version = "4.0.0-rc.7" +version = "4.0.0-rc.10" dependencies = [ "indexmap", ] diff --git a/runtimes/rust/src/convert.rs b/runtimes/rust/src/convert.rs index 2f6e9a301..f2d45b546 100644 --- a/runtimes/rust/src/convert.rs +++ b/runtimes/rust/src/convert.rs @@ -292,7 +292,7 @@ mod indexmap_impl { use crate::defer::Step; use crate::error::{Error, ErrorKind, Result}; - use crate::impls::{fill_set, read_key, FillSet}; + use crate::impls::{fill_set, read_key, write_set, FillSet}; use crate::reader::Reader; use crate::traits::{NinoRead, NinoWrite}; use crate::writer::Writer; @@ -409,11 +409,7 @@ mod indexmap_impl { impl NinoWrite for IndexSet { fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { - w.length(self.len())?; - for v in self { - v.write(w)?; - } - Ok(()) + write_set(self.iter(), w) } fn write_option<'a>(value: Option<&'a Self>, w: &mut Writer<'a>) -> Result<()> { diff --git a/runtimes/rust/src/impls.rs b/runtimes/rust/src/impls.rs index 093af4255..058572b75 100644 --- a/runtimes/rust/src/impls.rs +++ b/runtimes/rust/src/impls.rs @@ -285,1011 +285,15 @@ where Step::Dyn(std::rc::Rc::new(f)) } -// ---------------------------------------------------------------------- numbers - -macro_rules! number { - ($($t:ty, $n:literal, $method:ident;)*) => {$( - impl NinoRead for $t { - const MIN_SIZE: usize = $n; - const FIXED_SIZE: usize = $n; - - #[inline] - fn decode_fixed(bytes: &[u8]) -> Result { - bytes.first_chunk::<$n>().map(|b| <$t>::from_le_bytes(*b)).ok_or_else(Error::end) - } - - #[inline] - fn read(r: &mut Reader<'_>) -> Result { - r.$method() - } - - #[inline] - fn read_many(r: &mut Reader<'_>, count: usize) -> Result> { - let size = count.checked_mul($n).ok_or_else(Error::too_large)?; - let bytes = r.take(size)?; - Ok(bytes.as_chunks::<$n>().0.iter().map(|c| <$t>::from_le_bytes(*c)).collect()) - } - - #[inline] - fn read_many_into(r: &mut Reader<'_>, count: usize, values: &mut Vec) -> Result<()> { - let size = count.checked_mul($n).ok_or_else(Error::too_large)?; - let bytes = r.take(size)?; - values.clear(); - values.extend(bytes.as_chunks::<$n>().0.iter().map(|c| <$t>::from_le_bytes(*c))); - Ok(()) - } - } - - impl NinoWrite for $t { - const FIXED_SIZE: usize = $n; - - #[inline] - fn encode_fixed(&self, out: &mut [u8]) { - if let Some(dst) = out.first_chunk_mut::<$n>() { - *dst = self.to_le_bytes(); - } - } - - #[inline] - fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { - w.$method(*self); - Ok(()) - } - - #[inline] - fn write_many<'a>(values: &'a [Self], w: &mut Writer<'a>) -> Result<()> { - w.encoded(values, |v| v.to_le_bytes()); - Ok(()) - } - - #[inline] - fn write_counted<'a>(values: &'a [Self], w: &mut Writer<'a>) -> Result<()> { - w.counted(values, |v| v.to_le_bytes()) - } - } - )*}; -} - -number! { - i16, 2, i16; - u16, 2, u16; - i32, 4, i32; - u32, 4, u32; - i64, 8, i64; - u64, 8, u64; - i128, 16, i128; - u128, 16, u128; - f32, 4, f32; - f64, 8, f64; -} - -impl NinoRead for u8 { - const MIN_SIZE: usize = 1; - const FIXED_SIZE: usize = 1; - - #[inline] - fn decode_fixed(bytes: &[u8]) -> Result { - bytes.first().copied().ok_or_else(Error::end) - } - - #[inline] - fn read(r: &mut Reader<'_>) -> Result { - r.u8() - } - - /// A `byte[]`: one copy. - #[inline] - fn read_many(r: &mut Reader<'_>, count: usize) -> Result> { - r.take(count).map(<[u8]>::to_vec) - } - - #[inline] - fn read_many_into(r: &mut Reader<'_>, count: usize, values: &mut Vec) -> Result<()> { - let bytes = r.take(count)?; - values.clear(); - values.extend_from_slice(bytes); - Ok(()) - } -} - -impl NinoWrite for u8 { - const FIXED_SIZE: usize = 1; - - #[inline] - fn encode_fixed(&self, out: &mut [u8]) { - if let Some(b) = out.first_mut() { - *b = *self; - } - } - - #[inline] - fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { - w.u8(*self); - Ok(()) - } - - #[inline] - fn write_many<'a>(values: &'a [Self], w: &mut Writer<'a>) -> Result<()> { - w.bytes(values); - Ok(()) - } -} - -impl NinoRead for i8 { - const MIN_SIZE: usize = 1; - const FIXED_SIZE: usize = 1; - - #[inline] - fn decode_fixed(bytes: &[u8]) -> Result { - bytes.first().map(|&b| b as i8).ok_or_else(Error::end) - } - - #[inline] - fn read(r: &mut Reader<'_>) -> Result { - r.i8() - } - - #[inline] - fn read_many(r: &mut Reader<'_>, count: usize) -> Result> { - Ok(r.take(count)?.iter().map(|&b| b as i8).collect()) - } - - #[inline] - fn read_many_into(r: &mut Reader<'_>, count: usize, values: &mut Vec) -> Result<()> { - let bytes = r.take(count)?; - values.clear(); - values.extend(bytes.iter().map(|&b| b as i8)); - Ok(()) - } -} - -impl NinoWrite for i8 { - const FIXED_SIZE: usize = 1; - - #[inline] - fn encode_fixed(&self, out: &mut [u8]) { - if let Some(b) = out.first_mut() { - *b = *self as u8; - } - } - - #[inline] - fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { - w.i8(*self); - Ok(()) - } - - #[inline] - fn write_many<'a>(values: &'a [Self], w: &mut Writer<'a>) -> Result<()> { - w.encoded(values, |&v| [v as u8]); - Ok(()) - } - - #[inline] - fn write_counted<'a>(values: &'a [Self], w: &mut Writer<'a>) -> Result<()> { - w.counted(values, |&v| [v as u8]) - } -} - -impl NinoRead for bool { - const MIN_SIZE: usize = 1; - const FIXED_SIZE: usize = 1; - - #[inline] - fn decode_fixed(bytes: &[u8]) -> Result { - match bytes.first() { - Some(0) => Ok(false), - Some(1) => Ok(true), - Some(&b) => Err(Error::new(ErrorKind::InvalidBool, i32::from(b))), - None => Err(Error::end()), - } - } - - #[inline] - fn read(r: &mut Reader<'_>) -> Result { - r.bool() - } - - /// One pass that ORs every byte (no early exit, so it runs a vector at a time): a byte other than 0 and 1 sets - /// a bit above the lowest. Only then is the bad byte looked for. - #[inline] - fn read_many(r: &mut Reader<'_>, count: usize) -> Result> { - let bytes = r.take(count)?; - if bytes.iter().fold(0u8, |a, &b| a | b) > 1 { - return Err(invalid_bool(bytes)); - } - Ok(bytes.iter().map(|&b| b != 0).collect()) - } - - #[inline] - fn read_many_into(r: &mut Reader<'_>, count: usize, values: &mut Vec) -> Result<()> { - let bytes = r.take(count)?; - if bytes.iter().fold(0u8, |a, &b| a | b) > 1 { - return Err(invalid_bool(bytes)); - } - values.clear(); - values.extend(bytes.iter().map(|&b| b != 0)); - Ok(()) - } -} - -/// The error for the first byte of `bytes` that is not 0 or 1. -#[cold] -#[inline(never)] -fn invalid_bool(bytes: &[u8]) -> Error { - let b = bytes.iter().copied().find(|&b| b > 1).unwrap_or(2); - Error::new(ErrorKind::InvalidBool, i32::from(b)) -} - -impl NinoWrite for bool { - const FIXED_SIZE: usize = 1; - - #[inline] - fn encode_fixed(&self, out: &mut [u8]) { - if let Some(b) = out.first_mut() { - *b = u8::from(*self); - } - } - - #[inline] - fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { - w.bool(*self); - Ok(()) - } - - #[inline] - fn write_many<'a>(values: &'a [Self], w: &mut Writer<'a>) -> Result<()> { - w.encoded(values, |&v| [u8::from(v)]); - Ok(()) - } - - #[inline] - fn write_counted<'a>(values: &'a [Self], w: &mut Writer<'a>) -> Result<()> { - w.counted(values, |&v| [u8::from(v)]) - } -} - -// ---------------------------------------------------------------------- strings - -impl NinoRead for String { - const MIN_SIZE: usize = 1; - - #[inline] - fn read(r: &mut Reader<'_>) -> Result { - r.string()?.ok_or_else(Error::null) - } - - #[inline] - fn read_option(r: &mut Reader<'_>) -> Result> { - r.string() - } - - #[inline] - fn read_many(r: &mut Reader<'_>, count: usize) -> Result> { - r.strings(count) - } - - /// Strings are read new (a list of them by the batched reader when the `Vec` is empty); the `Vec`'s buffer is - /// kept. - #[inline] - fn read_many_into(r: &mut Reader<'_>, count: usize, values: &mut Vec) -> Result<()> { - if values.capacity() < count { - *values = r.strings(count)?; - return Ok(()); - } - crate::impls::read_each_into(r, count, values) - } -} - -impl NinoWrite for String { - const PREFETCH_BYTES: usize = 64; - - #[inline(always)] - fn prefetch(&self) { - crate::simd::prefetch(self.as_ptr()); - } - - #[inline] - fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { - w.string(Some(self)) - } - - #[inline] - fn write_many<'a>(values: &'a [Self], w: &mut Writer<'a>) -> Result<()> { - if prefetches::(values.len()) { - return crate::strings::write_strings_prefetched(w, values); - } - crate::strings::write_strings(w, values) - } - - #[inline] - fn write_option<'a>(value: Option<&'a Self>, w: &mut Writer<'a>) -> Result<()> { - w.string(value.map(String::as_str)) - } -} - -impl NinoWrite for str { - #[inline] - fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { - w.string(Some(self)) - } -} - -// ---------------------------------------------------------------------- Option, Box - -fn option_inner(v: &mut dyn Any) -> Option<&mut dyn Any> { - v.downcast_mut::>()?.as_mut().map(|x| x as &mut dyn Any) -} - -fn box_inner(v: &mut dyn Any) -> Option<&mut dyn Any> { - Some(&mut **v.downcast_mut::>()? as &mut dyn Any) -} - -/// A value that may be null, in `T`'s null encoding (see [`NinoRead::read_option`]). -impl NinoRead for Option { - const MAY_DEFER: bool = T::MAY_DEFER; - const MIN_SIZE: usize = 1; - - #[inline] - fn read(r: &mut Reader<'_>) -> Result { - if !T::MAY_DEFER { - return T::read_option(r); - } - let mark = r.defer_mark(); - let value = T::read_option(r)?; - r.defer_trail(mark, Step::Field(option_inner::)); - Ok(value) - } - - #[inline] - fn read_into(&mut self, r: &mut Reader<'_>) -> Result<()> { - if !T::MAY_DEFER { - return T::read_option_into(self, r); - } - let mark = r.defer_mark(); - T::read_option_into(self, r)?; - r.defer_trail(mark, Step::Field(option_inner::)); - Ok(()) - } -} - -impl NinoWrite for Option { - const PREFETCH_BYTES: usize = T::PREFETCH_BYTES; - - #[inline(always)] - fn prefetch(&self) { - if let Some(v) = self { - v.prefetch(); - } - } - - #[inline(always)] - fn prefetch_members(&self) { - if let Some(v) = self { - v.prefetch_members(); - } - } - - #[inline] - fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { - T::write_option(self.as_ref(), w) - } -} - -/// `T` on the heap (a class that holds itself): the same bytes as `T`. -impl NinoRead for Box { - const MAY_DEFER: bool = T::MAY_DEFER; - const MIN_SIZE: usize = T::MIN_SIZE; - - #[inline] - fn read(r: &mut Reader<'_>) -> Result { - if !T::MAY_DEFER { - return T::read_boxed(r); - } - let mark = r.defer_mark(); - let value = T::read_boxed(r)?; - r.defer_trail(mark, Step::Field(box_inner::)); - Ok(value) - } - - #[inline] - fn read_option(r: &mut Reader<'_>) -> Result> { - if !T::MAY_DEFER { - return T::read_boxed_option(r); - } - let mark = r.defer_mark(); - let value = T::read_boxed_option(r)?; - r.defer_trail(mark, Step::Field(box_inner::)); - Ok(value) - } - - #[inline] - fn read_into(&mut self, r: &mut Reader<'_>) -> Result<()> { - if !T::MAY_DEFER { - return T::read_boxed_into(self, r); - } - let mark = r.defer_mark(); - T::read_boxed_into(self, r)?; - r.defer_trail(mark, Step::Field(box_inner::)); - Ok(()) - } - - #[inline] - fn read_option_into(slot: &mut Option, r: &mut Reader<'_>) -> Result<()> { - if !T::MAY_DEFER { - return T::read_boxed_option_into(slot, r); - } - let mark = r.defer_mark(); - T::read_boxed_option_into(slot, r)?; - r.defer_trail(mark, Step::Field(box_inner::)); - Ok(()) - } -} - -impl NinoWrite for Box { - // Its target's size and 64 for the target's own targets (not `T::PREFETCH_BYTES`: a type that holds itself through a - // `Box` would define the constant through itself). - const PREFETCH_BYTES: usize = core::mem::size_of::().saturating_add(64); - - #[inline(always)] - fn prefetch(&self) { - crate::simd::prefetch(&**self); - } - - #[inline(always)] - fn prefetch_members(&self) { - (**self).prefetch(); - } - - #[inline] - fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { - (**self).write(w) - } - - #[inline] - fn write_option<'a>(value: Option<&'a Self>, w: &mut Writer<'a>) -> Result<()> { - T::write_option(value.map(|b| &**b), w) - } -} - -// ---------------------------------------------------------------------- sequences - -/// Writes a length and the elements; `None` is null. -#[inline] -fn write_seq<'a, T: NinoWrite>(values: Option<&'a [T]>, w: &mut Writer<'a>) -> Result<()> { - match values { - None => { - w.null_length(); - Ok(()) - } - Some(values) => T::write_counted(values, w), - } -} - -/// An array, list or other sequence: its length (-1 null), then each element. -impl NinoRead for Vec { - const MAY_DEFER: bool = T::MAY_DEFER; - const MIN_SIZE: usize = 4; - - #[inline] - fn read(r: &mut Reader<'_>) -> Result { - let count = r.length_not_null(T::MIN_SIZE)?; - T::read_many(r, count) - } - - #[inline] - fn read_option(r: &mut Reader<'_>) -> Result> { - match r.length(T::MIN_SIZE)? { - None => Ok(None), - Some(count) => T::read_many(r, count).map(Some), - } - } - - #[inline] - fn read_into(&mut self, r: &mut Reader<'_>) -> Result<()> { - let count = r.length_not_null(T::MIN_SIZE)?; - T::read_many_into(r, count, self) - } - - #[inline] - fn read_option_into(slot: &mut Option, r: &mut Reader<'_>) -> Result<()> { - match (r.length(T::MIN_SIZE)?, slot) { - (None, slot) => *slot = None, - (Some(count), Some(values)) => T::read_many_into(r, count, values)?, - (Some(count), slot) => *slot = Some(T::read_many(r, count)?), - } - Ok(()) - } -} - -impl NinoWrite for Vec { - const PREFETCH_BYTES: usize = 64; - - #[inline(always)] - fn prefetch(&self) { - crate::simd::prefetch(self.as_ptr()); - } - - #[inline] - fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { - write_seq(Some(self.as_slice()), w) - } - - #[inline] - fn write_option<'a>(value: Option<&'a Self>, w: &mut Writer<'a>) -> Result<()> { - write_seq(value.map(Vec::as_slice), w) - } -} - -impl NinoWrite for [T] { - #[inline] - fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { - write_seq(Some(self), w) - } -} - -/// A queue (`Queue`, `LinkedList`): its length, then each element from the front. -impl NinoRead for VecDeque { - const MAY_DEFER: bool = T::MAY_DEFER; - const MIN_SIZE: usize = 4; - - fn read(r: &mut Reader<'_>) -> Result { - let count = r.length_not_null(T::MIN_SIZE)?; - if T::MAY_DEFER { - read_into_vec(r, count, deque_item::).map(VecDeque::from) - } else { - T::read_many(r, count).map(VecDeque::from) - } - } - - fn read_option(r: &mut Reader<'_>) -> Result> { - match r.length(T::MIN_SIZE)? { - None => Ok(None), - Some(count) if T::MAY_DEFER => read_into_vec(r, count, deque_item::).map(|v| Some(v.into())), - Some(count) => T::read_many(r, count).map(|v| Some(v.into())), - } - } - - /// Cleared and refilled, keeping its buffer. - fn read_into(&mut self, r: &mut Reader<'_>) -> Result<()> { - let count = r.length_not_null(T::MIN_SIZE)?; - refill_deque(self, r, count) - } - - fn read_option_into(slot: &mut Option, r: &mut Reader<'_>) -> Result<()> { - let Some(queue) = slot else { - *slot = Self::read_option(r)?; - return Ok(()); - }; - match r.length(T::MIN_SIZE)? { - None => *slot = None, - Some(count) => refill_deque(queue, r, count)?, - } - Ok(()) - } -} - -/// Empties `queue` and reads `count` elements into it, keeping its buffer when it has room. -fn refill_deque(queue: &mut VecDeque, r: &mut Reader<'_>, count: usize) -> Result<()> { - queue.clear(); - if queue.capacity() < count { - queue.reserve(r.capacity::(count)); - } - for i in 0..count { - if T::MAY_DEFER { - let mark = r.defer_mark(); - queue.push_back(T::read(r)?); - r.defer_trail(mark, Step::Index(deque_item::, i)); - } else { - queue.push_back(T::read(r)?); - } - } - Ok(()) -} - -impl NinoWrite for VecDeque { - fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { - w.length(self.len())?; - let (front, back) = self.as_slices(); - T::write_many(front, w)?; - T::write_many(back, w) - } - - fn write_option<'a>(value: Option<&'a Self>, w: &mut Writer<'a>) -> Result<()> { - w.or_null_length(value) - } -} - -macro_rules! set { - ($set:ident, $($bound:tt)*) => { - /// A set: its length, then each element. A repeated element is rejected. - impl NinoRead for $set { - const MIN_SIZE: usize = 4; - - fn read(r: &mut Reader<'_>) -> Result { - Self::read_option(r)?.ok_or_else(Error::null) - } - - fn read_option(r: &mut Reader<'_>) -> Result> { - let Some(count) = r.length(T::MIN_SIZE)? else { return Ok(None) }; - let mut set = set!(@new $set, r.capacity::(count)); - fill_set(&mut set, r, count)?; - Ok(Some(set)) - } - - /// Cleared and refilled, keeping its buffer. - fn read_into(&mut self, r: &mut Reader<'_>) -> Result<()> { - let count = r.length_not_null(T::MIN_SIZE)?; - self.clear(); - set!(@reserve $set, self, r, count); - fill_set(self, r, count) - } - - fn read_option_into(slot: &mut Option, r: &mut Reader<'_>) -> Result<()> { - match slot { - Some(set) => { - let Some(count) = r.length(T::MIN_SIZE)? else { - *slot = None; - return Ok(()); - }; - set.clear(); - set!(@reserve $set, set, r, count); - fill_set(set, r, count) - } - None => { - *slot = Self::read_option(r)?; - Ok(()) - } - } - } - } - - impl FillSet for $set { - #[inline] - fn insert_new(&mut self, value: T) -> bool { - self.insert(value) - } - } - - impl NinoWrite for $set { - fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { - w.length(self.len())?; - for v in self { - v.write(w)?; - } - Ok(()) - } - - fn write_option<'a>(value: Option<&'a Self>, w: &mut Writer<'a>) -> Result<()> { - w.or_null_length(value) - } - } - }; - (@new HashSet, $n:expr) => { HashSet::with_capacity($n) }; - (@new BTreeSet, $n:expr) => { { let _ = $n; BTreeSet::new() } }; - // Room for `count` elements when the set has less (within the read's allocation budget). - (@reserve HashSet, $set:expr, $r:expr, $count:expr) => { - if $set.capacity() < $count { - $set.reserve($r.capacity::($count)); - } - }; - (@reserve BTreeSet, $set:expr, $r:expr, $count:expr) => { - let _ = $count; - }; -} - -/// A set read into ([`fill_set`]): inserts, saying whether the value was new. -pub(crate) trait FillSet { - fn insert_new(&mut self, value: T) -> bool; -} - -/// Reads `count` elements into `set` (empty); an element read twice is an error. -#[inline] -pub(crate) fn fill_set>(set: &mut S, r: &mut Reader<'_>, count: usize) -> Result<()> { - for _ in 0..count { - if !set.insert_new(read_key::(r)?) { - return Err(Error::of(ErrorKind::DuplicateKey)); - } - } - Ok(()) -} - -set!(HashSet, Eq + Hash); -set!(BTreeSet, Ord); - -/// `NinoRead` for a hash map type `$map` whose keys have `$bound`: its length, then each key and value, read -/// into an empty map by `$fill(map, r, count)` (which rejects a repeated key); read into an existing map, it is cleared -/// and refilled, keeping its buffer. One body for `HashMap` and `IndexMap` (convert.rs). -macro_rules! map { - ($(#[$doc:meta])* $map:ident, $fill:ident, $($bound:tt)*) => { - $(#[$doc])* - impl NinoRead for $map - where - K: NinoRead + $($bound)*, - V: NinoRead, - S: BuildHasher + Default + 'static, - { - const MAY_DEFER: bool = V::MAY_DEFER; - const MIN_SIZE: usize = 4; - - fn read(r: &mut Reader<'_>) -> Result { - Self::read_option(r)?.ok_or_else(Error::null) - } - - fn read_option(r: &mut Reader<'_>) -> Result> { - let Some(count) = r.length(K::MIN_SIZE.saturating_add(V::MIN_SIZE))? else { return Ok(None) }; - let mut map = $map::with_capacity_and_hasher(r.capacity::<(K, V)>(count), S::default()); - $fill(&mut map, r, count)?; - Ok(Some(map)) - } - - /// Cleared and refilled, keeping its buffer. - fn read_into(&mut self, r: &mut Reader<'_>) -> Result<()> { - let count = r.length_not_null(K::MIN_SIZE.saturating_add(V::MIN_SIZE))?; - $crate::impls::map!(@refill self, r, count, $fill) - } - - fn read_option_into(slot: &mut Option, r: &mut Reader<'_>) -> Result<()> { - let Some(map) = slot else { - *slot = Self::read_option(r)?; - return Ok(()); - }; - match r.length(K::MIN_SIZE.saturating_add(V::MIN_SIZE))? { - None => *slot = None, - Some(count) => $crate::impls::map!(@refill map, r, count, $fill)?, - } - Ok(()) - } - } - }; - (@refill $map:expr, $r:expr, $count:expr, $fill:ident) => {{ - $map.clear(); - if $map.capacity() < $count { - $map.reserve($r.capacity::<(K, V)>($count)); - } - $fill($map, $r, $count) - }}; -} -pub(crate) use map; - -map!( - /// A dictionary: its length, then each key and value. A repeated key is rejected. - HashMap, - fill_hash_map, - Eq + Hash + Clone -); - -/// Reads `count` entries into `map` (empty); a key read twice is an error. -#[inline] -fn fill_hash_map(map: &mut HashMap, r: &mut Reader<'_>, count: usize) -> Result<()> -where - K: NinoRead + Eq + Hash + Clone, - V: NinoRead, - S: BuildHasher + Default + 'static, -{ - if entries_fixed_read::() { - if ENTRY_SLICES { - read_entries_fixed(r, count, |key, value| match map.entry(key) { - hash_map::Entry::Occupied(_) => Err(Error::of(ErrorKind::DuplicateKey)), - hash_map::Entry::Vacant(e) => { - e.insert(value); - Ok(()) - } - })?; - } else { - // A plain insert, as measured on Neoverse-N2. On the error, a repeated key holds its second value. - read_entries_fixed(r, count, |key, value| match map.insert(key, value) { - Some(_) => Err(Error::of(ErrorKind::DuplicateKey)), - None => Ok(()), - })?; - } - return Ok(()); - } - for _ in 0..count { - let key = read_key::(r)?; - let value = if V::MAY_DEFER { - let mark = r.defer_mark(); - let value = V::read(r)?; - if r.defer_mark() != mark { - let at = key.clone(); - r.defer_trail( - mark, - dyn_step(move |m| Some(m.downcast_mut::>()?.get_mut(&at)? as &mut dyn Any)), - ); - } - value - } else { - V::read(r)? - }; - match map.entry(key) { - hash_map::Entry::Occupied(_) => return Err(Error::of(ErrorKind::DuplicateKey)), - hash_map::Entry::Vacant(e) => { - e.insert(value); - } - } - } - Ok(()) -} - -/// A sorted dictionary: its length, then each key and value. A repeated key is rejected. -impl NinoRead for BTreeMap -where - K: NinoRead + Ord + Clone, - V: NinoRead, -{ - const MAY_DEFER: bool = V::MAY_DEFER; - const MIN_SIZE: usize = 4; - - fn read(r: &mut Reader<'_>) -> Result { - Self::read_option(r)?.ok_or_else(Error::null) - } - - fn read_option(r: &mut Reader<'_>) -> Result> { - let Some(count) = r.length(K::MIN_SIZE.saturating_add(V::MIN_SIZE))? else { return Ok(None) }; - let mut map = BTreeMap::new(); - fill_btree_map(&mut map, r, count)?; - Ok(Some(map)) - } - - /// Cleared and refilled. - fn read_into(&mut self, r: &mut Reader<'_>) -> Result<()> { - let count = r.length_not_null(K::MIN_SIZE.saturating_add(V::MIN_SIZE))?; - self.clear(); - fill_btree_map(self, r, count) - } - - fn read_option_into(slot: &mut Option, r: &mut Reader<'_>) -> Result<()> { - let Some(map) = slot else { - *slot = Self::read_option(r)?; - return Ok(()); - }; - match r.length(K::MIN_SIZE.saturating_add(V::MIN_SIZE))? { - None => *slot = None, - Some(count) => { - map.clear(); - fill_btree_map(map, r, count)?; - } - } - Ok(()) - } -} - -/// Reads `count` entries into `map` (empty); a key read twice is an error. -#[inline] -fn fill_btree_map(map: &mut BTreeMap, r: &mut Reader<'_>, count: usize) -> Result<()> -where - K: NinoRead + Ord + Clone, - V: NinoRead, -{ - if entries_fixed_read::() { - return read_entries_fixed(r, count, |key, value| match map.insert(key, value) { - Some(_) => Err(Error::of(ErrorKind::DuplicateKey)), - None => Ok(()), - }); - } - for _ in 0..count { - let key = read_key::(r)?; - let value = if V::MAY_DEFER { - let mark = r.defer_mark(); - let value = V::read(r)?; - if r.defer_mark() != mark { - let at = key.clone(); - r.defer_trail( - mark, - dyn_step(move |m| Some(m.downcast_mut::>()?.get_mut(&at)? as &mut dyn Any)), - ); - } - value - } else { - V::read(r)? - }; - if map.insert(key, value).is_some() { - return Err(Error::of(ErrorKind::DuplicateKey)); - } - } - Ok(()) -} - -impl NinoWrite for HashMap { - fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { - if entries_fixed(K::FIXED_SIZE, V::FIXED_SIZE) { - return write_entries_fixed(self.iter(), w); - } - w.length(self.len())?; - for (k, v) in self { - k.write(w)?; - v.write(w)?; - } - Ok(()) - } - - fn write_option<'a>(value: Option<&'a Self>, w: &mut Writer<'a>) -> Result<()> { - w.or_null_length(value) - } -} - -impl NinoWrite for BTreeMap { - fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { - if entries_fixed(K::FIXED_SIZE, V::FIXED_SIZE) { - return write_entries_fixed(self.iter(), w); - } - w.length(self.len())?; - for (k, v) in self { - k.write(w)?; - v.write(w)?; - } - Ok(()) - } - - fn write_option<'a>(value: Option<&'a Self>, w: &mut Writer<'a>) -> Result<()> { - w.or_null_length(value) - } -} - -// ---------------------------------------------------------------------- tuples - -macro_rules! tuple { - ($($name:ident $index:tt),+) => { - /// `ValueTuple`, `KeyValuePair` (and, inside an `Option`, `Tuple`): the items in order, no header. - impl<$($name: NinoRead),+> NinoRead for ($($name,)+) { - const MAY_DEFER: bool = false $(|| $name::MAY_DEFER)+; - const MIN_SIZE: usize = 0usize $(.saturating_add($name::MIN_SIZE))+; - /// The items' sizes added up when every item is fixed-size. - const FIXED_SIZE: usize = - if false $(|| <$name as NinoRead>::FIXED_SIZE == 0)+ { 0 } else { 0usize $(.saturating_add(<$name as NinoRead>::FIXED_SIZE))+ }; - - // The last item's tail is not read. - #[allow(unused_assignments)] - #[inline] - fn decode_fixed(bytes: &[u8]) -> Result { - let mut rest = bytes; - Ok(($({ - let (item, tail) = rest.split_at_checked(<$name as NinoRead>::FIXED_SIZE).ok_or_else(Error::end)?; - rest = tail; - $name::decode_fixed(item)? - },)+)) - } - - #[inline] - fn read(r: &mut Reader<'_>) -> Result { - Ok(($( - r.read_member::<$name>(|p| Some(&mut p.downcast_mut::()?.$index as &mut dyn Any))?, - )+)) - } - } - - impl<$($name: NinoWrite),+> NinoWrite for ($($name,)+) { - const FIXED_SIZE: usize = - if false $(|| <$name as NinoWrite>::FIXED_SIZE == 0)+ { 0 } else { 0usize $(.saturating_add(<$name as NinoWrite>::FIXED_SIZE))+ }; - - // The last item's tail is not written. - #[allow(unused_assignments)] - #[inline] - fn encode_fixed(&self, out: &mut [u8]) { - let mut rest = out; - $( - let Some((item, tail)) = rest.split_at_mut_checked(<$name as NinoWrite>::FIXED_SIZE) else { return }; - rest = tail; - self.$index.encode_fixed(item); - )+ - } - - #[inline] - fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { - $(self.$index.write(w)?;)+ - Ok(()) - } - } - }; -} - -tuple!(A 0); -tuple!(A 0, B 1); -tuple!(A 0, B 1, C 2); -tuple!(A 0, B 1, C 2, D 3); -tuple!(A 0, B 1, C 2, D 3, E 4); -tuple!(A 0, B 1, C 2, D 3, E 4, F 5); -tuple!(A 0, B 1, C 2, D 3, E 4, F 5, G 6); +// Keep these files in this module and in their original order. The map macro is shared with IndexMap. +// A module boundary also changes rustc's codegen unit partitioning, even for untouched functions (#248). +include!("impls/numbers.rs"); +include!("impls/strings.rs"); +include!("impls/wrappers.rs"); +include!("impls/sequences.rs"); +include!("impls/sets.rs"); +include!("impls/maps.rs"); +include!("impls/tuples.rs"); #[cfg(test)] #[allow(clippy::indexing_slicing, clippy::arithmetic_side_effects, clippy::unwrap_used)] diff --git a/runtimes/rust/src/impls/maps.rs b/runtimes/rust/src/impls/maps.rs new file mode 100644 index 000000000..423378667 --- /dev/null +++ b/runtimes/rust/src/impls/maps.rs @@ -0,0 +1,228 @@ +/// `NinoRead` for a hash map type `$map` whose keys have `$bound`: its length, then each key and value, read +/// into an empty map by `$fill(map, r, count)` (which rejects a repeated key); read into an existing map, it is cleared +/// and refilled, keeping its buffer. One body for `HashMap` and `IndexMap` (convert.rs). +macro_rules! map { + ($(#[$doc:meta])* $map:ident, $fill:ident, $($bound:tt)*) => { + $(#[$doc])* + impl NinoRead for $map + where + K: NinoRead + $($bound)*, + V: NinoRead, + S: BuildHasher + Default + 'static, + { + const MAY_DEFER: bool = V::MAY_DEFER; + const MIN_SIZE: usize = 4; + + fn read(r: &mut Reader<'_>) -> Result { + Self::read_option(r)?.ok_or_else(Error::null) + } + + fn read_option(r: &mut Reader<'_>) -> Result> { + let Some(count) = r.length(K::MIN_SIZE.saturating_add(V::MIN_SIZE))? else { return Ok(None) }; + let mut map = $map::with_capacity_and_hasher(r.capacity::<(K, V)>(count), S::default()); + $fill(&mut map, r, count)?; + Ok(Some(map)) + } + + /// Cleared and refilled, keeping its buffer. + fn read_into(&mut self, r: &mut Reader<'_>) -> Result<()> { + let count = r.length_not_null(K::MIN_SIZE.saturating_add(V::MIN_SIZE))?; + $crate::impls::map!(@refill self, r, count, $fill) + } + + fn read_option_into(slot: &mut Option, r: &mut Reader<'_>) -> Result<()> { + let Some(map) = slot else { + *slot = Self::read_option(r)?; + return Ok(()); + }; + match r.length(K::MIN_SIZE.saturating_add(V::MIN_SIZE))? { + None => *slot = None, + Some(count) => $crate::impls::map!(@refill map, r, count, $fill)?, + } + Ok(()) + } + } + }; + (@refill $map:expr, $r:expr, $count:expr, $fill:ident) => {{ + $map.clear(); + if $map.capacity() < $count { + $map.reserve($r.capacity::<(K, V)>($count)); + } + $fill($map, $r, $count) + }}; +} +pub(crate) use map; + +map!( + /// A dictionary: its length, then each key and value. A repeated key is rejected. + HashMap, + fill_hash_map, + Eq + Hash + Clone +); + +/// Reads `count` entries into `map` (empty); a key read twice is an error. +#[inline] +fn fill_hash_map(map: &mut HashMap, r: &mut Reader<'_>, count: usize) -> Result<()> +where + K: NinoRead + Eq + Hash + Clone, + V: NinoRead, + S: BuildHasher + Default + 'static, +{ + if entries_fixed_read::() { + if ENTRY_SLICES { + read_entries_fixed(r, count, |key, value| match map.entry(key) { + hash_map::Entry::Occupied(_) => Err(Error::of(ErrorKind::DuplicateKey)), + hash_map::Entry::Vacant(e) => { + e.insert(value); + Ok(()) + } + })?; + } else { + // A plain insert, as measured on Neoverse-N2. On the error, a repeated key holds its second value. + read_entries_fixed(r, count, |key, value| match map.insert(key, value) { + Some(_) => Err(Error::of(ErrorKind::DuplicateKey)), + None => Ok(()), + })?; + } + return Ok(()); + } + for _ in 0..count { + let key = read_key::(r)?; + let value = if V::MAY_DEFER { + let mark = r.defer_mark(); + let value = V::read(r)?; + if r.defer_mark() != mark { + let at = key.clone(); + r.defer_trail( + mark, + dyn_step(move |m| Some(m.downcast_mut::>()?.get_mut(&at)? as &mut dyn Any)), + ); + } + value + } else { + V::read(r)? + }; + match map.entry(key) { + hash_map::Entry::Occupied(_) => return Err(Error::of(ErrorKind::DuplicateKey)), + hash_map::Entry::Vacant(e) => { + e.insert(value); + } + } + } + Ok(()) +} + +/// A sorted dictionary: its length, then each key and value. A repeated key is rejected. +impl NinoRead for BTreeMap +where + K: NinoRead + Ord + Clone, + V: NinoRead, +{ + const MAY_DEFER: bool = V::MAY_DEFER; + const MIN_SIZE: usize = 4; + + fn read(r: &mut Reader<'_>) -> Result { + Self::read_option(r)?.ok_or_else(Error::null) + } + + fn read_option(r: &mut Reader<'_>) -> Result> { + let Some(count) = r.length(K::MIN_SIZE.saturating_add(V::MIN_SIZE))? else { return Ok(None) }; + let mut map = BTreeMap::new(); + fill_btree_map(&mut map, r, count)?; + Ok(Some(map)) + } + + /// Cleared and refilled. + fn read_into(&mut self, r: &mut Reader<'_>) -> Result<()> { + let count = r.length_not_null(K::MIN_SIZE.saturating_add(V::MIN_SIZE))?; + self.clear(); + fill_btree_map(self, r, count) + } + + fn read_option_into(slot: &mut Option, r: &mut Reader<'_>) -> Result<()> { + let Some(map) = slot else { + *slot = Self::read_option(r)?; + return Ok(()); + }; + match r.length(K::MIN_SIZE.saturating_add(V::MIN_SIZE))? { + None => *slot = None, + Some(count) => { + map.clear(); + fill_btree_map(map, r, count)?; + } + } + Ok(()) + } +} + +/// Reads `count` entries into `map` (empty); a key read twice is an error. +#[inline] +fn fill_btree_map(map: &mut BTreeMap, r: &mut Reader<'_>, count: usize) -> Result<()> +where + K: NinoRead + Ord + Clone, + V: NinoRead, +{ + if entries_fixed_read::() { + return read_entries_fixed(r, count, |key, value| match map.insert(key, value) { + Some(_) => Err(Error::of(ErrorKind::DuplicateKey)), + None => Ok(()), + }); + } + for _ in 0..count { + let key = read_key::(r)?; + let value = if V::MAY_DEFER { + let mark = r.defer_mark(); + let value = V::read(r)?; + if r.defer_mark() != mark { + let at = key.clone(); + r.defer_trail( + mark, + dyn_step(move |m| Some(m.downcast_mut::>()?.get_mut(&at)? as &mut dyn Any)), + ); + } + value + } else { + V::read(r)? + }; + if map.insert(key, value).is_some() { + return Err(Error::of(ErrorKind::DuplicateKey)); + } + } + Ok(()) +} + +impl NinoWrite for HashMap { + fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { + if entries_fixed(K::FIXED_SIZE, V::FIXED_SIZE) { + return write_entries_fixed(self.iter(), w); + } + w.length(self.len())?; + for (k, v) in self { + k.write(w)?; + v.write(w)?; + } + Ok(()) + } + + fn write_option<'a>(value: Option<&'a Self>, w: &mut Writer<'a>) -> Result<()> { + w.or_null_length(value) + } +} + +impl NinoWrite for BTreeMap { + fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { + if entries_fixed(K::FIXED_SIZE, V::FIXED_SIZE) { + return write_entries_fixed(self.iter(), w); + } + w.length(self.len())?; + for (k, v) in self { + k.write(w)?; + v.write(w)?; + } + Ok(()) + } + + fn write_option<'a>(value: Option<&'a Self>, w: &mut Writer<'a>) -> Result<()> { + w.or_null_length(value) + } +} diff --git a/runtimes/rust/src/impls/numbers.rs b/runtimes/rust/src/impls/numbers.rs new file mode 100644 index 000000000..95d94773b --- /dev/null +++ b/runtimes/rust/src/impls/numbers.rs @@ -0,0 +1,263 @@ +// ---------------------------------------------------------------------- numbers + +macro_rules! number { + ($($t:ty, $n:literal, $method:ident;)*) => {$( + impl NinoRead for $t { + const MIN_SIZE: usize = $n; + const FIXED_SIZE: usize = $n; + + #[inline] + fn decode_fixed(bytes: &[u8]) -> Result { + bytes.first_chunk::<$n>().map(|b| <$t>::from_le_bytes(*b)).ok_or_else(Error::end) + } + + #[inline] + fn read(r: &mut Reader<'_>) -> Result { + r.$method() + } + + #[inline] + fn read_many(r: &mut Reader<'_>, count: usize) -> Result> { + let size = count.checked_mul($n).ok_or_else(Error::too_large)?; + let bytes = r.take(size)?; + Ok(bytes.as_chunks::<$n>().0.iter().map(|c| <$t>::from_le_bytes(*c)).collect()) + } + + #[inline] + fn read_many_into(r: &mut Reader<'_>, count: usize, values: &mut Vec) -> Result<()> { + let size = count.checked_mul($n).ok_or_else(Error::too_large)?; + let bytes = r.take(size)?; + values.clear(); + values.extend(bytes.as_chunks::<$n>().0.iter().map(|c| <$t>::from_le_bytes(*c))); + Ok(()) + } + } + + impl NinoWrite for $t { + const FIXED_SIZE: usize = $n; + + #[inline] + fn encode_fixed(&self, out: &mut [u8]) { + if let Some(dst) = out.first_chunk_mut::<$n>() { + *dst = self.to_le_bytes(); + } + } + + #[inline] + fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { + w.$method(*self); + Ok(()) + } + + #[inline] + fn write_many<'a>(values: &'a [Self], w: &mut Writer<'a>) -> Result<()> { + w.encoded(values, |v| v.to_le_bytes()); + Ok(()) + } + + #[inline] + fn write_counted<'a>(values: &'a [Self], w: &mut Writer<'a>) -> Result<()> { + w.counted(values, |v| v.to_le_bytes()) + } + } + )*}; +} + +number! { + i16, 2, i16; + u16, 2, u16; + i32, 4, i32; + u32, 4, u32; + i64, 8, i64; + u64, 8, u64; + i128, 16, i128; + u128, 16, u128; + f32, 4, f32; + f64, 8, f64; +} + +impl NinoRead for u8 { + const MIN_SIZE: usize = 1; + const FIXED_SIZE: usize = 1; + + #[inline] + fn decode_fixed(bytes: &[u8]) -> Result { + bytes.first().copied().ok_or_else(Error::end) + } + + #[inline] + fn read(r: &mut Reader<'_>) -> Result { + r.u8() + } + + /// A `byte[]`: one copy. + #[inline] + fn read_many(r: &mut Reader<'_>, count: usize) -> Result> { + r.take(count).map(<[u8]>::to_vec) + } + + #[inline] + fn read_many_into(r: &mut Reader<'_>, count: usize, values: &mut Vec) -> Result<()> { + let bytes = r.take(count)?; + values.clear(); + values.extend_from_slice(bytes); + Ok(()) + } +} + +impl NinoWrite for u8 { + const FIXED_SIZE: usize = 1; + + #[inline] + fn encode_fixed(&self, out: &mut [u8]) { + if let Some(b) = out.first_mut() { + *b = *self; + } + } + + #[inline] + fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { + w.u8(*self); + Ok(()) + } + + #[inline] + fn write_many<'a>(values: &'a [Self], w: &mut Writer<'a>) -> Result<()> { + w.bytes(values); + Ok(()) + } +} + +impl NinoRead for i8 { + const MIN_SIZE: usize = 1; + const FIXED_SIZE: usize = 1; + + #[inline] + fn decode_fixed(bytes: &[u8]) -> Result { + bytes.first().map(|&b| b as i8).ok_or_else(Error::end) + } + + #[inline] + fn read(r: &mut Reader<'_>) -> Result { + r.i8() + } + + #[inline] + fn read_many(r: &mut Reader<'_>, count: usize) -> Result> { + Ok(r.take(count)?.iter().map(|&b| b as i8).collect()) + } + + #[inline] + fn read_many_into(r: &mut Reader<'_>, count: usize, values: &mut Vec) -> Result<()> { + let bytes = r.take(count)?; + values.clear(); + values.extend(bytes.iter().map(|&b| b as i8)); + Ok(()) + } +} + +impl NinoWrite for i8 { + const FIXED_SIZE: usize = 1; + + #[inline] + fn encode_fixed(&self, out: &mut [u8]) { + if let Some(b) = out.first_mut() { + *b = *self as u8; + } + } + + #[inline] + fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { + w.i8(*self); + Ok(()) + } + + #[inline] + fn write_many<'a>(values: &'a [Self], w: &mut Writer<'a>) -> Result<()> { + w.encoded(values, |&v| [v as u8]); + Ok(()) + } + + #[inline] + fn write_counted<'a>(values: &'a [Self], w: &mut Writer<'a>) -> Result<()> { + w.counted(values, |&v| [v as u8]) + } +} + +impl NinoRead for bool { + const MIN_SIZE: usize = 1; + const FIXED_SIZE: usize = 1; + + #[inline] + fn decode_fixed(bytes: &[u8]) -> Result { + match bytes.first() { + Some(0) => Ok(false), + Some(1) => Ok(true), + Some(&b) => Err(Error::new(ErrorKind::InvalidBool, i32::from(b))), + None => Err(Error::end()), + } + } + + #[inline] + fn read(r: &mut Reader<'_>) -> Result { + r.bool() + } + + /// One pass that ORs every byte (no early exit, so it runs a vector at a time): a byte other than 0 and 1 sets + /// a bit above the lowest. Only then is the bad byte looked for. + #[inline] + fn read_many(r: &mut Reader<'_>, count: usize) -> Result> { + let bytes = r.take(count)?; + if bytes.iter().fold(0u8, |a, &b| a | b) > 1 { + return Err(invalid_bool(bytes)); + } + Ok(bytes.iter().map(|&b| b != 0).collect()) + } + + #[inline] + fn read_many_into(r: &mut Reader<'_>, count: usize, values: &mut Vec) -> Result<()> { + let bytes = r.take(count)?; + if bytes.iter().fold(0u8, |a, &b| a | b) > 1 { + return Err(invalid_bool(bytes)); + } + values.clear(); + values.extend(bytes.iter().map(|&b| b != 0)); + Ok(()) + } +} + +/// The error for the first byte of `bytes` that is not 0 or 1. +#[cold] +#[inline(never)] +fn invalid_bool(bytes: &[u8]) -> Error { + let b = bytes.iter().copied().find(|&b| b > 1).unwrap_or(2); + Error::new(ErrorKind::InvalidBool, i32::from(b)) +} + +impl NinoWrite for bool { + const FIXED_SIZE: usize = 1; + + #[inline] + fn encode_fixed(&self, out: &mut [u8]) { + if let Some(b) = out.first_mut() { + *b = u8::from(*self); + } + } + + #[inline] + fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { + w.bool(*self); + Ok(()) + } + + #[inline] + fn write_many<'a>(values: &'a [Self], w: &mut Writer<'a>) -> Result<()> { + w.encoded(values, |&v| [u8::from(v)]); + Ok(()) + } + + #[inline] + fn write_counted<'a>(values: &'a [Self], w: &mut Writer<'a>) -> Result<()> { + w.counted(values, |&v| [u8::from(v)]) + } +} diff --git a/runtimes/rust/src/impls/sequences.rs b/runtimes/rust/src/impls/sequences.rs new file mode 100644 index 000000000..531bcc97a --- /dev/null +++ b/runtimes/rust/src/impls/sequences.rs @@ -0,0 +1,147 @@ +// ---------------------------------------------------------------------- sequences + +/// Writes a length and the elements; `None` is null. +#[inline] +fn write_seq<'a, T: NinoWrite>(values: Option<&'a [T]>, w: &mut Writer<'a>) -> Result<()> { + match values { + None => { + w.null_length(); + Ok(()) + } + Some(values) => T::write_counted(values, w), + } +} + +/// An array, list or other sequence: its length (-1 null), then each element. +impl NinoRead for Vec { + const MAY_DEFER: bool = T::MAY_DEFER; + const MIN_SIZE: usize = 4; + + #[inline] + fn read(r: &mut Reader<'_>) -> Result { + let count = r.length_not_null(T::MIN_SIZE)?; + T::read_many(r, count) + } + + #[inline] + fn read_option(r: &mut Reader<'_>) -> Result> { + match r.length(T::MIN_SIZE)? { + None => Ok(None), + Some(count) => T::read_many(r, count).map(Some), + } + } + + #[inline] + fn read_into(&mut self, r: &mut Reader<'_>) -> Result<()> { + let count = r.length_not_null(T::MIN_SIZE)?; + T::read_many_into(r, count, self) + } + + #[inline] + fn read_option_into(slot: &mut Option, r: &mut Reader<'_>) -> Result<()> { + match (r.length(T::MIN_SIZE)?, slot) { + (None, slot) => *slot = None, + (Some(count), Some(values)) => T::read_many_into(r, count, values)?, + (Some(count), slot) => *slot = Some(T::read_many(r, count)?), + } + Ok(()) + } +} + +impl NinoWrite for Vec { + const PREFETCH_BYTES: usize = 64; + + #[inline(always)] + fn prefetch(&self) { + crate::simd::prefetch(self.as_ptr()); + } + + #[inline] + fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { + write_seq(Some(self.as_slice()), w) + } + + #[inline] + fn write_option<'a>(value: Option<&'a Self>, w: &mut Writer<'a>) -> Result<()> { + write_seq(value.map(Vec::as_slice), w) + } +} + +impl NinoWrite for [T] { + #[inline] + fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { + write_seq(Some(self), w) + } +} + +/// A queue (`Queue`, `LinkedList`): its length, then each element from the front. +impl NinoRead for VecDeque { + const MAY_DEFER: bool = T::MAY_DEFER; + const MIN_SIZE: usize = 4; + + fn read(r: &mut Reader<'_>) -> Result { + let count = r.length_not_null(T::MIN_SIZE)?; + if T::MAY_DEFER { + read_into_vec(r, count, deque_item::).map(VecDeque::from) + } else { + T::read_many(r, count).map(VecDeque::from) + } + } + + fn read_option(r: &mut Reader<'_>) -> Result> { + match r.length(T::MIN_SIZE)? { + None => Ok(None), + Some(count) if T::MAY_DEFER => read_into_vec(r, count, deque_item::).map(|v| Some(v.into())), + Some(count) => T::read_many(r, count).map(|v| Some(v.into())), + } + } + + /// Cleared and refilled, keeping its buffer. + fn read_into(&mut self, r: &mut Reader<'_>) -> Result<()> { + let count = r.length_not_null(T::MIN_SIZE)?; + refill_deque(self, r, count) + } + + fn read_option_into(slot: &mut Option, r: &mut Reader<'_>) -> Result<()> { + let Some(queue) = slot else { + *slot = Self::read_option(r)?; + return Ok(()); + }; + match r.length(T::MIN_SIZE)? { + None => *slot = None, + Some(count) => refill_deque(queue, r, count)?, + } + Ok(()) + } +} + +/// Empties `queue` and reads `count` elements into it, keeping its buffer when it has room. +fn refill_deque(queue: &mut VecDeque, r: &mut Reader<'_>, count: usize) -> Result<()> { + queue.clear(); + if queue.capacity() < count { + queue.reserve(r.capacity::(count)); + } + for i in 0..count { + if T::MAY_DEFER { + let mark = r.defer_mark(); + queue.push_back(T::read(r)?); + r.defer_trail(mark, Step::Index(deque_item::, i)); + } else { + queue.push_back(T::read(r)?); + } + } + Ok(()) +} + +impl NinoWrite for VecDeque { + fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { + w.length(self.len())?; + let (front, back) = self.as_slices(); + T::write_many(front, w)?; + T::write_many(back, w) + } + + fn write_option<'a>(value: Option<&'a Self>, w: &mut Writer<'a>) -> Result<()> { + w.or_null_length(value) + } +} diff --git a/runtimes/rust/src/impls/sets.rs b/runtimes/rust/src/impls/sets.rs new file mode 100644 index 000000000..ce3396e59 --- /dev/null +++ b/runtimes/rust/src/impls/sets.rs @@ -0,0 +1,110 @@ +macro_rules! set { + ($set:ident, $($bound:tt)*) => { + /// A set: its length, then each element. A repeated element is rejected. + impl NinoRead for $set { + const MIN_SIZE: usize = 4; + + fn read(r: &mut Reader<'_>) -> Result { + Self::read_option(r)?.ok_or_else(Error::null) + } + + fn read_option(r: &mut Reader<'_>) -> Result> { + let Some(count) = r.length(T::MIN_SIZE)? else { return Ok(None) }; + let mut set = set!(@new $set, r.capacity::(count)); + fill_set(&mut set, r, count)?; + Ok(Some(set)) + } + + /// Cleared and refilled, keeping its buffer. + fn read_into(&mut self, r: &mut Reader<'_>) -> Result<()> { + let count = r.length_not_null(T::MIN_SIZE)?; + self.clear(); + set!(@reserve $set, self, r, count); + fill_set(self, r, count) + } + + fn read_option_into(slot: &mut Option, r: &mut Reader<'_>) -> Result<()> { + match slot { + Some(set) => { + let Some(count) = r.length(T::MIN_SIZE)? else { + *slot = None; + return Ok(()); + }; + set.clear(); + set!(@reserve $set, set, r, count); + fill_set(set, r, count) + } + None => { + *slot = Self::read_option(r)?; + Ok(()) + } + } + } + } + + impl FillSet for $set { + #[inline] + fn insert_new(&mut self, value: T) -> bool { + self.insert(value) + } + } + + impl NinoWrite for $set { + fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { + write_set(self.iter(), w) + } + + fn write_option<'a>(value: Option<&'a Self>, w: &mut Writer<'a>) -> Result<()> { + w.or_null_length(value) + } + } + }; + (@new HashSet, $n:expr) => { HashSet::with_capacity($n) }; + (@new BTreeSet, $n:expr) => { { let _ = $n; BTreeSet::new() } }; + // Room for `count` elements when the set has less (within the read's allocation budget). + (@reserve HashSet, $set:expr, $r:expr, $count:expr) => { + if $set.capacity() < $count { + $set.reserve($r.capacity::($count)); + } + }; + (@reserve BTreeSet, $set:expr, $r:expr, $count:expr) => { + let _ = $count; + }; +} + +/// A set read into ([`fill_set`]): inserts, saying whether the value was new. +pub(crate) trait FillSet { + fn insert_new(&mut self, value: T) -> bool; +} + +/// Reads `count` elements into `set` (empty); an element read twice is an error. +#[inline] +pub(crate) fn fill_set>(set: &mut S, r: &mut Reader<'_>, count: usize) -> Result<()> { + for _ in 0..count { + if !set.insert_new(read_key::(r)?) { + return Err(Error::of(ErrorKind::DuplicateKey)); + } + } + Ok(()) +} + +set!(HashSet, Eq + Hash); +set!(BTreeSet, Ord); + +/// Writes a set's length and elements in iteration order, taking one reservation for fixed-size elements. +#[inline] +pub(crate) fn write_set<'a, T: NinoWrite + 'a>( + values: impl ExactSizeIterator, + w: &mut Writer<'a>, +) -> Result<()> { + if T::FIXED_SIZE != 0 && T::FIXED_SIZE <= crate::simd::FIXED_STACK { + let count = i32::try_from(values.len()).map_err(|_| Error::too_large())?; + crate::simd::extend_fixed_iter(w.buffer(), count.to_le_bytes(), values, T::FIXED_SIZE, T::encode_fixed); + return Ok(()); + } + w.length(values.len())?; + for value in values { + value.write(w)?; + } + Ok(()) +} diff --git a/runtimes/rust/src/impls/strings.rs b/runtimes/rust/src/impls/strings.rs new file mode 100644 index 000000000..dbcc276a9 --- /dev/null +++ b/runtimes/rust/src/impls/strings.rs @@ -0,0 +1,65 @@ +// ---------------------------------------------------------------------- strings + +impl NinoRead for String { + const MIN_SIZE: usize = 1; + + #[inline] + fn read(r: &mut Reader<'_>) -> Result { + r.string()?.ok_or_else(Error::null) + } + + #[inline] + fn read_option(r: &mut Reader<'_>) -> Result> { + r.string() + } + + #[inline] + fn read_many(r: &mut Reader<'_>, count: usize) -> Result> { + r.strings(count) + } + + /// Strings are read new (a list of them by the batched reader when the `Vec` is empty); the `Vec`'s buffer is + /// kept. + #[inline] + fn read_many_into(r: &mut Reader<'_>, count: usize, values: &mut Vec) -> Result<()> { + if values.capacity() < count { + *values = r.strings(count)?; + return Ok(()); + } + crate::impls::read_each_into(r, count, values) + } +} + +impl NinoWrite for String { + const PREFETCH_BYTES: usize = 64; + + #[inline(always)] + fn prefetch(&self) { + crate::simd::prefetch(self.as_ptr()); + } + + #[inline] + fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { + w.string(Some(self)) + } + + #[inline] + fn write_many<'a>(values: &'a [Self], w: &mut Writer<'a>) -> Result<()> { + if prefetches::(values.len()) { + return crate::strings::write_strings_prefetched(w, values); + } + crate::strings::write_strings(w, values) + } + + #[inline] + fn write_option<'a>(value: Option<&'a Self>, w: &mut Writer<'a>) -> Result<()> { + w.string(value.map(String::as_str)) + } +} + +impl NinoWrite for str { + #[inline] + fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { + w.string(Some(self)) + } +} diff --git a/runtimes/rust/src/impls/tuples.rs b/runtimes/rust/src/impls/tuples.rs new file mode 100644 index 000000000..0e341e63d --- /dev/null +++ b/runtimes/rust/src/impls/tuples.rs @@ -0,0 +1,64 @@ +// ---------------------------------------------------------------------- tuples + +macro_rules! tuple { + ($($name:ident $index:tt),+) => { + /// `ValueTuple`, `KeyValuePair` (and, inside an `Option`, `Tuple`): the items in order, no header. + impl<$($name: NinoRead),+> NinoRead for ($($name,)+) { + const MAY_DEFER: bool = false $(|| $name::MAY_DEFER)+; + const MIN_SIZE: usize = 0usize $(.saturating_add($name::MIN_SIZE))+; + /// The items' sizes added up when every item is fixed-size. + const FIXED_SIZE: usize = + if false $(|| <$name as NinoRead>::FIXED_SIZE == 0)+ { 0 } else { 0usize $(.saturating_add(<$name as NinoRead>::FIXED_SIZE))+ }; + + // The last item's tail is not read. + #[allow(unused_assignments)] + #[inline] + fn decode_fixed(bytes: &[u8]) -> Result { + let mut rest = bytes; + Ok(($({ + let (item, tail) = rest.split_at_checked(<$name as NinoRead>::FIXED_SIZE).ok_or_else(Error::end)?; + rest = tail; + $name::decode_fixed(item)? + },)+)) + } + + #[inline] + fn read(r: &mut Reader<'_>) -> Result { + Ok(($( + r.read_member::<$name>(|p| Some(&mut p.downcast_mut::()?.$index as &mut dyn Any))?, + )+)) + } + } + + impl<$($name: NinoWrite),+> NinoWrite for ($($name,)+) { + const FIXED_SIZE: usize = + if false $(|| <$name as NinoWrite>::FIXED_SIZE == 0)+ { 0 } else { 0usize $(.saturating_add(<$name as NinoWrite>::FIXED_SIZE))+ }; + + // The last item's tail is not written. + #[allow(unused_assignments)] + #[inline] + fn encode_fixed(&self, out: &mut [u8]) { + let mut rest = out; + $( + let Some((item, tail)) = rest.split_at_mut_checked(<$name as NinoWrite>::FIXED_SIZE) else { return }; + rest = tail; + self.$index.encode_fixed(item); + )+ + } + + #[inline] + fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { + $(self.$index.write(w)?;)+ + Ok(()) + } + } + }; +} + +tuple!(A 0); +tuple!(A 0, B 1); +tuple!(A 0, B 1, C 2); +tuple!(A 0, B 1, C 2, D 3); +tuple!(A 0, B 1, C 2, D 3, E 4); +tuple!(A 0, B 1, C 2, D 3, E 4, F 5); +tuple!(A 0, B 1, C 2, D 3, E 4, F 5, G 6); diff --git a/runtimes/rust/src/impls/wrappers.rs b/runtimes/rust/src/impls/wrappers.rs new file mode 100644 index 000000000..98e464be3 --- /dev/null +++ b/runtimes/rust/src/impls/wrappers.rs @@ -0,0 +1,136 @@ +// ---------------------------------------------------------------------- Option, Box + +fn option_inner(v: &mut dyn Any) -> Option<&mut dyn Any> { + v.downcast_mut::>()?.as_mut().map(|x| x as &mut dyn Any) +} + +fn box_inner(v: &mut dyn Any) -> Option<&mut dyn Any> { + Some(&mut **v.downcast_mut::>()? as &mut dyn Any) +} + +/// A value that may be null, in `T`'s null encoding (see [`NinoRead::read_option`]). +impl NinoRead for Option { + const MAY_DEFER: bool = T::MAY_DEFER; + const MIN_SIZE: usize = 1; + + #[inline] + fn read(r: &mut Reader<'_>) -> Result { + if !T::MAY_DEFER { + return T::read_option(r); + } + let mark = r.defer_mark(); + let value = T::read_option(r)?; + r.defer_trail(mark, Step::Field(option_inner::)); + Ok(value) + } + + #[inline] + fn read_into(&mut self, r: &mut Reader<'_>) -> Result<()> { + if !T::MAY_DEFER { + return T::read_option_into(self, r); + } + let mark = r.defer_mark(); + T::read_option_into(self, r)?; + r.defer_trail(mark, Step::Field(option_inner::)); + Ok(()) + } +} + +impl NinoWrite for Option { + const PREFETCH_BYTES: usize = T::PREFETCH_BYTES; + + #[inline(always)] + fn prefetch(&self) { + if let Some(v) = self { + v.prefetch(); + } + } + + #[inline(always)] + fn prefetch_members(&self) { + if let Some(v) = self { + v.prefetch_members(); + } + } + + #[inline] + fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { + T::write_option(self.as_ref(), w) + } +} + +/// `T` on the heap (a class that holds itself): the same bytes as `T`. +impl NinoRead for Box { + const MAY_DEFER: bool = T::MAY_DEFER; + const MIN_SIZE: usize = T::MIN_SIZE; + + #[inline] + fn read(r: &mut Reader<'_>) -> Result { + if !T::MAY_DEFER { + return T::read_boxed(r); + } + let mark = r.defer_mark(); + let value = T::read_boxed(r)?; + r.defer_trail(mark, Step::Field(box_inner::)); + Ok(value) + } + + #[inline] + fn read_option(r: &mut Reader<'_>) -> Result> { + if !T::MAY_DEFER { + return T::read_boxed_option(r); + } + let mark = r.defer_mark(); + let value = T::read_boxed_option(r)?; + r.defer_trail(mark, Step::Field(box_inner::)); + Ok(value) + } + + #[inline] + fn read_into(&mut self, r: &mut Reader<'_>) -> Result<()> { + if !T::MAY_DEFER { + return T::read_boxed_into(self, r); + } + let mark = r.defer_mark(); + T::read_boxed_into(self, r)?; + r.defer_trail(mark, Step::Field(box_inner::)); + Ok(()) + } + + #[inline] + fn read_option_into(slot: &mut Option, r: &mut Reader<'_>) -> Result<()> { + if !T::MAY_DEFER { + return T::read_boxed_option_into(slot, r); + } + let mark = r.defer_mark(); + T::read_boxed_option_into(slot, r)?; + r.defer_trail(mark, Step::Field(box_inner::)); + Ok(()) + } +} + +impl NinoWrite for Box { + // Its target's size and 64 for the target's own targets (not `T::PREFETCH_BYTES`: a type that holds itself through a + // `Box` would define the constant through itself). + const PREFETCH_BYTES: usize = core::mem::size_of::().saturating_add(64); + + #[inline(always)] + fn prefetch(&self) { + crate::simd::prefetch(&**self); + } + + #[inline(always)] + fn prefetch_members(&self) { + (**self).prefetch(); + } + + #[inline] + fn write<'a>(&'a self, w: &mut Writer<'a>) -> Result<()> { + (**self).write(w) + } + + #[inline] + fn write_option<'a>(value: Option<&'a Self>, w: &mut Writer<'a>) -> Result<()> { + T::write_option(value.map(|b| &**b), w) + } +} diff --git a/runtimes/rust/src/types.rs b/runtimes/rust/src/types.rs index 2ba209137..5f6da1425 100644 --- a/runtimes/rust/src/types.rs +++ b/runtimes/rust/src/types.rs @@ -28,7 +28,7 @@ macro_rules! fixed { /// Each element converted (a copy, mostly) and checked in one pass with no early exit, a vector at a time /// where the compiler can (`bad`: 0 only for valid values, and for all but a few at the edge of the - /// range). When one fails, the block is read with [`Self::decode`] one by one, which reports the first + /// range). When one fails, the block is decoded one value at a time, which reports the first /// invalid. #[inline] fn read_many(r: &mut Reader<'_>, count: usize) -> Result> { diff --git a/runtimes/rust/tests/generated/nino_types.rs b/runtimes/rust/tests/generated/nino_types.rs index 69b65b545..26d2dedbb 100644 --- a/runtimes/rust/tests/generated/nino_types.rs +++ b/runtimes/rust/tests/generated/nino_types.rs @@ -2279,24 +2279,30 @@ impl Choice { Self::String(value) } -1773443910 => { + let mark = r.defer_mark(); let value: Option> = r.read()?; if value.is_none() { return Err(nino::Error::new(nino::ErrorKind::UnexpectedNull, id)); } + r.defer_trail(mark, nino::Step::Field(|p| p.downcast_mut::()?.case_value())); Self::Point(value) } -749123728 => { + let mark = r.defer_mark(); let value: Option = r.read()?; if value.is_none() { return Err(nino::Error::new(nino::ErrorKind::UnexpectedNull, id)); } + r.defer_trail(mark, nino::Step::Field(|p| p.downcast_mut::()?.case_value())); Self::Animal(value) } -217079013 => { + let mark = r.defer_mark(); let value: Option> = r.read()?; if value.is_none() { return Err(nino::Error::new(nino::ErrorKind::UnexpectedNull, id)); } + r.defer_trail(mark, nino::Step::Field(|p| p.downcast_mut::()?.case_value())); Self::ListInt32(value) } 1279255967 => { @@ -2313,25 +2319,17 @@ impl Choice { impl NinoRead for Choice { const MAY_DEFER: bool = true; const MIN_SIZE: usize = 4; + #[inline] fn read(r: &mut nino::Reader<'_>) -> nino::Result { - let mut v = Self::Empty; - v.read_into(r)?; - Ok(v) - } - fn read_into(&mut self, r: &mut nino::Reader<'_>) -> nino::Result<()> { let id = r.i32()?; if id == 0 { - *self = Self::Empty; - return Ok(()); + return Ok(Self::Empty); } // A case can hold the union again: each level counts toward the depth limit. r.enter_struct()?; - let mark = r.defer_mark(); let value = Self::read_case(r, id); r.exit_struct(); - *self = value?; - r.defer_trail(mark, nino::Step::Field(|p| p.downcast_mut::()?.case_value())); - Ok(()) + value } } impl NinoWrite for Choice { @@ -6654,10 +6652,12 @@ impl UnionTree { fn read_case(r: &mut nino::Reader<'_>, id: i32) -> nino::Result { Ok(match id { 1950069485 => { + let mark = r.defer_mark(); let value: Option> = r.read()?; if value.is_none() { return Err(nino::Error::new(nino::ErrorKind::UnexpectedNull, id)); } + r.defer_trail(mark, nino::Step::Field(|p| p.downcast_mut::()?.case_value())); Self::UnionTreeArray(value) } 337757159 => Self::Int64(r.read()?), @@ -6668,25 +6668,17 @@ impl UnionTree { impl NinoRead for UnionTree { const MAY_DEFER: bool = true; const MIN_SIZE: usize = 4; + #[inline] fn read(r: &mut nino::Reader<'_>) -> nino::Result { - let mut v = Self::Empty; - v.read_into(r)?; - Ok(v) - } - fn read_into(&mut self, r: &mut nino::Reader<'_>) -> nino::Result<()> { let id = r.i32()?; if id == 0 { - *self = Self::Empty; - return Ok(()); + return Ok(Self::Empty); } // A case can hold the union again: each level counts toward the depth limit. r.enter_struct()?; - let mark = r.defer_mark(); let value = Self::read_case(r, id); r.exit_struct(); - *self = value?; - r.defer_trail(mark, nino::Step::Field(|p| p.downcast_mut::()?.case_value())); - Ok(()) + value } } impl NinoWrite for UnionTree { diff --git a/runtimes/rust/tests/generated/shapes.rs b/runtimes/rust/tests/generated/shapes.rs index 12d076696..c68c371f5 100644 --- a/runtimes/rust/tests/generated/shapes.rs +++ b/runtimes/rust/tests/generated/shapes.rs @@ -764,6 +764,70 @@ impl Empty { ); } +/// `Shapes.FixedCollections`: Positional, header Presence. +#[derive(Debug, Default, Clone, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct FixedCollections { + pub ids: Option>, + pub unique_ids: Option>, + pub grid: Option>, + pub pairs: Option>, + pub offsets: Option>, +} + +impl NinoReadBody for FixedCollections { + const TYPE_ID: i32 = Self::NINO_TYPE_ID; + + fn read_body(&mut self, r: &mut nino::Reader<'_>) -> nino::Result<()> { + r.read_into(&mut self.ids)?; + r.read_into(&mut self.unique_ids)?; + r.read_into(&mut self.grid)?; + r.read_into(&mut self.pairs)?; + r.read_into(&mut self.offsets)?; + Ok(()) + } +} + +impl NinoWriteBody for FixedCollections { + const TYPE_ID: i32 = Self::NINO_TYPE_ID; + + fn write_body<'a>(&'a self, w: &mut nino::Writer<'a>) -> nino::Result<()> { + w.write(&self.ids)?; + w.write(&self.unique_ids)?; + w.write(&self.grid)?; + w.write(&self.pairs)?; + w.write(&self.offsets)?; + Ok(()) + } +} + +impl NinoRead for FixedCollections { + const MAY_DEFER: bool = true; + nino::sealed_read!(); +} + +impl NinoWrite for FixedCollections { + const PREFETCH_BYTES: usize = 0usize + .saturating_add(> as NinoWrite>::PREFETCH_BYTES) + .saturating_add(> as NinoWrite>::PREFETCH_BYTES); + + fn prefetch(&self) { + self.unique_ids.prefetch(); + self.offsets.prefetch(); + } + + fn prefetch_members(&self) { + self.unique_ids.prefetch_members(); + self.offsets.prefetch_members(); + } + + nino::sealed_write!(); +} + +impl FixedCollections { + nino::type_consts!(0x9B5DCD24u32 as i32, "Shapes.FixedCollections", "format=Positional; header=Presence; trackReferences=false; raw=false; id=0x9B5DCD24; deferrable=true; members=Ids:System.Collections.Generic.Dictionary:map(raw(16),raw(8){Id:int@0:raw(4),On:bool@4:raw(1),Kind:byte@5:raw(1),Code:short@6:raw(2)});UniqueIds:System.Collections.Generic.HashSet:seq(raw(16));Grid:byte[,]:grid(2,raw(1));Pairs:System.Collections.Generic.Dictionary:map(raw(4),raw(8));Offsets:System.DateTimeOffset[]:seq(datetimeoffset)"); +} + /// `Shapes.ForestHolder`: Positional, header Presence. #[derive(Debug, Default, Clone, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] @@ -1140,17 +1204,21 @@ impl Measure { 546808484 => Self::Int32(r.read()?), -1251563749 => Self::Double(r.read()?), -217079013 => { + let mark = r.defer_mark(); let value: Option> = r.read()?; if value.is_none() { return Err(nino::Error::new(nino::ErrorKind::UnexpectedNull, id)); } + r.defer_trail(mark, nino::Step::Field(|p| p.downcast_mut::()?.case_value())); Self::ListInt32(value) } -1803246716 => { + let mark = r.defer_mark(); let value: Option>> = r.read()?; if value.is_none() { return Err(nino::Error::new(nino::ErrorKind::UnexpectedNull, id)); } + r.defer_trail(mark, nino::Step::Field(|p| p.downcast_mut::()?.case_value())); Self::ListString(value) } _ => return Err(nino::Error::new(nino::ErrorKind::UnknownTypeId, id)), @@ -1160,25 +1228,17 @@ impl Measure { impl NinoRead for Measure { const MAY_DEFER: bool = true; const MIN_SIZE: usize = 4; + #[inline] fn read(r: &mut nino::Reader<'_>) -> nino::Result { - let mut v = Self::Empty; - v.read_into(r)?; - Ok(v) - } - fn read_into(&mut self, r: &mut nino::Reader<'_>) -> nino::Result<()> { let id = r.i32()?; if id == 0 { - *self = Self::Empty; - return Ok(()); + return Ok(Self::Empty); } // A case can hold the union again: each level counts toward the depth limit. r.enter_struct()?; - let mark = r.defer_mark(); let value = Self::read_case(r, id); r.exit_struct(); - *self = value?; - r.defer_trail(mark, nino::Step::Field(|p| p.downcast_mut::()?.case_value())); - Ok(()) + value } } impl NinoWrite for Measure { @@ -2058,10 +2118,12 @@ impl Pick { fn read_case(r: &mut nino::Reader<'_>, id: i32) -> nino::Result { Ok(match id { 334101194 => { + let mark = r.defer_mark(); let value: Option> = r.read()?; if value.is_none() { return Err(nino::Error::new(nino::ErrorKind::UnexpectedNull, id)); } + r.defer_trail(mark, nino::Step::Field(|p| p.downcast_mut::()?.case_value())); Self::EmptyCase(value) } -2134742284 => Self::PickPair(r.read()?), @@ -2073,25 +2135,17 @@ impl Pick { impl NinoRead for Pick { const MAY_DEFER: bool = true; const MIN_SIZE: usize = 4; + #[inline] fn read(r: &mut nino::Reader<'_>) -> nino::Result { - let mut v = Self::Empty; - v.read_into(r)?; - Ok(v) - } - fn read_into(&mut self, r: &mut nino::Reader<'_>) -> nino::Result<()> { let id = r.i32()?; if id == 0 { - *self = Self::Empty; - return Ok(()); + return Ok(Self::Empty); } // A case can hold the union again: each level counts toward the depth limit. r.enter_struct()?; - let mark = r.defer_mark(); let value = Self::read_case(r, id); r.exit_struct(); - *self = value?; - r.defer_trail(mark, nino::Step::Field(|p| p.downcast_mut::()?.case_value())); - Ok(()) + value } } impl NinoWrite for Pick { @@ -3300,6 +3354,7 @@ pub trait NinoVisit { pub fn with_nino_type(name: &str, f: impl NinoVisit) -> Option { Some(match name { "Shapes.Empty" => f.visit::>>(), + "Shapes.FixedCollections" => f.visit::>>(), "Shapes.ForestHolder" => f.visit::>>(), "Shapes.Gappy" => f.visit::(), "Shapes.Generic.BasedInt" => f.visit::>>(), @@ -3349,6 +3404,7 @@ pub trait NinoSerdeVisit { pub fn with_nino_serde_type(name: &str, f: impl NinoSerdeVisit) -> Option { Some(match name { "Shapes.Empty" => f.visit::>>(), + "Shapes.FixedCollections" => f.visit::>>(), "Shapes.ForestHolder" => f.visit::>>(), "Shapes.Gappy" => f.visit::(), "Shapes.Generic.BasedInt" => f.visit::>>(), 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 a9ea7c971..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; @@ -1418,22 +1448,28 @@ function writeMeasure(w: NinoWriter, v: Measure | null): void { } w.enterStruct(); switch (v.case) { - case "Int32": - w.i32(546808484); - w.i32(v.value); + case "Int32": { + const at = w.reserve(8); + w.view.setInt32(at, 546808484, true); + w.view.setInt32(at + 4, v.value, true); break; - case "Double": - w.i32(-1251563749); - w.f64(v.value); + } + case "Double": { + const at = w.reserve(12); + w.view.setInt32(at, -1251563749, true); + w.view.setFloat64(at + 4, v.value, true); break; - case "ListInt32": + } + case "ListInt32": { w.i32(-217079013); - write$32(w, v.value); + write$35(w, v.value); break; - case "ListString": + } + case "ListString": { w.i32(-1803246716); - write$33(w, v.value); + write$36(w, v.value); break; + } default: throw types.unwritable(v); } @@ -1545,12 +1581,14 @@ function writePick(w: NinoWriter, v: Pick | null): void { writeEmpty(w, v); } else if (v instanceof PickPair) { - w.i32(-2134742284); - writePickPair(w, w.reserve(8), v); + const at = w.reserve(12); + w.view.setInt32(at, -2134742284, true); + writePickPair(w, at + 4, v); } else if (typeof v === "number") { - w.i32(31168724); - w.u8(v); + const at = w.reserve(5); + w.view.setInt32(at, 31168724, true); + w.view.setUint8(at + 4, v); } else throw types.unwritable(v as object); w.exitStruct(); @@ -1586,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; } @@ -1594,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(); } @@ -1633,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); @@ -1785,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) => { @@ -2180,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); } }); @@ -2200,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); } }); @@ -2239,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; @@ -2852,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)); @@ -2860,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; @@ -2869,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)); @@ -2877,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; @@ -2886,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)); @@ -2894,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; @@ -2903,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>(); @@ -2913,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; @@ -2924,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)); @@ -2932,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; @@ -2941,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(); @@ -2971,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; @@ -2985,7 +3104,7 @@ function readInto$26(r: NinoReader, cur: Map): Map(r.capacity(length)); @@ -2993,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; @@ -3002,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; @@ -3016,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; @@ -3030,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; @@ -3044,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; @@ -3057,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; @@ -3071,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; @@ -3079,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; @@ -3096,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; @@ -3108,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)); @@ -3116,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; @@ -3125,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; @@ -3137,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)); @@ -3145,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; @@ -3154,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; @@ -3166,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)); @@ -3174,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; @@ -3183,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>(); @@ -3196,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; @@ -3210,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; @@ -3222,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; @@ -3235,7 +3354,7 @@ function write$31(w: NinoWriter, map: ReadonlyMap(r.capacity(length)); @@ -3243,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)); @@ -3251,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; @@ -3265,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; @@ -3277,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)); @@ -3285,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; @@ -3294,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; @@ -3306,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)); @@ -3334,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; @@ -3348,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)); @@ -3356,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; @@ -3370,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>(); @@ -3380,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; @@ -3401,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; @@ -3409,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 d565c9f4e..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; @@ -3346,8 +3529,9 @@ function writeChoice(w: NinoWriter, v: Choice | null): void { } w.enterStruct(); if (typeof v === "number") { - w.i32(546808484); - w.i32(v); + const at = w.reserve(8); + w.view.setInt32(at, 546808484, true); + w.view.setInt32(at + 4, v, true); } else if (typeof v === "string") { w.i32(-65934901); @@ -3364,12 +3548,13 @@ 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") { - w.i32(1279255967); - w.u8(1); - w.i64(v); + const at = w.reserve(13); + w.view.setInt32(at, 1279255967, true); + w.view.setUint8(at + 4, 1); + w.view.setBigInt64(at + 5, v, true); } else throw types.unwritable(v as object); w.exitStruct(); @@ -3460,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) { @@ -3476,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); @@ -3616,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`. */ @@ -3651,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); } } @@ -3712,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); @@ -3825,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; @@ -3849,11 +4034,12 @@ 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") { - w.i32(337757159); - w.i64(v); + const at = w.reserve(12); + w.view.setInt32(at, 337757159, true); + w.view.setBigInt64(at + 4, v, true); } else throw types.unwritable(v as object); w.exitStruct(); @@ -3909,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); @@ -3930,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)); @@ -3938,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); @@ -4303,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(); @@ -4374,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(); @@ -4560,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) => { @@ -4607,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) => { @@ -5160,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; } @@ -5357,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); @@ -5375,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)); @@ -5433,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; @@ -5456,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; @@ -5464,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; @@ -5759,211 +5981,362 @@ 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); + 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]; @@ -5972,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)); @@ -5980,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; @@ -5989,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]; @@ -6003,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>(); @@ -6013,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; @@ -6024,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; @@ -6037,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)); @@ -6045,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; @@ -6054,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)); @@ -6062,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; @@ -6071,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)); @@ -6079,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; @@ -6088,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; @@ -6102,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; @@ -6116,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; @@ -6130,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)); @@ -6138,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; @@ -6147,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)); @@ -6155,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; @@ -6164,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)); @@ -6172,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; @@ -6181,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>(); @@ -6191,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; @@ -6202,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)); @@ -6210,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; @@ -6219,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; @@ -6233,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; @@ -6247,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; @@ -6261,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; @@ -6276,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; @@ -6290,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)); @@ -6298,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; @@ -6307,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)); @@ -6315,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; @@ -6324,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; @@ -6338,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; @@ -6352,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)); @@ -6360,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; @@ -6369,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(); @@ -6382,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; @@ -6396,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; @@ -6410,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; @@ -6423,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)); @@ -6431,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; @@ -6440,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; @@ -6454,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)); @@ -6491,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; @@ -6500,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; @@ -6514,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)); @@ -6623,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; @@ -6632,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)); @@ -6640,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; @@ -6649,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>(); @@ -6234,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; @@ -6245,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)); @@ -6253,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; @@ -6262,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; @@ -6276,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; @@ -6290,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; @@ -6304,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; @@ -6319,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; @@ -6333,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)); @@ -6341,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; @@ -6350,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)); @@ -6358,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; @@ -6367,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; @@ -6381,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; @@ -6395,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)); @@ -6403,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; @@ -6412,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(); @@ -6425,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; @@ -6439,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; @@ -6453,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; @@ -6466,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)); @@ -6474,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; @@ -6483,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; @@ -6497,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)); @@ -6534,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; @@ -6543,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; @@ -6557,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)); @@ -6666,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; @@ -6675,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)); @@ -6683,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; @@ -6692,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