diff --git a/.claude/skills/optimize-runtimes/references/blocks.md b/.claude/skills/optimize-runtimes/references/blocks.md index 58fe2a7b3..53b18e531 100644 --- a/.claude/skills/optimize-runtimes/references/blocks.md +++ b/.claude/skills/optimize-runtimes/references/blocks.md @@ -57,6 +57,10 @@ value check in a runtime or a template. 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 diff --git a/.claude/skills/optimize-runtimes/references/dispatch.md b/.claude/skills/optimize-runtimes/references/dispatch.md index 8a434579c..c33dcf415 100644 --- a/.claude/skills/optimize-runtimes/references/dispatch.md +++ b/.claude/skills/optimize-runtimes/references/dispatch.md @@ -43,7 +43,12 @@ call, a helper that takes a function, or a `read_into` / `deserializeInto` path. [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. + 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 diff --git a/.claude/skills/platforms/references/emulation.md b/.claude/skills/platforms/references/emulation.md index 087af48cb..eeeeaa5e8 100644 --- a/.claude/skills/platforms/references/emulation.md +++ b/.claude/skills/platforms/references/emulation.md @@ -50,7 +50,9 @@ 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 diff --git a/runtimes/csharp/src/Nino.Codegen/Targets/Go/GoTarget.cs b/runtimes/csharp/src/Nino.Codegen/Targets/Go/GoTarget.cs index ce4858946..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)); @@ -190,6 +194,7 @@ protected override void Reset() _namedCollections.Clear(); _helperByKey.Clear(); _helpers.Clear(); + _keyChecks.Clear(); _tuples.Clear(); _generics.Clear(); _closedByKey.Clear(); @@ -404,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/Templates/go/types.sbn b/runtimes/csharp/src/Nino.Codegen/Templates/go/types.sbn index c390b0c5a..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 @@ -291,34 +295,34 @@ func helper_body(h) $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.unique_keys ? "\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", "fixed" # Elements read twice fail, checked once over the elements (primitives read as one block). if $s.mode == "unique" && $s.element.block - ret $o + "\treturn nino.CheckUniqueValues(r, nino.ReadPrimitives[" + gotype($s.element) + "](r))\n}\n" + 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 nino.CheckUniqueValues(r, nino.ReadBlock[" + gotype($s.element) + "](r))\n}\n" + ret $o + "\treturn " + check_unique_values($s.element, "nino.ReadBlock[" + gotype($s.element) + "](r)") + "\n}\n" end if $s.element.kind == "prim" && $s.element.primitive == "Bool" - ret $o + "\treturn nino.CheckUniqueValues(r, nino.ReadBools(r))\n}\n" + 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 ? "nino.CheckUniqueValues(r, v)" : "v") + "\n\t}\n" + $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 ? "nino.CheckUniqueValues(r, v)" : "v") + "\n}\n" + 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" + 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 @@ -1023,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/go/AGENTS.md b/runtimes/go/AGENTS.md index 8d64c0bfb..53b2f9f0d 100644 --- a/runtimes/go/AGENTS.md +++ b/runtimes/go/AGENTS.md @@ -31,7 +31,7 @@ endian_little.go littleEndian = true on little-endian architectures 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, 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); key metadata cached by Go type + 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 @@ -153,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 b56c94481..43e59d13d 100644 --- a/runtimes/go/bench/model/nino_types.go +++ b/runtimes/go/bench/model/nino_types.go @@ -27082,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) { @@ -27116,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] { @@ -27134,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]) { @@ -27551,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) { @@ -28415,7 +28415,7 @@ 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 { @@ -29890,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 43151d5dc..9874c9e81 100644 --- a/runtimes/go/collections.go +++ b/runtimes/go/collections.go @@ -378,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 } @@ -415,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/internal/generated/nino_types.go b/runtimes/go/internal/generated/nino_types.go index 558eb1c84..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] { @@ -12538,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]) { @@ -12895,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) { @@ -12981,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] { @@ -12999,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] { @@ -13017,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] { @@ -13035,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] { @@ -13053,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) { @@ -13518,7 +13518,7 @@ func readV55(r *nino.Reader) []nino.Entry[int32, nino.NinoNullable[nino.Decimal] v = append(v, e) b = b[36:] } - return nino.CheckUniqueKeys(r, v) + return nino.CheckUniqueKeysWith(r, v, &keyCheck2) } func readV56(r *nino.Reader) []NinoNullableFieldsType { @@ -13655,7 +13655,7 @@ func writeV56(w *nino.Writer, v []NinoNullableFieldsType) { } 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]] { @@ -13717,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]) { @@ -13886,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) { @@ -14309,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) { @@ -14520,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) { @@ -14810,6 +14810,14 @@ func readV92(r *nino.Reader) nino.Entry[*string, *int32] { return v } +var keyCheck0 = nino.PrepareKeyCheck[string]() + +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 { Item1 T1 diff --git a/runtimes/go/internal/generated/shapes/nino_types.go b/runtimes/go/internal/generated/shapes/nino_types.go index ac733cf0d..cbe24575a 100644 --- a/runtimes/go/internal/generated/shapes/nino_types.go +++ b/runtimes/go/internal/generated/shapes/nino_types.go @@ -743,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]) { @@ -4963,7 +4963,7 @@ func writeV4(w *nino.Writer, v []nino.NullableSlot[TupleCell]) { } 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]) { @@ -4997,7 +4997,7 @@ func readV7(r *nino.Reader) []nino.Entry[int32, *int64] { } 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]) { @@ -5094,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]) { @@ -5188,11 +5188,11 @@ func readV14(r *nino.Reader) []nino.Entry[nino.Guid, Marked] { v = append(v, e) b = b[24:] } - return nino.CheckUniqueKeys(r, v) + return nino.CheckUniqueKeysWith(r, v, &keyCheck3) } func readV15(r *nino.Reader) []nino.Guid { - return nino.CheckUniqueValues(r, nino.ReadBlock[nino.Guid](r)) + return keyCheck3.Values(r, nino.ReadBlock[nino.Guid](r)) } func readV16(r *nino.Reader) *NinoGrid[uint8] { @@ -5522,7 +5522,7 @@ func readV27(r *nino.Reader) []nino.Entry[int32, nino.NinoNullable[float64]] { v = append(v, e) b = b[20:] } - return nino.CheckUniqueKeys(r, v) + return nino.CheckUniqueKeysWith(r, v, &keyCheck2) } func readV28(r *nino.Reader) NinoTuple2[uint8, nino.NinoNullable[nino.Guid]] { @@ -5981,7 +5981,7 @@ func readV40(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 writeV39(w *nino.Writer, v []*Box[int32]) { @@ -6217,7 +6217,7 @@ func writeV48(w *nino.Writer, v NinoTuple2[int32, *int32]) { } func readV49(r *nino.Reader) []nino.NullableSlot[int64] { - return nino.CheckUniqueValues(r, nino.ReadNullableSlots[int64](r)) + return keyCheck4.Values(r, nino.ReadNullableSlots[int64](r)) } func decodeV45(r *nino.Reader, b []byte) nino.NinoNullable[nino.Guid] { @@ -6237,6 +6237,16 @@ func encodeV45(b []byte, v nino.NinoNullable[nino.Guid]) { } } +var keyCheck0 = nino.PrepareKeyCheck[string]() + +var keyCheck1 = nino.PrepareKeyCheck[nino.NullableSlot[int32]]() + +var keyCheck2 = nino.PrepareKeyCheck[int32]() + +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 { Item1 T1 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 a6a876337..14c18aecf 100644 --- a/runtimes/go/raw.go +++ b/runtimes/go/raw.go @@ -240,7 +240,9 @@ func ReadPrimitiveEntries[K, V Primitive](r *Reader) []Entry[K, V] { b = b[wire:] } } - if repeated[K](unsafe.Pointer(unsafe.SliceData(v)), n, size, &r.keys) { + // 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 } diff --git a/runtimes/go/unique.go b/runtimes/go/unique.go index 235f02ab6..ce7e8c356 100644 --- a/runtimes/go/unique.go +++ b/runtimes/go/unique.go @@ -40,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]() @@ -79,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: @@ -91,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 repeatedOtherKeys[K](p, n, stride, scratch) + 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 @@ -470,8 +495,14 @@ func bytewiseKey(t reflect.Type) bool { // repeatedOtherKeys keeps bytewise key handling off the scalar and string paths. // //go:noinline -func repeatedOtherKeys[K comparable](p unsafe.Pointer, n, stride int, scratch *[]uint64) bool { - if size := bytewiseKeySize[K](); size != 0 && n <= 1<<(bits.UintSize-6) && int64(n) < 1<<31 { +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 } diff --git a/runtimes/go/unique_test.go b/runtimes/go/unique_test.go index 5b638c5e2..b2c5f7a9d 100644 --- a/runtimes/go/unique_test.go +++ b/runtimes/go/unique_test.go @@ -136,7 +136,7 @@ func TestUniqueBytewiseKeys(t *testing.T) { Id Guid Hi [2]uint64 } - if bytewiseKeySize[Guid]() != 16 || bytewiseKeySize[nested]() != 32 { + 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 || @@ -155,6 +155,39 @@ func TestUniqueBytewiseKeys(t *testing.T) { } } +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) { @@ -312,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)) @@ -329,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) @@ -346,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])