From d0caf5dc26e16f70a332286b7fdf8c7be27e98a0 Mon Sep 17 00:00:00 2001 From: Andreas Steinbart Date: Mon, 21 Sep 2026 04:33:24 +0000 Subject: [PATCH 1/3] feat(seq): place and reserve a wrapper-array element here (generator#587) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `Seq` held only the matrix-row half of the wrapper-array rules: `reserveRow` and its six primitive overloads. The other two shapes -- a `string`/`blob` element and a `struct`/`union`/nested-row element -- were emitted, inline, into every generated message class: if (id >= 5) throw Sofab.invalid("... above schema capacity 5"); while (m.warnings.size() <= id) m.warnings.add(""); m.warnings.set(id, _s); if (id >= MAX_DYN_ARRAY_COUNT) throw new java.io.UncheckedIOException( new SofabException(SofabError.LIMIT_EXCEEDED, "... above configured limit")); while (m.dyn_structs.size() <= id) m.dyn_structs.add(new DynStructsElem()); That is one copy of MESSAGE_SPEC §5.1 per wrapper array per schema, and a second implementation of the §6.2.1 cap beside the one `reserveRow` already has. Its schema dependence is a bound, an element type and an element default -- an argument, a type parameter and an argument -- which is ARCHITECTURE §8's condition for a helper belonging in the corelib. Two signatures, beside the row ones and taking the same `Bound`: placeElem(List out, int id, T def, T value, Bound bound) bound the index, fill the gaps omitted interior elements left with the shared default, `set` at the id so a repeat replaces (§7.4). reserveElem(List out, int id, Supplier make, Bound bound) bound the index, grow to id + 1 with one fresh element per slot. A slot already present is LEFT ALONE: a framed element's fields arrive one at a time and a re-opened id merges into what the earlier ones built (§7.4). They are two methods rather than one because the element default cannot be shared for the framed case: a struct, union or nested row is mutable and an arriving element decodes into the object the reservation placed, so one shared instance would alias every element of the array onto it. `make` is a generated method reference; javac lowers a non-capturing one to a constant, so it allocates nothing per call. `checkIndex` becomes public for the one site with no reservation to ride: a generated `fixlenBegin` arm bounds a string or blob element's index at the LENGTH WORD, so a message ending right there is refused rather than reported INCOMPLETE (§5.2). Java erases generics, so one body serves every element type -- no monomorphisation and no code growth however many wrapper arrays a schema declares. Measured with `tests/bench/run.sh --rows java` against this working tree: encode 17006, decode 31511 Ir/op, bit-identical to the committed row. Normative details preserved exactly as the emitted code had them: the index check runs BEFORE any growth, so a rejected id leaves the container unextended and a lower id delivered afterwards still lands (CORELIB_PLAN §7.2 item 8); a schema `count` is a capacity, so `id >= count` and the container starts empty; where the schema leaves the array open the receiver cap governs instead and the verdict is LIMIT_EXCEEDED, never both (§6.2.1); the cap is passed in, never held or defaulted. What stays generated is stated in the class note: the schema `count` verdict, which `Bound.SCHEMA_BOUNDED` deliberately carries no number for; an element's own `maxlen`, which has no reservation at the length word to ride and is `PayloadAcc`'s; and the routing of a framed element, which has a different shape per schema. Purely additive: no existing signature changes, so generated code from sofabgen before generator#587 still compiles and still runs. Tests exercise the helpers directly, with their own containers, rather than only through a decode -- placement at an id, an interior gap, the length that a lone high id sets, a repeat replacing (leaf) against a repeat merging (framed), the shared gap value costing no allocation, the id at the bound, the id past it with the container checked for partial extension and a lower id landing afterwards, the factory never called for a refused index, the cap breach as LIMIT_EXCEEDED rather than INVALID, an omitted bound as ARGUMENT, and the length word's three comparisons in the order generated code makes them, including an element payload over its maxlen. --- README.md | 7 +- src/main/java/org/sofabuffers/sofab/Seq.java | 179 ++++++++++++++++-- .../sofabuffers/sofab/ForgottenCapTest.java | 15 ++ .../sofabuffers/sofab/ReceiverCapTest.java | 122 ++++++++++++ .../java/org/sofabuffers/sofab/SeqTest.java | 163 ++++++++++++++++ 5 files changed, 466 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 3ffe796..cbc556f 100644 --- a/README.md +++ b/README.md @@ -264,7 +264,10 @@ is an argument, an element type is a type parameter. | symbol | what it is | |---|---| -| `Seq.reserveRow` / `reserveRowBytes` … `reserveRowDoubles` | place a matrix row at the index its id names, filling a gap with the empty row rather than shifting every later row down (MESSAGE_SPEC §5.1 / §7.4); the receiver cap on that index arrives as a `Bound` and is compared here (§6.2.1) | +| `Seq.placeElem` | place a wrapper array's decoded `string` or `blob` at the index its id names, filling the gaps omitted interior elements left with the shared element default; a repeated id replaces (MESSAGE_SPEC §5.1 / §7.4) | +| `Seq.reserveElem` | reserve the slot a wrapper array's `struct`, `union` or nested-array element is routed into, one fresh element per slot from a factory; a re-opened id merges into the element its earlier fields built (§7.4) | +| `Seq.reserveRow` / `reserveRowBytes` … `reserveRowDoubles` | place a matrix row at the index its id names, filling a gap with the empty row rather than shifting every later row down (MESSAGE_SPEC §5.1 / §7.4) | +| `Seq.checkIndex` | the element-index bound each of the three reservations above takes, on its own — for the **length word** of a `string`/`blob` element, which has no reservation to ride and must be judged before the payload (§5.2). Where the schema bounds the array this is `Bound.SCHEMA_BOUNDED` and the caller's own `INVALID` governs; where it does not, the `Bound` carries the receiver cap and the comparison happens here (§6.2.1) | | `Seq.ensureCap` (one per primitive width) | the array-growth policy: double, stop at the announced count, and never allocate from a count the wire claimed but has not delivered | | `Seq.ARRAY_INIT_CAP`, `Seq.EMPTY_BYTES` … `EMPTY_DOUBLES` | the bounded first reservation, and the shared zero-length arrays a field initializer points at | | `Seq.reset` / `Seq.orEmpty` / `Seq.boolsToLongs` | re-arm a reused destination in place; absorb a null field on the encode side; the one boxed-to-primitive conversion `bool` still needs | @@ -293,7 +296,7 @@ the limit guards: |---|---|---| | `max_dyn_string_len` | `PayloadAcc.string(…, bound)` | the announced `total`, before a byte is buffered | | `max_dyn_blob_len` | `PayloadAcc.blob(…, bound)` | the same | -| `max_dyn_array_count` | `Seq.reserveRow` / `reserveRow*(…, bound)` | the row **index**, before the row and the list grow | +| `max_dyn_array_count` | `Seq.placeElem` / `reserveElem` / `reserveRow` / `reserveRow*(…, bound)`, and `Seq.checkIndex(…, bound)` at a `string`/`blob` element's length word | the element **index**, before anything is created and before the list grows | A breach is `SofabError.LIMIT_EXCEEDED` — a policy rejection of well-formed bytes, never clamped into a shortened value and never the `INVALID` outcome. It is diff --git a/src/main/java/org/sofabuffers/sofab/Seq.java b/src/main/java/org/sofabuffers/sofab/Seq.java index 2ee1901..453afdf 100644 --- a/src/main/java/org/sofabuffers/sofab/Seq.java +++ b/src/main/java/org/sofabuffers/sofab/Seq.java @@ -10,6 +10,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.function.Supplier; /** * Element placement and array growth for generated decode destinations — the @@ -29,6 +30,16 @@ * a list, because a wrapper array of strings, blobs or sub-messages has no * primitive form. * + *

Three reservations, one shape. Every wrapper array a schema can + * declare reaches this class through one of three calls, which differ only in what + * a slot holds: {@link #placeElem} puts a decoded {@code string} or {@code blob} at + * the index its id names; {@link #reserveElem} makes the slot a {@code struct}, + * {@code union} or nested-array element will be routed into; {@link #reserveRow} + * and its six primitive overloads reserve a matrix row. The schema dependence of + * all three is exactly a bound, an element type and an element default — an + * argument, a type parameter and an argument — which is the whole of why they fit + * here at all. + * *

Two rules run through all of it. Ids are positions (MESSAGE_SPEC §5.1): * an array element's id is its index, an interior element equal to the * element default may be omitted, and the highest id present is what gives the @@ -38,16 +49,25 @@ * follow, bounded by nothing until a schema {@code count} or a receiver limit * bounds it, so no method here allocates from a count alone. * - *

Receiver caps (CORELIB_PLAN §6.2.1). The row reservations — - * {@link #reserveRow} and the six primitive {@code reserveRow*} overloads — take - * a {@link Bound} on the outer array's element index and compare it here, before - * the row is created and before the outer list is grown to hold it. A wrapper - * array announces no count, so the index is what a cap can bind: its length is - * highest present id + 1 (MESSAGE_SPEC §5.1), and two elements at id 0 and id - * 65535 are a 65536-slot list. §6.2.1 permits exactly this placement — "a corelib - * MAY take a limit as an argument and perform the check itself, and a port that - * does is conformant" — and the rule then has one implementation: a caller - * that passes the cap does not also guard in front of the call. + *

Receiver caps (CORELIB_PLAN §6.2.1). Every reservation here — + * {@link #placeElem}, {@link #reserveElem}, {@link #reserveRow} and the six + * primitive {@code reserveRow*} overloads — takes a {@link Bound} on the array's + * element index and compares it here, before anything is created and before + * the list is grown to hold it. A wrapper array announces no count, so the index is + * what a cap can bind: its length is highest present id + 1 (MESSAGE_SPEC §5.1), + * and two elements at id 0 and id 65535 are a 65536-slot list. §6.2.1 permits + * exactly this placement — "a corelib MAY take a limit as an argument and perform + * the check itself, and a port that does is conformant" — and the rule then has + * one implementation: a caller that passes the cap does not also guard in + * front of the call. + * + *

{@link #checkIndex} is that comparison on its own, published for the one site + * that has no reservation to ride: a generated {@code fixlenBegin} arm bounds a + * {@code string} or {@code blob} element's index at the length word, so that + * a message ending right there is still refused rather than reported + * {@code INCOMPLETE} (MESSAGE_SPEC §5.2). The placement that follows re-runs it, + * which costs one comparison against a folded constant and spares the two sites + * from having to agree by inspection. * *

Nothing here holds a limit. The number is the caller's, used for that * one comparison and not retained; there is no default, no fallback and no @@ -63,9 +83,16 @@ * than an uncapped index. §6.2.1: "no unset state and no unlimited mode", and a * codec "MUST NOT read an omitted argument as unlimited". * - *

What the caps here do not cover. The cap on a row's own element - * count, and on the count of a top-level native array, is not one of these - * arguments: {@code n} below is a length the caller has already bounded, and the + *

What the caps here do not cover. A {@code string} or {@code blob} + * element's own {@code maxlen} is not one of these arguments: the payload arrives + * through the visitor's own callback, and its length must be decided at the + * length word so that a message truncated right after that word is refused + * rather than {@code INCOMPLETE} (MESSAGE_SPEC §5.2). There is no reservation here + * for it to ride — {@link PayloadAcc#checkStringLength} and + * {@link PayloadAcc#string} own that half. + * + *

The cap on a row's own element count, and on the count of a top-level + * native array, is not one of these arguments: {@code n} below is a length the caller has already bounded, and the * two numbers can be governed by different rules — an inner array the schema * bounds inside an outer one it does not. A native array count also has no call * into this class at all; generated code writes {@code new int[count]} straight @@ -110,6 +137,115 @@ private Seq() { /** The shared empty {@code double[]}; see {@link #EMPTY_BYTES}. */ public static final double[] EMPTY_DOUBLES = {}; + /** + * Place a leaf element — a wrapper array's {@code string} or + * {@code blob} — at the index its wire id names, growing the list and filling + * the gaps that omitted interior elements left (MESSAGE_SPEC §5.1, §2). + * + *

Three rules of §5.1 sit in this one loop, and not one of them is visible + * in the bytes: two implementations can disagree about every one and still emit + * an identical message, which is why they are written here once instead of + * being re-emitted per schema (CORELIB_PLAN §7.2 item 8 asks for them + * separately for the same reason). + * + *

    + *
  • A missing id fills a gap with {@code def} rather than shifting + * every later element down by one — an interior element equal to the + * element default is omitted by a conformant encoder (§2). + *
  • The array's length is highest present id + 1, so growing to + * {@code id + 1} per element is exactly right and no trailing fill is + * ever needed: the last element is never elided. + *
  • A repeated id replaces rather than appends (§7.4), which + * {@code set} does by construction and an {@code add} could not. + *
+ * + *

The index is bounded before the list grows (§7.2 item 8), so a + * refused id leaves the list exactly as it was and a lower id delivered + * afterwards still lands at its own index. Where the schema declares a + * {@code count} the caller has already rejected a breach as {@code INVALID} + * (MESSAGE_SPEC §7.1) and passes {@link Bound#SCHEMA_BOUNDED}; where it + * declares none, {@code bound} carries the receiver cap, the comparison happens + * here and a breach is {@code LIMIT_EXCEEDED}. Never both (§6.2.1). + * + *

{@code def} is shared, not copied. The gap value of an array of + * strings or blobs is {@code ""} or {@link #EMPTY_BYTES} — immutable, or + * zero-length and so with no state to share — so a gap costs no allocation. An + * element whose default is a mutable object belongs in + * {@link #reserveElem} instead, which makes one per slot. + * + * @param out the destination list, which this grows + * @param id the element's wire id, which is its index + * @param def the element default, filling any gap below {@code id} + * @param value the decoded element + * @param bound {@link Bound#receiver(long)} carrying the caller's + * {@code max_dyn_array_count} (§6.2.1), or + * {@link Bound#SCHEMA_BOUNDED} where the schema bounds the array + * @param element type + * @throws java.io.UncheckedIOException wrapping a {@code LIMIT_EXCEEDED} + * {@link SofabException} when {@code id} + * is at or past the receiver cap, or an + * {@code ARGUMENT} one when {@code bound} + * is null + */ + public static void placeElem(List out, int id, T def, T value, Bound bound) { + checkIndex(id, bound); + while (out.size() <= id) { + out.add(def); + } + out.set(id, value); + } + + /** + * Reserve a framed element — the slot a wrapper array's {@code struct}, + * {@code union} or nested-array element is routed into: bound the index, then + * grow the list to {@code id + 1}, giving each new slot its own element from + * {@code make} (MESSAGE_SPEC §5.1, §2). + * + *

The same three rules as {@link #placeElem} and the same ordering — the + * index is decided before the list grows (§7.2 item 8) — with one deliberate + * difference: a slot already present is left alone. A framed element's + * fields arrive one at a time and each is routed into the object this call + * reserved, so a re-opened element id must merge into what its earlier + * fields built rather than start the element again (§7.4); replacing the slot + * would discard them. That is also why nothing is returned: generated code parks + * {@code id} in its own element-index register and reaches the element through + * {@code out.get(...)} on the field arms that follow. + * + *

A factory, not a shared default. A struct, union or nested row is + * mutable and reachable by the caller, and an arriving element decodes + * into the object placed here, so one shared instance would alias every + * element of the array onto it — the single reason this is a second method + * rather than {@link #placeElem} with one more argument. {@code make} is a + * generated method reference ({@code SomeElem::new}): it names a generated type, + * which is the schema dependence a type parameter is allowed to carry, and javac + * lowers a non-capturing one to a constant, so the argument allocates nothing + * per call. + * + *

What this does not own is the routing — binding the element + * index, switching into the element's scope, emptying a re-opened nested row. + * That has a different shape per schema and stays generated. This owns growth + * and the bound, and stops at the slot. + * + * @param out the destination list, which this grows + * @param id the element's wire id, which is its index + * @param make the element factory, called once per slot this creates + * @param bound {@link Bound#receiver(long)} carrying the caller's + * {@code max_dyn_array_count} (§6.2.1), or + * {@link Bound#SCHEMA_BOUNDED} where the schema bounds the array + * @param element type + * @throws java.io.UncheckedIOException wrapping a {@code LIMIT_EXCEEDED} + * {@link SofabException} when {@code id} + * is at or past the receiver cap, or an + * {@code ARGUMENT} one when {@code bound} + * is null + */ + public static void reserveElem(List out, int id, Supplier make, Bound bound) { + checkIndex(id, bound); + while (out.size() <= id) { + out.add(make.get()); + } + } + /** * Reserve the row at index {@code id} of a matrix — an array whose elements are * themselves arrays — as an empty row, growing the outer list with empty @@ -367,10 +503,17 @@ public static double[] reserveRowDoubles(List rows, int id, int n, Bou } /** - * The element-index rule of §6.2.1, written once for all seven reservations: - * a bound must have been stated, and where it is a receiver cap the index is - * refused before the row is created and before the outer list is grown to hold - * it. + * The element-index rule of §6.2.1, written once for all nine reservations — + * and published for the one site that has none to ride. A bound must have been + * stated, and where it is a receiver cap the index is refused before anything is + * created and before the list is grown to hold it. + * + *

The site with no reservation is the length word of a {@code string} + * or {@code blob} element: generated code bounds the element's index there, so + * that a message ending right after that word is refused rather than reported + * {@code INCOMPLETE} (MESSAGE_SPEC §5.2), and the placement that follows — + * {@link #placeElem} — runs the same comparison again against the same folded + * constant. * *

The index is compared with {@code >=} rather than {@code >} because a * wrapper array's length is highest present id + 1 (MESSAGE_SPEC §5.1): an @@ -383,7 +526,7 @@ public static double[] reserveRowDoubles(List rows, int id, int n, Bou * would promise a limit to raise that was never configured (§6.3), and not * silence, which would decode the index uncapped. */ - private static void checkIndex(int id, Bound bound) { + public static void checkIndex(int id, Bound bound) { if (Bound.required(bound, "max_dyn_array_count").exceededByIndex(id)) { throw overIndexCap(id, bound); } diff --git a/src/test/java/org/sofabuffers/sofab/ForgottenCapTest.java b/src/test/java/org/sofabuffers/sofab/ForgottenCapTest.java index dd54286..227a7fb 100644 --- a/src/test/java/org/sofabuffers/sofab/ForgottenCapTest.java +++ b/src/test/java/org/sofabuffers/sofab/ForgottenCapTest.java @@ -55,6 +55,7 @@ class ForgottenCapTest { /** The calls that compare a receiver cap; each must take the bound as a type. */ private static final List CAP_TAKING_METHODS = List.of( "PayloadAcc.string", "PayloadAcc.blob", + "Seq.placeElem", "Seq.reserveElem", "Seq.checkIndex", "Seq.reserveRow", "Seq.reserveRowBytes", "Seq.reserveRowShorts", "Seq.reserveRowInts", "Seq.reserveRowLongs", "Seq.reserveRowFloats", "Seq.reserveRowDoubles"); @@ -202,6 +203,20 @@ void anOmittedBoundIsReportedAndNotObeyed() throws Exception { assertEquals(SofabError.ARGUMENT, categoryOf( () -> call(Seq.class, "reserveRow", null, wrapper, 3, null))); assertEquals(0, wrapper.size()); + + List leaves = new ArrayList<>(); + assertEquals(SofabError.ARGUMENT, categoryOf( + () -> call(Seq.class, "placeElem", null, leaves, 3, "", "v", null))); + assertEquals(0, leaves.size(), "refused before anything was placed or grown"); + + List framed = new ArrayList<>(); + assertEquals(SofabError.ARGUMENT, categoryOf( + () -> call(Seq.class, "reserveElem", null, framed, 3, + (java.util.function.Supplier) Object::new, null))); + assertEquals(0, framed.size()); + + assertEquals(SofabError.ARGUMENT, categoryOf( + () -> call(Seq.class, "checkIndex", null, 3, null))); } /** diff --git a/src/test/java/org/sofabuffers/sofab/ReceiverCapTest.java b/src/test/java/org/sofabuffers/sofab/ReceiverCapTest.java index 9174b52..e12aba7 100644 --- a/src/test/java/org/sofabuffers/sofab/ReceiverCapTest.java +++ b/src/test/java/org/sofabuffers/sofab/ReceiverCapTest.java @@ -327,6 +327,128 @@ void aSchemaBoundedRowIndexIsTheCallersToCheck() { assertEquals(41, rows.size()); } + /** + * The same bound, on the two element reservations beside the row ones: a leaf + * element's placement and a framed element's slot. The cap binds the + * index for the same reason — a wrapper array carries no count, so its + * length is whatever the highest id says it is. + */ + @Test + void anElementIndexAtItsCapIsRefused() { + List leaves = new ArrayList<>(); + assertEquals(SofabError.LIMIT_EXCEEDED, categoryOf(assertThrows(UncheckedIOException.class, + () -> Seq.placeElem(leaves, 4, "", "over", Bound.receiver(4))))); + assertEquals(0, leaves.size(), "refused, so the list never grew"); + Seq.placeElem(leaves, 3, "", "last", Bound.receiver(4)); + assertEquals(4, leaves.size(), "index max - 1 is the last one that fits"); + + List framed = new ArrayList<>(); + assertEquals(SofabError.LIMIT_EXCEEDED, categoryOf(assertThrows(UncheckedIOException.class, + () -> Seq.reserveElem(framed, 4, Object::new, Bound.receiver(4))))); + assertEquals(0, framed.size()); + Seq.reserveElem(framed, 3, Object::new, Bound.receiver(4)); + assertEquals(4, framed.size()); + } + + /** + * The comparison runs before the element is made. The factory here + * throws, so a check made after the growth would surface that instead of the + * refusal — and would have made an object for an index the cap forbids. + */ + @Test + void theIndexIsRefusedBeforeTheElementIsMade() { + List out = new ArrayList<>(); + assertEquals(SofabError.LIMIT_EXCEEDED, categoryOf(assertThrows(UncheckedIOException.class, + () -> Seq.reserveElem(out, 9, () -> { + throw new AssertionError("the element was made for a refused index"); + }, Bound.receiver(4))))); + assertEquals(0, out.size()); + } + + /** + * CORELIB_PLAN §7.2 item 8: a refused id leaves the container not partially + * extended, so a lower id delivered afterwards still lands at its own index. + * A growth that ran before the check would have left four defaults behind and + * put this element at index 5. + */ + @Test + void aRefusedIndexLeavesTheContainerUnextended() { + List out = new ArrayList<>(); + Seq.placeElem(out, 1, "", "b", Bound.receiver(4)); + assertThrows(UncheckedIOException.class, + () -> Seq.placeElem(out, 5, "", "over", Bound.receiver(4))); + + assertEquals(2, out.size(), "the refused element neither grew nor shifted the list"); + Seq.placeElem(out, 0, "", "a", Bound.receiver(4)); + assertEquals(List.of("a", "b"), out, "a lower id delivered afterwards still lands"); + } + + /** As for a row, the schema-bounded statement compares nothing here. */ + @Test + void aSchemaBoundedElementIndexIsTheCallersToCheck() { + List out = new ArrayList<>(); + Seq.placeElem(out, 40, "", "far", Bound.SCHEMA_BOUNDED); + assertEquals(41, out.size()); + + List framed = new ArrayList<>(); + Seq.reserveElem(framed, 40, Object::new, Bound.SCHEMA_BOUNDED); + assertEquals(41, framed.size()); + } + + /** + * The same comparison, on its own, for the one site that has no reservation to + * ride: a {@code string} or {@code blob} element's index is bounded at the + * length word, so a message ending right after that word is refused + * rather than reported {@code INCOMPLETE} (MESSAGE_SPEC §5.2). + */ + @Test + void theLengthWordLatchTakesTheSameIndexComparison() { + assertEquals(SofabError.LIMIT_EXCEEDED, categoryOf(assertThrows(UncheckedIOException.class, + () -> Seq.checkIndex(4, Bound.receiver(4))))); + Seq.checkIndex(3, Bound.receiver(4)); + Seq.checkIndex(40, Bound.SCHEMA_BOUNDED); + assertEquals(SofabError.ARGUMENT, categoryOf(assertThrows(UncheckedIOException.class, + () -> Seq.checkIndex(0, null)))); + } + + /** + * The three comparisons a wrapper-array {@code string} element passes through, + * in the order generated code makes them: the element index and the + * element length both at the length word, before a byte of payload is + * buffered, and the placement after the value exists. + * + *

The element's {@code maxlen} half is {@link PayloadAcc}'s, not + * {@link Seq}'s — there is no reservation at the length word for it to ride — + * and this pins that the two answer separately and leave the array untouched + * when either refuses. + */ + @Test + void anElementIsBoundedAtTheLengthWordBeforeItsPayloadIsTaken() { + Bound index = Bound.receiver(4); + Bound elemMax = Bound.receiver(CAP_VALUE); + List out = new ArrayList<>(); + byte[] p = payload(CAP_VALUE); + + Seq.checkIndex(1, index); + PayloadAcc.checkStringLength(p.length, elemMax); + Seq.placeElem(out, 1, "", new PayloadAcc().string(p.length, 0, p, 0, p.length, elemMax), + index); + assertEquals(List.of("", "aaaaaaaa"), out); + + // An element payload over its maxlen: refused at the length word, with no + // payload taken and nothing placed. + byte[] over = payload(CAP_VALUE + 1); + assertEquals(SofabError.LIMIT_EXCEEDED, categoryOf(assertThrows(UncheckedIOException.class, + () -> PayloadAcc.checkStringLength(over.length, elemMax)))); + assertEquals(SofabError.LIMIT_EXCEEDED, categoryOf(assertThrows(UncheckedIOException.class, + () -> new PayloadAcc().string(over.length, 0, over, 0, over.length, elemMax)))); + + // And an over-cap index is refused at the same word, on its own bound. + assertEquals(SofabError.LIMIT_EXCEEDED, categoryOf(assertThrows(UncheckedIOException.class, + () -> Seq.checkIndex(4, index)))); + assertEquals(2, out.size(), "neither refusal touched the array"); + } + // --- the category, and the decode it terminates ------------------------- /** diff --git a/src/test/java/org/sofabuffers/sofab/SeqTest.java b/src/test/java/org/sofabuffers/sofab/SeqTest.java index 59f6b9a..a7c3b35 100644 --- a/src/test/java/org/sofabuffers/sofab/SeqTest.java +++ b/src/test/java/org/sofabuffers/sofab/SeqTest.java @@ -7,6 +7,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -262,6 +263,168 @@ void aRowAtTheNextIndexAppends() { assertEquals(2, wrappers.size()); } + // --- placement: leaf elements -------------------------------------------- + + /** + * An id past the end fills the space below it with the element default rather + * than shifting every later element down by one: an interior element equal to + * that default is omitted by a conformant encoder (MESSAGE_SPEC §2), so ids + * {@code 0, 2} are a three-element array whose middle slot is the default. + */ + @Test + void aLeafElementGapFillsRatherThanShifts() { + List out = new ArrayList<>(); + Seq.placeElem(out, 0, "", "first", Bound.SCHEMA_BOUNDED); + Seq.placeElem(out, 2, "", "third", Bound.SCHEMA_BOUNDED); + + assertEquals(List.of("first", "", "third"), out); + } + + /** + * The array's length is highest present id + 1 (§5.1), so a single element at + * a high id is a long array of defaults — not a one-element one. + */ + @Test + void aLeafElementAloneAtAHighIdSetsTheLength() { + List out = new ArrayList<>(); + Seq.placeElem(out, 3, "", "last", Bound.SCHEMA_BOUNDED); + + assertEquals(4, out.size()); + assertEquals(List.of("", "", "", "last"), out); + } + + /** A repeated id replaces rather than appends: last occurrence wins (§7.4). */ + @Test + void aRepeatedLeafElementIdReplaces() { + List out = new ArrayList<>(); + Seq.placeElem(out, 1, "", "stale", Bound.SCHEMA_BOUNDED); + Seq.placeElem(out, 1, "", "fresh", Bound.SCHEMA_BOUNDED); + + assertEquals(List.of("", "fresh"), out); + } + + /** An element at the very next index appends rather than growing a gap. */ + @Test + void aLeafElementAtTheNextIndexAppends() { + List out = new ArrayList<>(); + Seq.placeElem(out, 0, "", "a", Bound.SCHEMA_BOUNDED); + Seq.placeElem(out, 1, "", "b", Bound.SCHEMA_BOUNDED); + + assertEquals(List.of("a", "b"), out); + } + + /** + * The gap value is shared, not copied: a blob array's default is the one + * {@link Seq#EMPTY_BYTES}, which has no state to share, so an array of ids + * {@code 0, 9} costs eight references and no allocation. + */ + @Test + void aLeafGapCostsNoAllocation() { + List out = new ArrayList<>(); + Seq.placeElem(out, 2, Seq.EMPTY_BYTES, new byte[] { 7 }, Bound.SCHEMA_BOUNDED); + + assertEquals(3, out.size()); + assertSame(Seq.EMPTY_BYTES, out.get(0)); + assertSame(Seq.EMPTY_BYTES, out.get(1)); + assertArrayEquals(new byte[] { 7 }, out.get(2)); + } + + /** + * Java erases generics, so the one method body above serves every element type + * a wrapper array of leaves can have — which is why this move costs no code + * growth on this port however many such arrays a schema declares. + */ + @Test + void oneBodyPlacesEveryLeafElementType() { + List strings = new ArrayList<>(); + List blobs = new ArrayList<>(); + Seq.placeElem(strings, 1, "", "s", Bound.SCHEMA_BOUNDED); + Seq.placeElem(blobs, 1, Seq.EMPTY_BYTES, new byte[] { 1 }, Bound.SCHEMA_BOUNDED); + + assertEquals(List.of("", "s"), strings); + assertEquals(2, blobs.size()); + assertArrayEquals(new byte[] { 1 }, blobs.get(1)); + } + + // --- placement: framed elements ------------------------------------------- + + /** + * A struct, union or nested-row element is mutable and caller-reachable, + * so every slot gets its own object from the factory. One shared instance would + * alias the whole array onto it — the reason this is a second method rather + * than {@link Seq#placeElem} with one more argument. + */ + @Test + void everyFramedSlotGetsItsOwnElement() { + List out = new ArrayList<>(); + Seq.reserveElem(out, 2, Elem::new, Bound.SCHEMA_BOUNDED); + + assertEquals(3, out.size()); + assertNotSame(out.get(0), out.get(1)); + assertNotSame(out.get(1), out.get(2)); + + out.get(2).a = 7; + assertEquals(0, out.get(0).a, "writing one element must not write them all"); + } + + /** + * A re-opened element id merges into the object its earlier fields built + * (§7.4 for a struct or union): the fields arrive one at a time, each routed + * into the slot this call reserved, so replacing the slot would discard them. + */ + @Test + void aRepeatedFramedElementIdMergesIntoTheSameObject() { + List out = new ArrayList<>(); + Seq.reserveElem(out, 0, Elem::new, Bound.SCHEMA_BOUNDED); + Elem first = out.get(0); + first.a = 3; + + Seq.reserveElem(out, 0, Elem::new, Bound.SCHEMA_BOUNDED); + assertSame(first, out.get(0), "the element is merged into, not started again"); + assertEquals(3, out.get(0).a); + assertEquals(1, out.size()); + } + + /** A reservation below the high-water mark creates nothing at all. */ + @Test + void aFramedReservationBelowTheHighWaterMarkMakesNoElement() { + int[] made = { 0 }; + List out = new ArrayList<>(); + Seq.reserveElem(out, 2, () -> { + made[0]++; + return new Elem(); + }, Bound.SCHEMA_BOUNDED); + assertEquals(3, made[0], "the slot and the two gaps below it"); + + Seq.reserveElem(out, 0, () -> { + made[0]++; + return new Elem(); + }, Bound.SCHEMA_BOUNDED); + assertEquals(3, made[0], "id 0 already had a slot"); + assertEquals(3, out.size()); + } + + /** + * A gap below a framed element is a default element, not a hole: an + * omitted interior element is one whose fields are all default (§2), and the + * factory is what says what that is. + */ + @Test + void aFramedGapIsADefaultElementAndNotNull() { + List out = new ArrayList<>(); + Seq.reserveElem(out, 1, Elem::new, Bound.SCHEMA_BOUNDED); + + assertNotNull(out.get(0)); + assertEquals(0, out.get(0).a); + assertEquals(0, out.get(0).b); + } + + /** A framed element stand-in: mutable and caller-reachable, like a generated struct. */ + private static final class Elem { + int a; + int b; + } + // --- re-arming and the encode-side identity ------------------------------ /** reset() empties in place — the point of taking a destination from the caller. */ From f296aff77c71b7b740d99533722c20e6ee1005ba Mon Sep 17 00:00:00 2001 From: Andreas Steinbart Date: Mon, 21 Sep 2026 22:30:17 +0000 Subject: [PATCH 2/3] feat(bound)!: compare the schema count in Seq, as Bound.schema(n) (generator#587) Bound gains a schema variant, Bound.schema(n), so the Seq reservations (placeElem, reserveElem, reserveRow, reserveRow*) and Seq.checkIndex compare a wrapper array's schema count themselves: id >= count is INVALID_MSG, a receiver cap stays LIMIT_EXCEEDED, and exactly one of the two is ever handed in (CORELIB_PLAN 6.2.1). The index is still compared before anything grows (7.2 item 8), and the fast path is still one comparison; the verdict is chosen out of line, on the path that throws. Bound.SCHEMA_BOUNDED stays for one legitimate use: a string/blob whose schema maxlen the caller already enforced at the length word, where PayloadAcc has no second number to compare. It carries no count, so every Seq reservation now refuses it as ARGUMENT instead of growing the list uncompared. PayloadAcc also honours Bound.schema(n) as a maxlen, INVALID_MSG above it. SchemaBoundTest pins the new variant on all nine reservations: at the bound, past it (INVALID, list not extended, a lower id still lands), and never LIMIT_EXCEEDED. SequenceGrowthTest now drives the real Seq.checkIndex, Seq.placeElem and Seq.reserveElem instead of a hand-rolled copy. BREAKING CHANGE: Seq reservations reject Bound.SCHEMA_BOUNDED with ARGUMENT; pass Bound.schema(count) where the schema bounds the array. --- README.md | 35 ++- .../java/org/sofabuffers/sofab/Bound.java | 255 +++++++++++----- .../org/sofabuffers/sofab/PayloadAcc.java | 21 +- src/main/java/org/sofabuffers/sofab/Seq.java | 286 +++++++++++------- .../java/org/sofabuffers/sofab/Sofab.java | 3 +- .../sofabuffers/sofab/ForgottenCapTest.java | 27 +- .../sofabuffers/sofab/ReceiverCapTest.java | 31 +- .../sofabuffers/sofab/SchemaBoundTest.java | 204 +++++++++++++ .../java/org/sofabuffers/sofab/SeqTest.java | 81 ++--- .../sofabuffers/sofab/SequenceGrowthTest.java | 65 ++-- 10 files changed, 699 insertions(+), 309 deletions(-) create mode 100644 src/test/java/org/sofabuffers/sofab/SchemaBoundTest.java diff --git a/README.md b/README.md index cbc556f..1b5622e 100644 --- a/README.md +++ b/README.md @@ -267,7 +267,7 @@ is an argument, an element type is a type parameter. | `Seq.placeElem` | place a wrapper array's decoded `string` or `blob` at the index its id names, filling the gaps omitted interior elements left with the shared element default; a repeated id replaces (MESSAGE_SPEC §5.1 / §7.4) | | `Seq.reserveElem` | reserve the slot a wrapper array's `struct`, `union` or nested-array element is routed into, one fresh element per slot from a factory; a re-opened id merges into the element its earlier fields built (§7.4) | | `Seq.reserveRow` / `reserveRowBytes` … `reserveRowDoubles` | place a matrix row at the index its id names, filling a gap with the empty row rather than shifting every later row down (MESSAGE_SPEC §5.1 / §7.4) | -| `Seq.checkIndex` | the element-index bound each of the three reservations above takes, on its own — for the **length word** of a `string`/`blob` element, which has no reservation to ride and must be judged before the payload (§5.2). Where the schema bounds the array this is `Bound.SCHEMA_BOUNDED` and the caller's own `INVALID` governs; where it does not, the `Bound` carries the receiver cap and the comparison happens here (§6.2.1) | +| `Seq.checkIndex` | the element-index bound each of the three reservations above takes, on its own — for the **length word** of a `string`/`blob` element, which has no reservation to ride and must be judged before the payload (§5.2). The `Bound` carries the schema `count` where the schema declares one (`Bound.schema`, `INVALID_MSG` at `id >= count`) and the receiver cap where it does not (`Bound.receiver`, `LIMIT_EXCEEDED`); either way the comparison happens here, before anything grows (§6.2.1, §7.2 item 8) | | `Seq.ensureCap` (one per primitive width) | the array-growth policy: double, stop at the announced count, and never allocate from a count the wire claimed but has not delivered | | `Seq.ARRAY_INIT_CAP`, `Seq.EMPTY_BYTES` … `EMPTY_DOUBLES` | the bounded first reservation, and the shared zero-length arrays a field initializer points at | | `Seq.reset` / `Seq.orEmpty` / `Seq.boolsToLongs` | re-arm a reused destination in place; absorb a null field on the encode side; the one boxed-to-primitive conversion `bool` still needs | @@ -275,7 +275,7 @@ is an argument, an element type is a type parameter. | `Utf8.decode` | validate a byte range and materialize it, in that order — the only order in which invalid UTF-8 can still be rejected (§6.4) | | `Sofab.invalid` | the carrier a `Visitor` rejects malformed input through, since a callback declares no checked exception; `IStream.feed` latches it as terminal like its own rejections | | `Sofab.limitExceeded` / `Sofab.argument` | the twin carrier for a receiver-limit refusal, which is latched as terminal too but under its own code, **never** as `INVALID`; and the carrier for a defect in the call, such as a bound the caller never stated | -| `Bound.receiver` / `Bound.SCHEMA_BOUNDED` | which of §6.2.1's two rules bounds one field: the deployment's configured cap, or the schema's own `count`/`maxlen` | +| `Bound.schema` / `Bound.receiver` / `Bound.SCHEMA_BOUNDED` | which of §6.2.1's two rules bounds one field, with its number and its verdict: the schema's own `count`/`maxlen` (`INVALID_MSG`), or the deployment's configured cap (`LIMIT_EXCEEDED`); `SCHEMA_BOUNDED` is the numberless statement for a payload whose `maxlen` the caller has already enforced | | `OStream.overScratch` / `copyOfBytesUsed` | a per-thread buffer for a one-shot `encode()`, so the worst case is allocated once per thread rather than once per call. The **size** stays with the caller (CORELIB_PLAN §5.1): generated code passes its own `MAX_SIZE` | These are ordinary public API, usable directly; they are simply shaped by what @@ -298,6 +298,11 @@ the limit guards: | `max_dyn_blob_len` | `PayloadAcc.blob(…, bound)` | the same | | `max_dyn_array_count` | `Seq.placeElem` / `reserveElem` / `reserveRow` / `reserveRow*(…, bound)`, and `Seq.checkIndex(…, bound)` at a `string`/`blob` element's length word | the element **index**, before anything is created and before the list grows | +The same array calls take the schema `count` too, as `Bound.schema(count)`, and +compare it in the same place: a `count` is a capacity, so `id >= count` is +`INVALID_MSG` (MESSAGE_SPEC §7.1) and never `LIMIT_EXCEEDED`. One argument per +field, so the schema bound and the cap are never both in force. + A breach is `SofabError.LIMIT_EXCEEDED` — a policy rejection of well-formed bytes, never clamped into a shortened value and never the `INVALID` outcome. It is **terminal** (§6.3): the decode ends there, and every further `feed` repeats the @@ -306,37 +311,39 @@ that passes a cap here does not also guard in front of the call: the rule has on implementation. `Bound` is what each of those calls takes, and it has exactly the two answers -§6.2.1 admits — never one number with a reserved value for the second: +§6.2.1 admits, each carrying its own verdict — never one number with a reserved +value for the second: ```java private static final Bound TAGS_CAP = Bound.receiver(MAX_DYN_ARRAY_COUNT); +private static final Bound ROWS_COUNT = Bound.schema(8); -Seq.reserveRow(rows, id, TAGS_CAP); // schema declares no count: -Seq.reserveRow(rows, id, Bound.SCHEMA_BOUNDED); // count: N — checked one line above +Seq.reserveRow(rows, id, TAGS_CAP); // schema declares no count: LIMIT_EXCEEDED at the cap +Seq.reserveRow(rows, id, ROWS_COUNT); // count: 8 — INVALID_MSG at id 8 and above ``` `Bound.receiver(n)` is the deployment's configured number for a schema-unbounded -field. `Bound.SCHEMA_BOUNDED` states that the schema's `maxlen`/`count` governs -instead (a breach there is the caller's `Sofab.invalid`, `INVALID_MSG`) — it carries -no number, because this library does not apply the schema bound and a second copy of -that rule here is what §6.2.1's *one implementation* forbids. +field. `Bound.schema(n)` is the schema's `count` (or `maxlen`), compared by the same +call. `Bound.SCHEMA_BOUNDED` is the numberless statement for a `string`/`blob` +whose `maxlen` the caller has already enforced at its length word, so `PayloadAcc` +compares nothing; it cannot bound an array index, and every `Seq` reservation +refuses it as `SofabError.ARGUMENT`. **A cap that was never stated is reported, not obeyed.** §6.2.1 admits "no unset state and no unlimited mode" and forbids reading an omitted argument as *unlimited*, so there is no numeric value that means "the schema bounds this" and nothing to -default to: `Bound.receiver` refuses `0` (Java's unassigned field) and every -negative (the sentinel this shape replaced), and a `null` bound is +default to: `Bound.receiver` and `Bound.schema` refuse `0` (Java's unassigned field) +and every negative (the sentinel this shape replaced), and a `null` bound is `SofabError.ARGUMENT` — a defect in the **call**, not `LIMIT_EXCEEDED`, which would promise a limit to raise that was never configured (§6.3). `ARRAY_MAX` is a format ceiling and is not available as a fallback either. Build each `Bound` once, into a `static final`: they are constants of the -deployment, so nothing is allocated per call or per message. +deployment or the schema, so nothing is allocated per call or per message. Two checks stay in generated code, because no call into this library carries them: a **native array count** (`new int[count]` is written straight into the field) and -the element **index of a flat wrapper array** of strings, blobs or sub-messages -(placed by an inline `while (list.size() <= id)`). +a matrix **row's own element count**. ## Memory handling diff --git a/src/main/java/org/sofabuffers/sofab/Bound.java b/src/main/java/org/sofabuffers/sofab/Bound.java index 38ab856..06ffb01 100644 --- a/src/main/java/org/sofabuffers/sofab/Bound.java +++ b/src/main/java/org/sofabuffers/sofab/Bound.java @@ -6,92 +6,116 @@ */ package org.sofabuffers.sofab; +import java.io.UncheckedIOException; + /** * Which of the two rules of CORELIB_PLAN §6.2.1 bounds this field: the * schema's {@code count}/{@code maxlen}, or a receiver cap the - * deployment configured. + * deployment configured — and, with it, the number and the verdict a breach earns. * *

The two are mutually exclusive — §6.2.1: receiver limits "MUST NOT be * applied to a field the schema already bounds. There the schema bound governs and * its violation is {@code INVALID}" — and they are the only two answers. This type * exists so that a call site has to give one of them, and so that saying which - * is not the same act as choosing a number: + * is part of the value rather than a convention beside it: * *

    - *
  • {@link #SCHEMA_BOUNDED} — the schema declares the ceiling. The caller has - * already enforced it at this same header, as {@link Sofab#invalid} - * (MESSAGE_SPEC §7.1), so there is no second number to compare against here. + *
  • {@link #schema(long)} — the schema declares the ceiling {@code n}. The call + * it is handed to compares against it, and a breach is + * {@link SofabError#INVALID_MSG} (MESSAGE_SPEC §7.1): the bytes contradict the + * schema both peers agreed on. It never reports + * {@link SofabError#LIMIT_EXCEEDED}. *
  • {@link #receiver(long)} — the schema declares none, and this is the * deployment's {@code max_dyn_string_len} / {@code max_dyn_blob_len} / * {@code max_dyn_array_count} for the field. A breach is - * {@link SofabError#LIMIT_EXCEEDED}. + * {@link SofabError#LIMIT_EXCEEDED}: the bytes are well-formed and the same + * message decodes under a looser cap. + *
  • {@link #SCHEMA_BOUNDED} — the schema declares a {@code maxlen} for a + * {@code string}/{@code blob} the caller has already enforced at the + * same header, so a {@link PayloadAcc} length check has no second number to + * compare. It carries no number, and so it cannot bound an array + * index: every {@link Seq} reservation refuses it as + * {@link SofabError#ARGUMENT} and wants {@link #schema(long)} instead. *
* - *

Why a type and not a number. These two answers used to share one - * {@code long} parameter, with a negative sentinel for the first — so a caller who - * had forgotten to state a cap and a caller asserting the schema bounds - * this field handed over the identical bit pattern, and the forgotten one - * decoded uncapped and unreported. One sentinel cannot carry two opposite meanings. - * Here the schema answer is a distinct object carrying no number at all, and - * every numeric value that reaches a cap comparison is a receiver cap, - * because {@link #receiver(long)} is the only way to make one. + *

One implementation of each rule. The {@link Seq} reservations take the + * schema {@code count} as {@code Bound.schema(count)} and compare it themselves, + * exactly where they compare a receiver cap, so a caller that passes a bound does + * not also guard in front of the call. §6.2.1's "never both" then holds by + * construction: one argument, one number, one verdict. The index is compared + * before anything is created or grown (CORELIB_PLAN §7.2 item 8). + * + *

Why a type and not a number. These answers used to share one + * {@code long} parameter, with a negative sentinel for "the schema bounds this" — + * so a caller who had forgotten to state a cap and a caller asserting the + * schema's rule handed over the identical bit pattern, and the forgotten one decoded + * uncapped and unreported. Here the verdict travels with the number, and the only + * ways to make a bound carrying a number are the two named factories. * *

Both "forgot" values are diagnosed, not obeyed. Java writes an * unassigned {@code long} field as {@code 0} and the retired sentinel was - * {@code -1}; {@link #receiver(long)} refuses both with {@link SofabError#ARGUMENT}, - * and a {@code null} reference reaching one of the calls is refused the same way - * rather than read as no cap. §6.2.1 admits "no unset state and no - * unlimited mode", and a codec "MUST NOT read an omitted argument as + * {@code -1}; both factories refuse both with {@link SofabError#ARGUMENT}, and a + * {@code null} reference reaching one of the calls is refused the same way rather + * than read as no cap. §6.2.1 admits "no unset state and no unlimited + * mode", and a codec "MUST NOT read an omitted argument as * unlimited". * *

This library still holds no limit. A {@code Bound} is built by the * caller out of the caller's number, used for one comparison and not retained; * nothing here defaults one, falls back to one, or clamps to one. * {@link Sofab#ARRAY_MAX} and {@link Sofab#ID_MAX} are format ceilings, - * whose breach is {@link SofabError#INVALID_MSG}, and §6.2.1 forbids presenting one - * as a receiver cap — so there is deliberately no {@code Bound} that means "the - * format ceiling". + * and §6.2.1 forbids presenting one as a receiver cap — so there is deliberately no + * {@code Bound} that means "the format ceiling". * *

Where the value comes from, and what it costs. A cap is a constant of - * the deployment, so generated code builds its {@code Bound}s once, into - * {@code static final} fields, and passes them per call: + * the deployment and a schema bound a constant of the schema, so generated code + * builds its {@code Bound}s once, into {@code static final} fields, and passes them + * per call: * *

{@code
- * private static final Bound STRING_CAP = Bound.receiver(MAX_DYN_STRING_LEN);
+ * private static final Bound CAP_DYN_ARRAY_COUNT = Bound.receiver(MAX_DYN_ARRAY_COUNT);
+ * private static final Bound TAGS_COUNT = Bound.schema(8);
  *
- * public void string(int id, int total, int offset, byte[] data, int co, int cl) {
- *     switch (id) {
- *         case 1 -> { // schema: maxlen: 64 -- the caller's own INVALID check
- *             if (total > 64) { throw Sofab.invalid("note: string length above maxlen 64"); }
- *             note = acc.string(total, offset, data, co, cl, Bound.SCHEMA_BOUNDED);
- *         }
- *         case 2 -> // schema declares no maxlen
- *             free = acc.string(total, offset, data, co, cl, STRING_CAP);
- *         default -> { }  // an id this message does not read: never capped
- *     }
- * }
+ * // schema `count: 8` -- compared inside, INVALID_MSG at index 8 and above
+ * Seq.placeElem(m.tags, id, "", s, TAGS_COUNT);
+ * // schema declares no count -- compared inside, LIMIT_EXCEEDED at the cap
+ * Seq.placeElem(m.notes, id, "", s, CAP_DYN_ARRAY_COUNT);
  * }
* - *

Nothing is allocated per call or per message on that path, and both constants - * are {@code static final} objects with a {@code final} field, which the JIT folds + *

Nothing is allocated per call or per message on that path, and every constant + * is a {@code static final} object with {@code final} fields, which the JIT folds * into the comparison it guards. * *

Instances are immutable and shareable. */ public final class Bound { + /** {@link #SCHEMA_BOUNDED}: a statement with no number. */ + private static final byte STATED = 0; + /** {@link #schema(long)}: the schema's bound, INVALID_MSG past it. */ + private static final byte SCHEMA = 1; + /** {@link #receiver(long)}: the deployment's cap, LIMIT_EXCEEDED past it. */ + private static final byte RECEIVER = 2; + /** - * The receiver cap, or {@code -1} for {@link #SCHEMA_BOUNDED}. Only - * {@link #receiver(long)} can produce a non-negative value, and it refuses - * everything below {@code 1}, so a non-negative {@code cap} here is always a - * number a caller deliberately configured. + * The number, or {@code -1} for {@link #SCHEMA_BOUNDED}. Only the two factories + * produce a non-negative value, and both refuse everything below {@code 1}, so a + * non-negative {@code max} here is always a number a caller deliberately stated. + * + *

The {@code -1} is also what keeps the index comparison a single compare: + * every index is {@code >= -1}, so {@link #SCHEMA_BOUNDED} always reaches the + * out-of-line rejection, which refuses it as {@link SofabError#ARGUMENT}. */ - private final long cap; + private final long max; + + /** Which rule {@link #max} states: {@link #STATED}, {@link #SCHEMA} or {@link #RECEIVER}. */ + private final byte kind; /** - * The schema bounds this field, so §6.2.1 forbids a receiver cap on it: the - * {@code count} or {@code maxlen} governs and a breach is the caller's - * {@link Sofab#invalid} (MESSAGE_SPEC §7.1). + * The schema bounds this {@code string} or {@code blob} and the caller has + * already enforced its {@code maxlen} at the same header, as + * {@link Sofab#invalid} (MESSAGE_SPEC §7.1), so §6.2.1 forbids a receiver cap + * on it and there is no second number for {@link PayloadAcc} to compare. * *

It is not "unlimited", and it is not "unset". It is a statement * about which rule applies, made by the layer that knows the schema. Passing it @@ -99,16 +123,50 @@ public final class Bound { * much this process holds; that is a defect in the call, not a mode this * library offers. * - *

It carries no number, because this library does not apply the schema - * bound — the caller does, at the same header, one line before the call. Handing - * the {@code maxlen} over as well would put a second implementation of - * MESSAGE_SPEC §7.1 here, which §6.2.1's "one implementation, wherever it runs" - * forbids just as it forbids two implementations of the cap. + *

It bounds no array index. An index has a reservation to ride, and + * the reservation compares the schema {@code count} itself when handed + * {@link #schema(long)}; every {@link Seq} call refuses this value as + * {@link SofabError#ARGUMENT} rather than growing a list uncompared. */ - public static final Bound SCHEMA_BOUNDED = new Bound(-1L); + public static final Bound SCHEMA_BOUNDED = new Bound(-1L, STATED); - private Bound(long cap) { - this.cap = cap; + private Bound(long max, byte kind) { + this.max = max; + this.kind = kind; + } + + /** + * The bound the schema declares for this field — an array's {@code count}, or a + * {@code string}/{@code blob}'s {@code maxlen} — compared by the call it is + * handed to. A value past it is {@link SofabError#INVALID_MSG} (MESSAGE_SPEC + * §7.1), never {@link SofabError#LIMIT_EXCEEDED}: the bytes contradict the + * schema, and no receiver configuration makes them decode. + * + *

A {@code count} is a capacity, not a length: the destination starts + * empty and the wire carries the length, so an element index {@code id} breaches + * it when {@code id >= count}. A {@code maxlen} bounds a byte length, which + * breaches it when {@code length > maxlen}. + * + *

The number is the schema's, and §6.2.1's exclusivity is the caller's to + * honour by handing over exactly one bound per field: where the schema declares + * this, no receiver cap applies. + * + * @param n the schema's {@code count} or {@code maxlen}, at least {@code 1} — + * what the schema validator admits + * @return the bound to hand to the call that guards the field + * @throws IllegalArgumentException if {@code n} is below {@code 1}; it refines + * {@link SofabError#ARGUMENT} (§6.3). {@code 0} + * is an unassigned field and a negative is the + * retired sentinel, neither of them a schema + * bound + */ + public static Bound schema(long n) { + if (n < 1L) { + throw new IllegalArgumentException( + "sofab: " + SofabError.ARGUMENT + " (schema bound " + n + + " is not a count or maxlen: a schema admits 1 and above)"); + } + return new Bound(n, SCHEMA); } /** @@ -129,7 +187,7 @@ private Bound(long cap) { *

  • {@code 0} is what Java writes into an unassigned {@code long} or * {@code int} field, so accepting it would let an unconfigured constant * silently become a policy that refuses every non-empty value; - *
  • a negative was the retired sentinel for {@link #SCHEMA_BOUNDED}, and is + *
  • a negative was the retired sentinel for "the schema bounds this", and is * the bit pattern this type exists to stop meaning two things. * * @@ -151,44 +209,81 @@ public static Bound receiver(long max) { + " is not a limit: a cap is at least 1, and " + (max == 0L ? "0 is an unassigned field, not a policy" : "a negative is not \"the schema bounds this\" — " - + "pass Bound.SCHEMA_BOUNDED for that") + + "pass Bound.schema(n) for that") + ")"); } - return new Bound(max); + return new Bound(max, RECEIVER); } /** - * Whether {@code value} breaches this bound — {@code false} for + * Whether a byte {@code length} breaches this bound — {@code false} for * {@link #SCHEMA_BOUNDED}, which states that the caller's own schema check * governs the field. * - * @param value the announced length or the element index at the header - * @return true if a receiver cap is stated and {@code value} is above it + * @param length the announced payload length at the header + * @return true if a number is stated and {@code length} is above it + */ + boolean exceededBy(long length) { + return kind != STATED && length > max; + } + + /** + * The rejection for a {@code length} {@link #exceededBy} refused, out of line + * so the comparison that guards it stays small on the decode path: INVALID_MSG + * for the schema's {@code maxlen}, LIMIT_EXCEEDED for the receiver's cap. + * + * @param noun {@code "string length"} or {@code "blob length"} + * @param length the announced length + * @return the exception to throw */ - boolean exceededBy(long value) { - return cap >= 0L && value > cap; + UncheckedIOException rejectLength(String noun, long length) { + if (kind == SCHEMA) { + return Sofab.invalid(noun + " " + length + " above schema maxlen " + max); + } + return Sofab.limitExceeded(noun + " " + length + " above configured limit " + max); } /** - * Whether {@code index} breaches this bound as an element index: an - * element at index {@code cap} makes an array of {@code cap + 1}, so the - * comparison is {@code >=} rather than {@code >}. + * The rejection for an element {@code index} that reached the out-of-line path + * of {@link Seq#checkIndex} — {@code index >= max}, which every index meets for + * {@link #SCHEMA_BOUNDED}. + * + *
      + *
    • {@link #schema(long)}: INVALID_MSG. An index at or past the schema + * {@code count} makes an array longer than the schema's capacity + * (MESSAGE_SPEC §7.1). + *
    • {@link #receiver(long)}: LIMIT_EXCEEDED. An element at index {@code cap} + * makes a list of {@code cap + 1}, one more than the receiver said it would + * hold (§6.2.1). Rejected, never clamped — placing it at {@code cap - 1} + * instead would be data corruption. + *
    • {@link #SCHEMA_BOUNDED}: ARGUMENT. It carries no count, so the call has + * nothing to compare; silence would grow the list uncompared. + *
    * * @param index the wire's element index - * @return true if a receiver cap is stated and {@code index} is at or past it + * @return the exception to throw */ - boolean exceededByIndex(long index) { - return cap >= 0L && index >= cap; + UncheckedIOException rejectIndex(long index) { + switch (kind) { + case SCHEMA: + return Sofab.invalid("array element index " + index + " above schema capacity " + max); + case RECEIVER: + return Sofab.limitExceeded("array element index " + index + " above configured limit " + max); + default: + return Sofab.argument("Bound.SCHEMA_BOUNDED carries no count and cannot bound an " + + "array index: pass Bound.schema(count) where the schema bounds the " + + "array, or Bound.receiver(n) where it does not"); + } } /** - * The configured limit, for the rejection message. Negative for - * {@link #SCHEMA_BOUNDED}, which never rejects. + * The stated number — what {@link Seq#checkIndex} compares an index against, + * and what a diagnostic names. Negative for {@link #SCHEMA_BOUNDED}. * - * @return the cap + * @return the number */ long cap() { - return cap; + return max; } /** @@ -197,14 +292,14 @@ long cap() { * argument as unlimited"). * * @param bound the caller's bound - * @param which the {@code max_dyn_*} limit this call guards, for the diagnostic + * @param which what this call bounds, for the diagnostic * @return {@code bound} */ static Bound required(Bound bound, String which) { if (bound == null) { throw Sofab.argument("no bound stated for " + which - + ": pass Bound.receiver(n) with the configured limit, or " - + "Bound.SCHEMA_BOUNDED where the schema bounds this field"); + + ": pass Bound.schema(n) where the schema bounds this field, or " + + "Bound.receiver(n) with the configured limit where it does not"); } return bound; } @@ -212,10 +307,18 @@ static Bound required(Bound bound, String which) { /** * A short description naming which rule this states, for diagnostics. * - * @return {@code "Bound.SCHEMA_BOUNDED"} or {@code "Bound.receiver(n)"} + * @return {@code "Bound.SCHEMA_BOUNDED"}, {@code "Bound.schema(n)"} or + * {@code "Bound.receiver(n)"} */ @Override public String toString() { - return cap < 0L ? "Bound.SCHEMA_BOUNDED" : "Bound.receiver(" + cap + ")"; + switch (kind) { + case SCHEMA: + return "Bound.schema(" + max + ")"; + case RECEIVER: + return "Bound.receiver(" + max + ")"; + default: + return "Bound.SCHEMA_BOUNDED"; + } } } diff --git a/src/main/java/org/sofabuffers/sofab/PayloadAcc.java b/src/main/java/org/sofabuffers/sofab/PayloadAcc.java index 55b82cf..595eacf 100644 --- a/src/main/java/org/sofabuffers/sofab/PayloadAcc.java +++ b/src/main/java/org/sofabuffers/sofab/PayloadAcc.java @@ -75,7 +75,9 @@ * {@code maxlen} governs instead — a distinct value carrying no number, so a caller * that forgot to configure a cap cannot arrive here spelling the same thing a * schema-bounded field spells. A missing bound is {@link Sofab#argument}, never - * silently uncapped. + * silently uncapped. A caller may instead hand the {@code maxlen} itself over as + * {@link Bound#schema(long)}; it is then compared here like a cap, but a breach is + * {@code INVALID_MSG} (MESSAGE_SPEC §7.1), never {@code LIMIT_EXCEEDED}. * *

    The number is the caller's. §6.2.1 fixes the provenance of a receiver * limit — it comes from generated code, which knows the schema and the target — @@ -227,7 +229,7 @@ public byte[] blob(int total, int offset, byte[] data, int chunkOffset, int chun */ public static void checkStringLength(int total, Bound bound) { if (Bound.required(bound, "max_dyn_string_len").exceededBy(total)) { - throw overCap("string length", total, bound); + throw bound.rejectLength("string length", total); } } @@ -246,23 +248,10 @@ public static void checkStringLength(int total, Bound bound) { */ public static void checkBlobLength(int total, Bound bound) { if (Bound.required(bound, "max_dyn_blob_len").exceededBy(total)) { - throw overCap("blob length", total, bound); + throw bound.rejectLength("blob length", total); } } - /** - * Build the {@link SofabError#LIMIT_EXCEEDED} rejection, out of line so the - * comparison that guards it stays two instructions on the decode path. - * - *

    The detail names the announced length and the limit it broke, which is - * what a receiver acts on: raise the limit, or the sender sends less. It does - * not name the field — this class is handed a payload, not a schema — so a - * caller wanting the field in the message catches and re-raises. - */ - private static java.io.UncheckedIOException overCap(String noun, int total, Bound bound) { - return Sofab.limitExceeded(noun + " " + total + " above configured limit " + bound.cap()); - } - /** * Append a chunk, growing the buffer as bytes actually arrive. * diff --git a/src/main/java/org/sofabuffers/sofab/Seq.java b/src/main/java/org/sofabuffers/sofab/Seq.java index 453afdf..b2d74e4 100644 --- a/src/main/java/org/sofabuffers/sofab/Seq.java +++ b/src/main/java/org/sofabuffers/sofab/Seq.java @@ -49,16 +49,20 @@ * follow, bounded by nothing until a schema {@code count} or a receiver limit * bounds it, so no method here allocates from a count alone. * - *

    Receiver caps (CORELIB_PLAN §6.2.1). Every reservation here — - * {@link #placeElem}, {@link #reserveElem}, {@link #reserveRow} and the six - * primitive {@code reserveRow*} overloads — takes a {@link Bound} on the array's - * element index and compares it here, before anything is created and before - * the list is grown to hold it. A wrapper array announces no count, so the index is - * what a cap can bind: its length is highest present id + 1 (MESSAGE_SPEC §5.1), - * and two elements at id 0 and id 65535 are a 65536-slot list. §6.2.1 permits - * exactly this placement — "a corelib MAY take a limit as an argument and perform - * the check itself, and a port that does is conformant" — and the rule then has - * one implementation: a caller that passes the cap does not also guard in + *

    The index bound (MESSAGE_SPEC §7.1, CORELIB_PLAN §6.2.1). Every + * reservation here — {@link #placeElem}, {@link #reserveElem}, {@link #reserveRow} + * and the six primitive {@code reserveRow*} overloads — takes a {@link Bound} on the + * array's element index and compares it here, before anything is created and + * before the list is grown to hold it. A wrapper array announces no count, so the + * index is what bounds it: its length is highest present id + 1 (MESSAGE_SPEC §5.1), + * and two elements at id 0 and id 65535 are a 65536-slot list. The bound is the + * schema {@code count} where the schema declares one ({@link Bound#schema(long)}, + * a capacity; a breach is {@code INVALID}) and the receiver's + * {@code max_dyn_array_count} where it does not ({@link Bound#receiver(long)}; a + * breach is {@code LIMIT_EXCEEDED}) — exactly one of the two, never both. §6.2.1 + * permits this placement — "a corelib MAY take a limit as an argument and perform + * the check itself, and a port that does is conformant" — and each rule then has + * one implementation: a caller that passes the bound does not also guard in * front of the call. * *

    {@link #checkIndex} is that comparison on its own, published for the one site @@ -72,16 +76,17 @@ *

    Nothing here holds a limit. The number is the caller's, used for that * one comparison and not retained; there is no default, no fallback and no * clamping, and {@link Sofab#ARRAY_MAX} is a format ceiling rather than a - * receiver cap. Where the schema bounds the outer array the caller passes - * {@link Bound#SCHEMA_BOUNDED} and rejects an over-capacity index itself, as - * {@code INVALID} (MESSAGE_SPEC §7.1). + * receiver cap. The schema {@code count} is the schema's number, handed in the + * same way. * *

    The two answers are separate values, and an unstated one is refused. - * {@link Bound#receiver(long)} is the only way to reach the comparison with a - * number, so a caller who never configured a cap cannot arrive here spelling what - * a schema-bounded field spells; a {@code null} is {@link Sofab#argument} rather - * than an uncapped index. §6.2.1: "no unset state and no unlimited mode", and a - * codec "MUST NOT read an omitted argument as unlimited". + * {@link Bound#schema(long)} and {@link Bound#receiver(long)} are the only ways to + * reach the comparison with a number, and each carries its own verdict, so a + * caller who never configured a cap cannot arrive here spelling what a + * schema-bounded array spells. A {@code null}, and {@link Bound#SCHEMA_BOUNDED} + * (which carries no count), are {@link Sofab#argument} rather than an uncompared + * index. §6.2.1: "no unset state and no unlimited mode", and a codec "MUST NOT read + * an omitted argument as unlimited". * *

    What the caps here do not cover. A {@code string} or {@code blob} * element's own {@code maxlen} is not one of these arguments: the payload arrives @@ -162,10 +167,10 @@ private Seq() { *

    The index is bounded before the list grows (§7.2 item 8), so a * refused id leaves the list exactly as it was and a lower id delivered * afterwards still lands at its own index. Where the schema declares a - * {@code count} the caller has already rejected a breach as {@code INVALID} - * (MESSAGE_SPEC §7.1) and passes {@link Bound#SCHEMA_BOUNDED}; where it - * declares none, {@code bound} carries the receiver cap, the comparison happens - * here and a breach is {@code LIMIT_EXCEEDED}. Never both (§6.2.1). + * {@code count}, {@code bound} carries it and a breach is {@code INVALID} + * (MESSAGE_SPEC §7.1); where it declares none, {@code bound} carries the + * receiver cap and a breach is {@code LIMIT_EXCEEDED}. Never both (§6.2.1); + * see {@link #checkIndex}. * *

    {@code def} is shared, not copied. The gap value of an array of * strings or blobs is {@code ""} or {@link #EMPTY_BYTES} — immutable, or @@ -177,15 +182,19 @@ private Seq() { * @param id the element's wire id, which is its index * @param def the element default, filling any gap below {@code id} * @param value the decoded element - * @param bound {@link Bound#receiver(long)} carrying the caller's - * {@code max_dyn_array_count} (§6.2.1), or - * {@link Bound#SCHEMA_BOUNDED} where the schema bounds the array + * @param bound {@link Bound#schema(long)} carrying the schema {@code count}, + * or {@link Bound#receiver(long)} carrying the caller's + * {@code max_dyn_array_count} where the schema declares none + * (§6.2.1) — see {@link #checkIndex} * @param element type - * @throws java.io.UncheckedIOException wrapping a {@code LIMIT_EXCEEDED} + * @throws java.io.UncheckedIOException wrapping an {@code INVALID_MSG} * {@link SofabException} when {@code id} - * is at or past the receiver cap, or an + * is at or past the schema {@code count}, + * a {@code LIMIT_EXCEEDED} one when it is + * at or past the receiver cap, or an * {@code ARGUMENT} one when {@code bound} - * is null + * is null or {@link Bound#SCHEMA_BOUNDED}; + * the list is left untouched in all three */ public static void placeElem(List out, int id, T def, T value, Bound bound) { checkIndex(id, bound); @@ -229,15 +238,19 @@ public static void placeElem(List out, int id, T def, T value, Bound boun * @param out the destination list, which this grows * @param id the element's wire id, which is its index * @param make the element factory, called once per slot this creates - * @param bound {@link Bound#receiver(long)} carrying the caller's - * {@code max_dyn_array_count} (§6.2.1), or - * {@link Bound#SCHEMA_BOUNDED} where the schema bounds the array + * @param bound {@link Bound#schema(long)} carrying the schema {@code count}, + * or {@link Bound#receiver(long)} carrying the caller's + * {@code max_dyn_array_count} where the schema declares none + * (§6.2.1) — see {@link #checkIndex} * @param element type - * @throws java.io.UncheckedIOException wrapping a {@code LIMIT_EXCEEDED} + * @throws java.io.UncheckedIOException wrapping an {@code INVALID_MSG} * {@link SofabException} when {@code id} - * is at or past the receiver cap, or an + * is at or past the schema {@code count}, + * a {@code LIMIT_EXCEEDED} one when it is + * at or past the receiver cap, or an * {@code ARGUMENT} one when {@code bound} - * is null + * is null or {@link Bound#SCHEMA_BOUNDED}; + * the list is left untouched in all three */ public static void reserveElem(List out, int id, Supplier make, Bound bound) { checkIndex(id, bound); @@ -268,23 +281,25 @@ public static void reserveElem(List out, int id, Supplier make, Bound * *

    {@code id} is the wire's, and this grows the list to hold it, so it is * bounded here. Which bound depends on the outer array: where the schema - * declares a capacity the caller checks it before calling and rejects a - * breach as {@code INVALID} (MESSAGE_SPEC §7.1), passing - * {@link Bound#SCHEMA_BOUNDED}; where the schema declares none, {@code bound} - * carries the receiver cap and the comparison happens here (§6.2.1). + * declares a capacity, {@code bound} carries it and a breach is {@code INVALID} + * (MESSAGE_SPEC §7.1); where the schema declares none, {@code bound} carries + * the receiver cap and a breach is {@code LIMIT_EXCEEDED} (§6.2.1). * * @param rows the outer list, one entry per row * @param id index of the row to reserve - * @param bound {@link Bound#receiver(long)} carrying the caller's - * {@code max_dyn_array_count} (§6.2.1), or - * {@link Bound#SCHEMA_BOUNDED} where the schema bounds the outer - * array + * @param bound {@link Bound#schema(long)} carrying the outer array's schema + * {@code count}, or {@link Bound#receiver(long)} carrying the + * caller's {@code max_dyn_array_count} where the schema declares + * none (§6.2.1) — see {@link #checkIndex} * @param row element type - * @throws java.io.UncheckedIOException wrapping a {@code LIMIT_EXCEEDED} + * @throws java.io.UncheckedIOException wrapping an {@code INVALID_MSG} * {@link SofabException} when {@code id} - * is at or past the receiver cap, or an + * is at or past the schema {@code count}, + * a {@code LIMIT_EXCEEDED} one when it is + * at or past the receiver cap, or an * {@code ARGUMENT} one when {@code bound} - * is null + * is null or {@link Bound#SCHEMA_BOUNDED}; + * the list is left untouched in all three */ public static void reserveRow(List> rows, int id, Bound bound) { checkIndex(id, bound); @@ -316,17 +331,20 @@ public static void reserveRow(List> rows, int id, Bound bound) { * @param rows the outer list, one entry per row * @param id index of the row to reserve * @param n initial length of the new row - * @param bound {@link Bound#receiver(long)} carrying the caller's - * {@code max_dyn_array_count} (§6.2.1) bounding the row - * index, or {@link Bound#SCHEMA_BOUNDED} where the schema - * bounds the outer array. It does not bound {@code n}, which the - * caller has already bounded. + * @param bound {@link Bound#schema(long)} carrying the outer array's schema + * {@code count}, or {@link Bound#receiver(long)} carrying the + * caller's {@code max_dyn_array_count}, bounding the row + * index — see {@link #checkIndex}. It does not bound + * {@code n}, which the caller has already bounded. * @return the new row, now at index {@code id} - * @throws java.io.UncheckedIOException wrapping a {@code LIMIT_EXCEEDED} + * @throws java.io.UncheckedIOException wrapping an {@code INVALID_MSG} * {@link SofabException} when {@code id} - * is at or past the receiver cap, or an + * is at or past the schema {@code count}, + * a {@code LIMIT_EXCEEDED} one when it is + * at or past the receiver cap, or an * {@code ARGUMENT} one when {@code bound} - * is null + * is null or {@link Bound#SCHEMA_BOUNDED}; + * the list is left untouched in all three */ public static byte[] reserveRowBytes(List rows, int id, int n, Bound bound) { checkIndex(id, bound); @@ -348,17 +366,20 @@ public static byte[] reserveRowBytes(List rows, int id, int n, Bound bou * @param rows the outer list, one entry per row * @param id index of the row to reserve * @param n initial length of the new row - * @param bound {@link Bound#receiver(long)} carrying the caller's - * {@code max_dyn_array_count} (§6.2.1) bounding the row - * index, or {@link Bound#SCHEMA_BOUNDED} where the schema - * bounds the outer array. It does not bound {@code n}, which the - * caller has already bounded. + * @param bound {@link Bound#schema(long)} carrying the outer array's schema + * {@code count}, or {@link Bound#receiver(long)} carrying the + * caller's {@code max_dyn_array_count}, bounding the row + * index — see {@link #checkIndex}. It does not bound + * {@code n}, which the caller has already bounded. * @return the new row, now at index {@code id} - * @throws java.io.UncheckedIOException wrapping a {@code LIMIT_EXCEEDED} + * @throws java.io.UncheckedIOException wrapping an {@code INVALID_MSG} * {@link SofabException} when {@code id} - * is at or past the receiver cap, or an + * is at or past the schema {@code count}, + * a {@code LIMIT_EXCEEDED} one when it is + * at or past the receiver cap, or an * {@code ARGUMENT} one when {@code bound} - * is null + * is null or {@link Bound#SCHEMA_BOUNDED}; + * the list is left untouched in all three */ public static short[] reserveRowShorts(List rows, int id, int n, Bound bound) { checkIndex(id, bound); @@ -380,17 +401,20 @@ public static short[] reserveRowShorts(List rows, int id, int n, Bound * @param rows the outer list, one entry per row * @param id index of the row to reserve * @param n initial length of the new row - * @param bound {@link Bound#receiver(long)} carrying the caller's - * {@code max_dyn_array_count} (§6.2.1) bounding the row - * index, or {@link Bound#SCHEMA_BOUNDED} where the schema - * bounds the outer array. It does not bound {@code n}, which the - * caller has already bounded. + * @param bound {@link Bound#schema(long)} carrying the outer array's schema + * {@code count}, or {@link Bound#receiver(long)} carrying the + * caller's {@code max_dyn_array_count}, bounding the row + * index — see {@link #checkIndex}. It does not bound + * {@code n}, which the caller has already bounded. * @return the new row, now at index {@code id} - * @throws java.io.UncheckedIOException wrapping a {@code LIMIT_EXCEEDED} + * @throws java.io.UncheckedIOException wrapping an {@code INVALID_MSG} * {@link SofabException} when {@code id} - * is at or past the receiver cap, or an + * is at or past the schema {@code count}, + * a {@code LIMIT_EXCEEDED} one when it is + * at or past the receiver cap, or an * {@code ARGUMENT} one when {@code bound} - * is null + * is null or {@link Bound#SCHEMA_BOUNDED}; + * the list is left untouched in all three */ public static int[] reserveRowInts(List rows, int id, int n, Bound bound) { checkIndex(id, bound); @@ -412,17 +436,20 @@ public static int[] reserveRowInts(List rows, int id, int n, Bound bound) * @param rows the outer list, one entry per row * @param id index of the row to reserve * @param n initial length of the new row - * @param bound {@link Bound#receiver(long)} carrying the caller's - * {@code max_dyn_array_count} (§6.2.1) bounding the row - * index, or {@link Bound#SCHEMA_BOUNDED} where the schema - * bounds the outer array. It does not bound {@code n}, which the - * caller has already bounded. + * @param bound {@link Bound#schema(long)} carrying the outer array's schema + * {@code count}, or {@link Bound#receiver(long)} carrying the + * caller's {@code max_dyn_array_count}, bounding the row + * index — see {@link #checkIndex}. It does not bound + * {@code n}, which the caller has already bounded. * @return the new row, now at index {@code id} - * @throws java.io.UncheckedIOException wrapping a {@code LIMIT_EXCEEDED} + * @throws java.io.UncheckedIOException wrapping an {@code INVALID_MSG} * {@link SofabException} when {@code id} - * is at or past the receiver cap, or an + * is at or past the schema {@code count}, + * a {@code LIMIT_EXCEEDED} one when it is + * at or past the receiver cap, or an * {@code ARGUMENT} one when {@code bound} - * is null + * is null or {@link Bound#SCHEMA_BOUNDED}; + * the list is left untouched in all three */ public static long[] reserveRowLongs(List rows, int id, int n, Bound bound) { checkIndex(id, bound); @@ -444,17 +471,20 @@ public static long[] reserveRowLongs(List rows, int id, int n, Bound bou * @param rows the outer list, one entry per row * @param id index of the row to reserve * @param n initial length of the new row - * @param bound {@link Bound#receiver(long)} carrying the caller's - * {@code max_dyn_array_count} (§6.2.1) bounding the row - * index, or {@link Bound#SCHEMA_BOUNDED} where the schema - * bounds the outer array. It does not bound {@code n}, which the - * caller has already bounded. + * @param bound {@link Bound#schema(long)} carrying the outer array's schema + * {@code count}, or {@link Bound#receiver(long)} carrying the + * caller's {@code max_dyn_array_count}, bounding the row + * index — see {@link #checkIndex}. It does not bound + * {@code n}, which the caller has already bounded. * @return the new row, now at index {@code id} - * @throws java.io.UncheckedIOException wrapping a {@code LIMIT_EXCEEDED} + * @throws java.io.UncheckedIOException wrapping an {@code INVALID_MSG} * {@link SofabException} when {@code id} - * is at or past the receiver cap, or an + * is at or past the schema {@code count}, + * a {@code LIMIT_EXCEEDED} one when it is + * at or past the receiver cap, or an * {@code ARGUMENT} one when {@code bound} - * is null + * is null or {@link Bound#SCHEMA_BOUNDED}; + * the list is left untouched in all three */ public static float[] reserveRowFloats(List rows, int id, int n, Bound bound) { checkIndex(id, bound); @@ -476,17 +506,20 @@ public static float[] reserveRowFloats(List rows, int id, int n, Bound * @param rows the outer list, one entry per row * @param id index of the row to reserve * @param n initial length of the new row - * @param bound {@link Bound#receiver(long)} carrying the caller's - * {@code max_dyn_array_count} (§6.2.1) bounding the row - * index, or {@link Bound#SCHEMA_BOUNDED} where the schema - * bounds the outer array. It does not bound {@code n}, which the - * caller has already bounded. + * @param bound {@link Bound#schema(long)} carrying the outer array's schema + * {@code count}, or {@link Bound#receiver(long)} carrying the + * caller's {@code max_dyn_array_count}, bounding the row + * index — see {@link #checkIndex}. It does not bound + * {@code n}, which the caller has already bounded. * @return the new row, now at index {@code id} - * @throws java.io.UncheckedIOException wrapping a {@code LIMIT_EXCEEDED} + * @throws java.io.UncheckedIOException wrapping an {@code INVALID_MSG} * {@link SofabException} when {@code id} - * is at or past the receiver cap, or an + * is at or past the schema {@code count}, + * a {@code LIMIT_EXCEEDED} one when it is + * at or past the receiver cap, or an * {@code ARGUMENT} one when {@code bound} - * is null + * is null or {@link Bound#SCHEMA_BOUNDED}; + * the list is left untouched in all three */ public static double[] reserveRowDoubles(List rows, int id, int n, Bound bound) { checkIndex(id, bound); @@ -503,10 +536,24 @@ public static double[] reserveRowDoubles(List rows, int id, int n, Bou } /** - * The element-index rule of §6.2.1, written once for all nine reservations — - * and published for the one site that has none to ride. A bound must have been - * stated, and where it is a receiver cap the index is refused before anything is - * created and before the list is grown to hold it. + * The element-index rule, written once for all nine reservations — and + * published for the one site that has none to ride. A bound must have been + * stated, and the index is refused before anything is created and before the + * list is grown to hold it (CORELIB_PLAN §7.2 item 8), so a lower id delivered + * after a refused one still lands at its own index. + * + *

    Which verdict a breach earns is the bound's, and exactly one of the two is + * ever in force (§6.2.1, "never both"): + * + *

      + *
    • {@link Bound#schema(long)} — the schema {@code count}, a capacity: + * the list starts empty, the wire carries the length, and {@code id >= count} + * is {@link SofabError#INVALID_MSG} (MESSAGE_SPEC §7.1). Never + * {@code LIMIT_EXCEEDED}. + *
    • {@link Bound#receiver(long)} — the {@code max_dyn_array_count} for an + * array the schema leaves open, and {@code id >= cap} is + * {@link SofabError#LIMIT_EXCEEDED}. + *
    * *

    The site with no reservation is the length word of a {@code string} * or {@code blob} element: generated code bounds the element's index there, so @@ -517,30 +564,37 @@ public static double[] reserveRowDoubles(List rows, int id, int n, Bou * *

    The index is compared with {@code >=} rather than {@code >} because a * wrapper array's length is highest present id + 1 (MESSAGE_SPEC §5.1): an - * element at index {@code cap} makes a list of {@code cap + 1}, which is one - * more than the receiver said it would hold. Rejected, never clamped — placing - * the element at {@code cap - 1} instead would be data corruption. - * - *

    A missing bound is a defect in the call and answers - * {@link SofabError#ARGUMENT}, not {@link SofabError#LIMIT_EXCEEDED}, which - * would promise a limit to raise that was never configured (§6.3), and not - * silence, which would decode the index uncapped. + * element at index {@code n} makes a list of {@code n + 1}. Rejected, never + * clamped — placing the element at {@code n - 1} instead would be data + * corruption. + * + *

    A missing bound, or {@link Bound#SCHEMA_BOUNDED} — which carries no count to + * compare — is a defect in the call and answers + * {@link SofabError#ARGUMENT}, not a verdict on the bytes and not silence, which + * would grow the list uncompared (§6.3). + * + *

    The fast path is one comparison against a folded constant; the verdict is + * decided out of line, on the path that throws. + * + * @param id the element's wire id, which is its index + * @param bound {@link Bound#schema(long)} carrying the schema {@code count}, or + * {@link Bound#receiver(long)} carrying the caller's + * {@code max_dyn_array_count} (§6.2.1) + * @throws java.io.UncheckedIOException wrapping an {@code INVALID_MSG} + * {@link SofabException} when {@code id} is + * at or past the schema {@code count}, a + * {@code LIMIT_EXCEEDED} one when it is at + * or past the receiver cap, or an + * {@code ARGUMENT} one when {@code bound} + * is null or {@link Bound#SCHEMA_BOUNDED} */ public static void checkIndex(int id, Bound bound) { - if (Bound.required(bound, "max_dyn_array_count").exceededByIndex(id)) { - throw overIndexCap(id, bound); + Bound b = Bound.required(bound, "the array element index"); + if (id >= b.cap()) { + throw b.rejectIndex(id); } } - /** - * Build the {@link SofabError#LIMIT_EXCEEDED} rejection, out of line so the - * comparison that guards it stays two instructions on the decode path. - */ - private static java.io.UncheckedIOException overIndexCap(int id, Bound bound) { - return Sofab.limitExceeded( - "array element index " + id + " above configured limit " + bound.cap()); - } - /** * Empty a list in place, keeping its capacity, and materialize one only * when the field is null. diff --git a/src/main/java/org/sofabuffers/sofab/Sofab.java b/src/main/java/org/sofabuffers/sofab/Sofab.java index 6956fe6..2eab58c 100644 --- a/src/main/java/org/sofabuffers/sofab/Sofab.java +++ b/src/main/java/org/sofabuffers/sofab/Sofab.java @@ -154,7 +154,8 @@ public static UncheckedIOException limitExceeded(String detail) { * bytes and not in the deployment. * *

    Raised where a {@link Bound} the caller had to state is missing — a - * {@code null} where a receiver cap or {@link Bound#SCHEMA_BOUNDED} belonged. + * {@code null} where a bound belonged, or the numberless + * {@link Bound#SCHEMA_BOUNDED} handed to a call that bounds an array index. * §6.2.1 forbids reading an omitted argument as unlimited, so an * omission is reported rather than obeyed. * diff --git a/src/test/java/org/sofabuffers/sofab/ForgottenCapTest.java b/src/test/java/org/sofabuffers/sofab/ForgottenCapTest.java index 227a7fb..c4b8349 100644 --- a/src/test/java/org/sofabuffers/sofab/ForgottenCapTest.java +++ b/src/test/java/org/sofabuffers/sofab/ForgottenCapTest.java @@ -123,9 +123,11 @@ void noConstantOfThisLibraryIsANegativeSentinel() throws Exception { } /** - * The schema statement is an object with no number in it, and the only way to - * produce a bound carrying one is the receiver factory. So the two answers do - * not share a representation at all — not merely different values of one. + * The numberless schema statement is an object with no number in it, and the + * only ways to produce a bound carrying one are the two named factories, each + * of which fixes the verdict with the number. So a receiver cap and a schema + * bound do not share a representation at all — not merely different values of + * one. */ @Test void theSchemaStatementCarriesNoNumber() throws Exception { @@ -145,9 +147,10 @@ void theSchemaStatementCarriesNoNumber() throws Exception { if (!Modifier.isPublic(m.getModifiers()) || !Modifier.isStatic(m.getModifiers())) { continue; } - assertEquals("receiver", m.getName(), - "receiver(long) is the only public factory: every other one would be a " - + "second way to reach the comparison"); + assertTrue(m.getName().equals("receiver") || m.getName().equals("schema"), + "receiver(long) and schema(long) are the only public factories: any other " + + "would be a way to reach the comparison without naming its verdict, " + + "found " + m.getName()); } } @@ -172,6 +175,18 @@ void theValuesAForgottenCapArrivesAsAreRefused() throws Exception { + "InvalidArgument), not a limit to raise and not malformed bytes"); } assertNotNull(receiver.invoke(null, 1L), "1 is the smallest real cap"); + + // The schema factory refuses the same two values: 0 is an unassigned field + // and a negative the retired sentinel, and the schema validator admits + // neither as a count or maxlen. + Method schema = boundClass().getMethod("schema", long.class); + for (long forgotten : new long[] {0L, -1L, Long.MIN_VALUE}) { + InvocationTargetException e = assertThrows(InvocationTargetException.class, + () -> schema.invoke(null, forgotten), + "Bound.schema(" + forgotten + ") must not become a bound"); + assertInstanceOf(IllegalArgumentException.class, e.getCause()); + } + assertNotNull(schema.invoke(null, 1L), "1 is the smallest schema count"); } /** diff --git a/src/test/java/org/sofabuffers/sofab/ReceiverCapTest.java b/src/test/java/org/sofabuffers/sofab/ReceiverCapTest.java index e12aba7..106117f 100644 --- a/src/test/java/org/sofabuffers/sofab/ReceiverCapTest.java +++ b/src/test/java/org/sofabuffers/sofab/ReceiverCapTest.java @@ -319,12 +319,18 @@ void anOverCapIndexIsNotClampedIntoTheList() { assertEquals(1, rows.size(), "the refused row was neither appended nor moved down"); } - /** As for a payload, the schema-bounded sentinel compares nothing here. */ + /** + * {@link Bound#SCHEMA_BOUNDED} carries no count, so it cannot bound a row index: + * the reservation refuses it as a defect in the call rather than growing the + * list uncompared. The schema {@code count} travels as {@link Bound#schema(long)} + * (see {@link SchemaBoundTest}). + */ @Test - void aSchemaBoundedRowIndexIsTheCallersToCheck() { + void aNumberlessSchemaStatementCannotBoundARowIndex() { List rows = new ArrayList<>(); - Seq.reserveRowInts(rows, 40, 1, Bound.SCHEMA_BOUNDED); - assertEquals(41, rows.size()); + assertEquals(SofabError.ARGUMENT, categoryOf(assertThrows(UncheckedIOException.class, + () -> Seq.reserveRowInts(rows, 40, 1, Bound.SCHEMA_BOUNDED)))); + assertEquals(0, rows.size(), "refused, so nothing was reserved or grown"); } /** @@ -383,16 +389,18 @@ void aRefusedIndexLeavesTheContainerUnextended() { assertEquals(List.of("a", "b"), out, "a lower id delivered afterwards still lands"); } - /** As for a row, the schema-bounded statement compares nothing here. */ + /** As for a row, the numberless schema statement bounds no element index. */ @Test - void aSchemaBoundedElementIndexIsTheCallersToCheck() { + void aNumberlessSchemaStatementCannotBoundAnElementIndex() { List out = new ArrayList<>(); - Seq.placeElem(out, 40, "", "far", Bound.SCHEMA_BOUNDED); - assertEquals(41, out.size()); + assertEquals(SofabError.ARGUMENT, categoryOf(assertThrows(UncheckedIOException.class, + () -> Seq.placeElem(out, 0, "", "near", Bound.SCHEMA_BOUNDED)))); + assertEquals(0, out.size()); List framed = new ArrayList<>(); - Seq.reserveElem(framed, 40, Object::new, Bound.SCHEMA_BOUNDED); - assertEquals(41, framed.size()); + assertEquals(SofabError.ARGUMENT, categoryOf(assertThrows(UncheckedIOException.class, + () -> Seq.reserveElem(framed, 0, Object::new, Bound.SCHEMA_BOUNDED)))); + assertEquals(0, framed.size()); } /** @@ -406,7 +414,8 @@ void theLengthWordLatchTakesTheSameIndexComparison() { assertEquals(SofabError.LIMIT_EXCEEDED, categoryOf(assertThrows(UncheckedIOException.class, () -> Seq.checkIndex(4, Bound.receiver(4))))); Seq.checkIndex(3, Bound.receiver(4)); - Seq.checkIndex(40, Bound.SCHEMA_BOUNDED); + assertEquals(SofabError.ARGUMENT, categoryOf(assertThrows(UncheckedIOException.class, + () -> Seq.checkIndex(0, Bound.SCHEMA_BOUNDED)))); assertEquals(SofabError.ARGUMENT, categoryOf(assertThrows(UncheckedIOException.class, () -> Seq.checkIndex(0, null)))); } diff --git a/src/test/java/org/sofabuffers/sofab/SchemaBoundTest.java b/src/test/java/org/sofabuffers/sofab/SchemaBoundTest.java new file mode 100644 index 0000000..f8ca5d5 --- /dev/null +++ b/src/test/java/org/sofabuffers/sofab/SchemaBoundTest.java @@ -0,0 +1,204 @@ +/* + * SofaBuffers Java - the schema's own bound, compared by the corelib call it is + * handed to (MESSAGE_SPEC §7.1, CORELIB_PLAN §6.2.1, §7.2 item 8). + * + * SPDX-License-Identifier: MIT + */ + +package org.sofabuffers.sofab; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.UncheckedIOException; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + +/** + * {@link Bound#schema(long)}: a schema {@code count} handed to the reservation + * that grows the list, and compared there. + * + *

    A {@code count} is a capacity, not a length — the list starts empty and + * the wire carries the length — so the last index that fits is {@code count - 1} + * and {@code id >= count} is {@code INVALID_MSG}. The receiver cap is the other, + * exclusive answer (§6.2.1): a schema bound never reports {@code LIMIT_EXCEEDED}. + * And the index is compared before anything grows (§7.2 item 8), so a refused id + * leaves the list as it was and a lower id delivered afterwards still lands. + */ +class SchemaBoundTest { + + private static final int COUNT = 5; + private static final Bound SCHEMA = Bound.schema(COUNT); + + private static SofabError categoryOf(UncheckedIOException e) { + return assertInstanceOf(SofabException.class, e.getCause()).error(); + } + + private static SofabError refusal(Runnable call) { + return categoryOf(assertThrows(UncheckedIOException.class, call::run)); + } + + /** + * Every reservation that takes a {@link Bound}, as a call on one list: the + * leaf placement, the framed slot, the list row and the six primitive rows. + */ + private static List reservations() { + return List.of( + new Reservation("placeElem", (out, id) -> Seq.placeElem(strings(out), id, "", "v", SCHEMA)), + new Reservation("reserveElem", (out, id) -> Seq.reserveElem(objects(out), id, Object::new, SCHEMA)), + new Reservation("reserveRow", (out, id) -> Seq.reserveRow(lists(out), id, SCHEMA)), + new Reservation("reserveRowBytes", (out, id) -> Seq.reserveRowBytes(bytes(out), id, 1, SCHEMA)), + new Reservation("reserveRowShorts", (out, id) -> Seq.reserveRowShorts(shorts(out), id, 1, SCHEMA)), + new Reservation("reserveRowInts", (out, id) -> Seq.reserveRowInts(ints(out), id, 1, SCHEMA)), + new Reservation("reserveRowLongs", (out, id) -> Seq.reserveRowLongs(longs(out), id, 1, SCHEMA)), + new Reservation("reserveRowFloats", (out, id) -> Seq.reserveRowFloats(floats(out), id, 1, SCHEMA)), + new Reservation("reserveRowDoubles", (out, id) -> Seq.reserveRowDoubles(doubles(out), id, 1, SCHEMA))); + } + + /** At the bound: index {@code count - 1} is the last one that fits. */ + @Test + void theLastIndexTheCapacityHoldsLands() { + for (Reservation r : reservations()) { + List out = new ArrayList<>(); + r.call.accept(out, COUNT - 1); + assertEquals(COUNT, out.size(), r.name + ": grown to count, gaps filled"); + } + Seq.checkIndex(COUNT - 1, SCHEMA); + } + + /** + * Past the bound: index {@code count} is INVALID_MSG, and the list is not + * extended toward it — so a lower id delivered afterwards still lands at its + * own index rather than behind a run of defaults. + */ + @Test + void anIndexAtTheCountIsInvalidAndLeavesTheListUnextended() { + for (Reservation r : reservations()) { + List out = new ArrayList<>(); + r.call.accept(out, 1); + assertEquals(SofabError.INVALID_MSG, refusal(() -> r.call.accept(out, COUNT)), + r.name + ": id == count breaches the capacity"); + assertEquals(SofabError.INVALID_MSG, refusal(() -> r.call.accept(out, 1 << 20)), + r.name + ": far past it too"); + assertEquals(2, out.size(), r.name + ": the refused id neither grew nor shifted the list"); + r.call.accept(out, 0); + assertEquals(2, out.size(), r.name + ": a lower id delivered afterwards still lands"); + } + assertEquals(SofabError.INVALID_MSG, refusal(() -> Seq.checkIndex(COUNT, SCHEMA))); + } + + /** + * The breach is judged before the element is made: the factory here throws, so + * a check made after the growth would surface that instead of the refusal. + */ + @Test + void theIndexIsJudgedBeforeTheElementIsMade() { + List out = new ArrayList<>(); + assertEquals(SofabError.INVALID_MSG, refusal(() -> Seq.reserveElem(out, COUNT, () -> { + throw new AssertionError("the element was made for a refused index"); + }, SCHEMA))); + assertEquals(0, out.size()); + } + + /** + * §6.2.1: the schema bound and the receiver cap are exclusive, and so are their + * verdicts. The same index against the same number is INVALID_MSG under the + * schema and LIMIT_EXCEEDED under a cap — never the other way round, and a + * schema bound never reports LIMIT_EXCEEDED however far the index lies. + */ + @Test + void aSchemaBoundNeverReportsLimitExceeded() { + for (int id : new int[] {COUNT, COUNT + 1, 1 << 16, Integer.MAX_VALUE}) { + assertEquals(SofabError.INVALID_MSG, refusal(() -> Seq.checkIndex(id, SCHEMA))); + for (Reservation r : reservations()) { + assertNotEquals(SofabError.LIMIT_EXCEEDED, refusal(() -> r.call.accept(new ArrayList<>(), id)), + r.name + " at " + id); + } + } + assertEquals(SofabError.LIMIT_EXCEEDED, + refusal(() -> Seq.checkIndex(COUNT, Bound.receiver(COUNT))), + "the receiver cap keeps its own verdict"); + } + + /** + * A {@code maxlen} handed to {@link PayloadAcc} as a schema bound is compared + * at the announced length and is INVALID_MSG above it — before a byte is + * taken — and never LIMIT_EXCEEDED. + */ + @Test + void aSchemaMaxlenOnAPayloadIsInvalidAboveIt() { + Bound maxlen = Bound.schema(4); + byte[] p = "abcde".getBytes(java.nio.charset.StandardCharsets.US_ASCII); + PayloadAcc.checkStringLength(4, maxlen); + PayloadAcc.checkBlobLength(4, maxlen); + assertEquals(SofabError.INVALID_MSG, refusal(() -> PayloadAcc.checkStringLength(5, maxlen))); + assertEquals(SofabError.INVALID_MSG, refusal(() -> PayloadAcc.checkBlobLength(5, maxlen))); + + PayloadAcc acc = new PayloadAcc(); + assertEquals(SofabError.INVALID_MSG, refusal(() -> acc.string(5, 0, p, 0, 2, maxlen))); + // Nothing was taken: an in-bound payload through the same accumulator is whole. + assertNull(acc.blob(4, 0, p, 0, 2, maxlen)); + assertEquals("abcd", new String(acc.blob(4, 2, p, 2, 2, maxlen), + java.nio.charset.StandardCharsets.US_ASCII)); + } + + @Test + void itNamesItsRule() { + assertEquals("Bound.schema(5)", SCHEMA.toString()); + assertNotEquals(Bound.receiver(COUNT).toString(), SCHEMA.toString()); + } + + // --- fixtures ------------------------------------------------------------ + + /** One reservation under test, applied to an untyped list. */ + private record Reservation(String name, java.util.function.BiConsumer, Integer> call) { + } + + @SuppressWarnings("unchecked") + private static List strings(List out) { + return (List) (List) out; + } + + private static List objects(List out) { + return out; + } + + @SuppressWarnings("unchecked") + private static List> lists(List out) { + return (List>) (List) out; + } + + @SuppressWarnings("unchecked") + private static List bytes(List out) { + return (List) (List) out; + } + + @SuppressWarnings("unchecked") + private static List shorts(List out) { + return (List) (List) out; + } + + @SuppressWarnings("unchecked") + private static List ints(List out) { + return (List) (List) out; + } + + @SuppressWarnings("unchecked") + private static List longs(List out) { + return (List) (List) out; + } + + @SuppressWarnings("unchecked") + private static List floats(List out) { + return (List) (List) out; + } + + @SuppressWarnings("unchecked") + private static List doubles(List out) { + return (List) (List) out; + } +} diff --git a/src/test/java/org/sofabuffers/sofab/SeqTest.java b/src/test/java/org/sofabuffers/sofab/SeqTest.java index a7c3b35..9df52cc 100644 --- a/src/test/java/org/sofabuffers/sofab/SeqTest.java +++ b/src/test/java/org/sofabuffers/sofab/SeqTest.java @@ -33,6 +33,13 @@ */ class SeqTest { + /** + * The schema {@code count} every placement below is bounded by: above every + * index these tests place, so what they pin is placement, not the bound + * ({@link SchemaBoundTest} pins the bound itself). + */ + private static final Bound COUNT_8 = Bound.schema(8); + // --- growth: capacity edges --------------------------------------------- /** Below the length it already has, the array is handed straight back. */ @@ -155,7 +162,7 @@ void everyPrimitiveWidthGrowsAlike() { @Test void aWrapperRowGapFillsRatherThanShifts() { List> rows = new ArrayList<>(); - Seq.reserveRow(rows, 2, Bound.SCHEMA_BOUNDED); + Seq.reserveRow(rows, 2, COUNT_8); rows.get(2).add("third"); assertEquals(3, rows.size()); @@ -171,11 +178,11 @@ void aWrapperRowGapFillsRatherThanShifts() { @Test void aRepeatedWrapperRowIsEmptiedInPlace() { List> rows = new ArrayList<>(); - Seq.reserveRow(rows, 0, Bound.SCHEMA_BOUNDED); + Seq.reserveRow(rows, 0, COUNT_8); List first = rows.get(0); first.add("stale"); - Seq.reserveRow(rows, 0, Bound.SCHEMA_BOUNDED); + Seq.reserveRow(rows, 0, COUNT_8); assertSame(first, rows.get(0), "the row object is reused"); assertEquals(List.of(), rows.get(0), "its value is replaced, not merged into"); assertEquals(1, rows.size()); @@ -186,7 +193,7 @@ void aRepeatedWrapperRowIsEmptiedInPlace() { void aNullWrapperRowIsMaterialized() { List> rows = new ArrayList<>(); rows.add(null); - Seq.reserveRow(rows, 0, Bound.SCHEMA_BOUNDED); + Seq.reserveRow(rows, 0, COUNT_8); assertEquals(List.of(), rows.get(0)); } @@ -194,7 +201,7 @@ void aNullWrapperRowIsMaterialized() { @Test void aPrimitiveRowGapFillsWithTheSharedEmptyRow() { List rows = new ArrayList<>(); - int[] row = Seq.reserveRowInts(rows, 2, 3, Bound.SCHEMA_BOUNDED); + int[] row = Seq.reserveRowInts(rows, 2, 3, COUNT_8); assertEquals(3, rows.size()); assertSame(Seq.EMPTY_INTS, rows.get(0), "a gap costs no allocation"); @@ -207,9 +214,9 @@ void aPrimitiveRowGapFillsWithTheSharedEmptyRow() { @Test void aRepeatedPrimitiveRowIsReplaced() { List rows = new ArrayList<>(); - int[] first = Seq.reserveRowInts(rows, 0, 2, Bound.SCHEMA_BOUNDED); + int[] first = Seq.reserveRowInts(rows, 0, 2, COUNT_8); first[0] = 9; - int[] second = Seq.reserveRowInts(rows, 0, 2, Bound.SCHEMA_BOUNDED); + int[] second = Seq.reserveRowInts(rows, 0, 2, COUNT_8); assertNotSame(first, second); assertSame(second, rows.get(0)); @@ -224,42 +231,42 @@ void aRepeatedPrimitiveRowIsReplaced() { @Test void everyPrimitiveRowWidthPlacesAlike() { List bytes = new ArrayList<>(); - assertEquals(2, Seq.reserveRowBytes(bytes, 1, 2, Bound.SCHEMA_BOUNDED).length); + assertEquals(2, Seq.reserveRowBytes(bytes, 1, 2, COUNT_8).length); assertSame(Seq.EMPTY_BYTES, bytes.get(0)); - assertSame(Seq.reserveRowBytes(bytes, 1, 3, Bound.SCHEMA_BOUNDED), bytes.get(1)); + assertSame(Seq.reserveRowBytes(bytes, 1, 3, COUNT_8), bytes.get(1)); List shorts = new ArrayList<>(); - assertEquals(2, Seq.reserveRowShorts(shorts, 1, 2, Bound.SCHEMA_BOUNDED).length); + assertEquals(2, Seq.reserveRowShorts(shorts, 1, 2, COUNT_8).length); assertSame(Seq.EMPTY_SHORTS, shorts.get(0)); - assertSame(Seq.reserveRowShorts(shorts, 1, 3, Bound.SCHEMA_BOUNDED), shorts.get(1)); + assertSame(Seq.reserveRowShorts(shorts, 1, 3, COUNT_8), shorts.get(1)); List longs = new ArrayList<>(); - assertEquals(2, Seq.reserveRowLongs(longs, 1, 2, Bound.SCHEMA_BOUNDED).length); + assertEquals(2, Seq.reserveRowLongs(longs, 1, 2, COUNT_8).length); assertSame(Seq.EMPTY_LONGS, longs.get(0)); - assertSame(Seq.reserveRowLongs(longs, 1, 3, Bound.SCHEMA_BOUNDED), longs.get(1)); + assertSame(Seq.reserveRowLongs(longs, 1, 3, COUNT_8), longs.get(1)); List floats = new ArrayList<>(); - assertEquals(2, Seq.reserveRowFloats(floats, 1, 2, Bound.SCHEMA_BOUNDED).length); + assertEquals(2, Seq.reserveRowFloats(floats, 1, 2, COUNT_8).length); assertSame(Seq.EMPTY_FLOATS, floats.get(0)); - assertSame(Seq.reserveRowFloats(floats, 1, 3, Bound.SCHEMA_BOUNDED), floats.get(1)); + assertSame(Seq.reserveRowFloats(floats, 1, 3, COUNT_8), floats.get(1)); List doubles = new ArrayList<>(); - assertEquals(2, Seq.reserveRowDoubles(doubles, 1, 2, Bound.SCHEMA_BOUNDED).length); + assertEquals(2, Seq.reserveRowDoubles(doubles, 1, 2, COUNT_8).length); assertSame(Seq.EMPTY_DOUBLES, doubles.get(0)); - assertSame(Seq.reserveRowDoubles(doubles, 1, 3, Bound.SCHEMA_BOUNDED), doubles.get(1)); + assertSame(Seq.reserveRowDoubles(doubles, 1, 3, COUNT_8), doubles.get(1)); } /** A row reserved at the very next index appends rather than growing a gap. */ @Test void aRowAtTheNextIndexAppends() { List rows = new ArrayList<>(); - Seq.reserveRowInts(rows, 0, 1, Bound.SCHEMA_BOUNDED); - Seq.reserveRowInts(rows, 1, 1, Bound.SCHEMA_BOUNDED); + Seq.reserveRowInts(rows, 0, 1, COUNT_8); + Seq.reserveRowInts(rows, 1, 1, COUNT_8); assertEquals(2, rows.size()); List> wrappers = new ArrayList<>(); - Seq.reserveRow(wrappers, 0, Bound.SCHEMA_BOUNDED); - Seq.reserveRow(wrappers, 1, Bound.SCHEMA_BOUNDED); + Seq.reserveRow(wrappers, 0, COUNT_8); + Seq.reserveRow(wrappers, 1, COUNT_8); assertEquals(2, wrappers.size()); } @@ -274,8 +281,8 @@ void aRowAtTheNextIndexAppends() { @Test void aLeafElementGapFillsRatherThanShifts() { List out = new ArrayList<>(); - Seq.placeElem(out, 0, "", "first", Bound.SCHEMA_BOUNDED); - Seq.placeElem(out, 2, "", "third", Bound.SCHEMA_BOUNDED); + Seq.placeElem(out, 0, "", "first", COUNT_8); + Seq.placeElem(out, 2, "", "third", COUNT_8); assertEquals(List.of("first", "", "third"), out); } @@ -287,7 +294,7 @@ void aLeafElementGapFillsRatherThanShifts() { @Test void aLeafElementAloneAtAHighIdSetsTheLength() { List out = new ArrayList<>(); - Seq.placeElem(out, 3, "", "last", Bound.SCHEMA_BOUNDED); + Seq.placeElem(out, 3, "", "last", COUNT_8); assertEquals(4, out.size()); assertEquals(List.of("", "", "", "last"), out); @@ -297,8 +304,8 @@ void aLeafElementAloneAtAHighIdSetsTheLength() { @Test void aRepeatedLeafElementIdReplaces() { List out = new ArrayList<>(); - Seq.placeElem(out, 1, "", "stale", Bound.SCHEMA_BOUNDED); - Seq.placeElem(out, 1, "", "fresh", Bound.SCHEMA_BOUNDED); + Seq.placeElem(out, 1, "", "stale", COUNT_8); + Seq.placeElem(out, 1, "", "fresh", COUNT_8); assertEquals(List.of("", "fresh"), out); } @@ -307,8 +314,8 @@ void aRepeatedLeafElementIdReplaces() { @Test void aLeafElementAtTheNextIndexAppends() { List out = new ArrayList<>(); - Seq.placeElem(out, 0, "", "a", Bound.SCHEMA_BOUNDED); - Seq.placeElem(out, 1, "", "b", Bound.SCHEMA_BOUNDED); + Seq.placeElem(out, 0, "", "a", COUNT_8); + Seq.placeElem(out, 1, "", "b", COUNT_8); assertEquals(List.of("a", "b"), out); } @@ -321,7 +328,7 @@ void aLeafElementAtTheNextIndexAppends() { @Test void aLeafGapCostsNoAllocation() { List out = new ArrayList<>(); - Seq.placeElem(out, 2, Seq.EMPTY_BYTES, new byte[] { 7 }, Bound.SCHEMA_BOUNDED); + Seq.placeElem(out, 2, Seq.EMPTY_BYTES, new byte[] { 7 }, COUNT_8); assertEquals(3, out.size()); assertSame(Seq.EMPTY_BYTES, out.get(0)); @@ -338,8 +345,8 @@ void aLeafGapCostsNoAllocation() { void oneBodyPlacesEveryLeafElementType() { List strings = new ArrayList<>(); List blobs = new ArrayList<>(); - Seq.placeElem(strings, 1, "", "s", Bound.SCHEMA_BOUNDED); - Seq.placeElem(blobs, 1, Seq.EMPTY_BYTES, new byte[] { 1 }, Bound.SCHEMA_BOUNDED); + Seq.placeElem(strings, 1, "", "s", COUNT_8); + Seq.placeElem(blobs, 1, Seq.EMPTY_BYTES, new byte[] { 1 }, COUNT_8); assertEquals(List.of("", "s"), strings); assertEquals(2, blobs.size()); @@ -357,7 +364,7 @@ void oneBodyPlacesEveryLeafElementType() { @Test void everyFramedSlotGetsItsOwnElement() { List out = new ArrayList<>(); - Seq.reserveElem(out, 2, Elem::new, Bound.SCHEMA_BOUNDED); + Seq.reserveElem(out, 2, Elem::new, COUNT_8); assertEquals(3, out.size()); assertNotSame(out.get(0), out.get(1)); @@ -375,11 +382,11 @@ void everyFramedSlotGetsItsOwnElement() { @Test void aRepeatedFramedElementIdMergesIntoTheSameObject() { List out = new ArrayList<>(); - Seq.reserveElem(out, 0, Elem::new, Bound.SCHEMA_BOUNDED); + Seq.reserveElem(out, 0, Elem::new, COUNT_8); Elem first = out.get(0); first.a = 3; - Seq.reserveElem(out, 0, Elem::new, Bound.SCHEMA_BOUNDED); + Seq.reserveElem(out, 0, Elem::new, COUNT_8); assertSame(first, out.get(0), "the element is merged into, not started again"); assertEquals(3, out.get(0).a); assertEquals(1, out.size()); @@ -393,13 +400,13 @@ void aFramedReservationBelowTheHighWaterMarkMakesNoElement() { Seq.reserveElem(out, 2, () -> { made[0]++; return new Elem(); - }, Bound.SCHEMA_BOUNDED); + }, COUNT_8); assertEquals(3, made[0], "the slot and the two gaps below it"); Seq.reserveElem(out, 0, () -> { made[0]++; return new Elem(); - }, Bound.SCHEMA_BOUNDED); + }, COUNT_8); assertEquals(3, made[0], "id 0 already had a slot"); assertEquals(3, out.size()); } @@ -412,7 +419,7 @@ void aFramedReservationBelowTheHighWaterMarkMakesNoElement() { @Test void aFramedGapIsADefaultElementAndNotNull() { List out = new ArrayList<>(); - Seq.reserveElem(out, 1, Elem::new, Bound.SCHEMA_BOUNDED); + Seq.reserveElem(out, 1, Elem::new, COUNT_8); assertNotNull(out.get(0)); assertEquals(0, out.get(0).a); diff --git a/src/test/java/org/sofabuffers/sofab/SequenceGrowthTest.java b/src/test/java/org/sofabuffers/sofab/SequenceGrowthTest.java index aeace78..d5131b6 100644 --- a/src/test/java/org/sofabuffers/sofab/SequenceGrowthTest.java +++ b/src/test/java/org/sofabuffers/sofab/SequenceGrowthTest.java @@ -46,14 +46,15 @@ * asserts {@code expect}: container length and outcome only, no allocator * instrumentation, which is what makes the cases portable across the family. * - *

    What this port owns. The struct cases run through {@link Seq#reserveRow}, - * the library's own wrapper-array placement: it compares the element index against - * the {@link Bound} it is handed (§6.2.1), fills a gap with the empty row rather than - * shifting later rows down, and replaces rather than merges. A struct element here is - * a framed sub-sequence carrying one unsigned field, which is exactly a row holding - * one value. The string cases have no such helper — a {@code List} destination - * is placed by generated code — so that path uses the library's cap comparison through - * {@link Bound} and states the gap fill itself, standing in for the generated layer. + *

    What this port owns. Both element kinds run through the library's own + * wrapper-array placement, exactly as generated code calls it, so the cases exercise + * the real helpers rather than a copy of them. A string element is bounded at its + * length word by {@link Seq#checkIndex} and placed, once its payload is whole, by + * {@link Seq#placeElem}; a struct element — a framed sub-sequence carrying one + * unsigned field — gets its slot from {@link Seq#reserveElem}. Each compares the + * element index against the {@link Bound} it is handed (§6.2.1) before it grows the + * list, and fills a gap with the element default rather than shifting later + * elements down. */ class SequenceGrowthTest { @@ -162,10 +163,10 @@ private static byte[] build(JsonObject c) throws IOException { // --- the destination, standing in for the generated layer --------------------- /** - * The wrapper-array destination. The struct path goes through - * {@link Seq#reserveRow}, which is the library's placement and its cap comparison; - * the string path states the same contract for a {@code List}, which has - * no helper here. + * The wrapper-array destination, standing in for a generated message: the struct + * path reserves its slot through {@link Seq#reserveElem}, the string path bounds + * the index through {@link Seq#checkIndex} at the first piece and places the + * value through {@link Seq#placeElem} — the calls generated code makes. * *

    The order matters and is what the growth/reject case is about: §6.2.1 bounds * the index before the container it indexes into is extended, so a @@ -175,7 +176,7 @@ private static final class GrowthDest implements Visitor { private final boolean structElements; private final Bound bound = Bound.receiver(CAP); private final List strings = new ArrayList<>(); - private final List> rows = new ArrayList<>(); + private final List> structs = new ArrayList<>(); private int depth; private int element = -1; private byte[] payload = Seq.EMPTY_BYTES; @@ -194,16 +195,21 @@ private static final class GrowthDest implements Visitor { * it indexes into is extended" forbids. */ int length() { - return structElements ? rows.size() : strings.size(); + return structElements ? structs.size() : strings.size(); } String stringAt(int i) { return i < strings.size() ? strings.get(i) : ""; } + /** + * The element's one field, or its default. A re-opened element merges + * into the slot {@link Seq#reserveElem} kept, so the last value written to + * the field is its value (MESSAGE_SPEC §7.4). + */ long numberAt(int i) { - List row = i < rows.size() ? rows.get(i) : null; - return row == null || row.isEmpty() ? 0L : row.get(0); + List fields = i < structs.size() ? structs.get(i) : null; + return fields == null || fields.isEmpty() ? 0L : fields.get(fields.size() - 1); } @Override @@ -211,9 +217,10 @@ public void sequenceBegin(int id) { depth++; // depth 1 is the wrapper itself; depth 2 is a struct element. if (depth == 2 && structElements) { - // The library's own placement: bounds the index against the cap, - // gap-fills with the empty row, and never shifts later rows down. - Seq.reserveRow(rows, id, bound); + // The library's own framed-element reservation: bounds the index + // against the cap, gap-fills with fresh elements, and never shifts + // later elements down. + Seq.reserveElem(structs, id, ArrayList::new, bound); element = id; } } @@ -229,7 +236,7 @@ public void sequenceEnd() { @Override public void unsigned(int id, long value) { if (depth == 2 && structElements && element >= 0 && id == 0) { - rows.get(element).add(value); + structs.get(element).add(value); } } @@ -240,23 +247,17 @@ public void string(int id, int total, int offset, byte[] data, int chunkOffset, return; } // The index is bounded at the FIRST piece, before any payload is kept: a - // rejection must not depend on the payload arriving whole. + // rejection must not depend on the payload arriving whole. Generated code + // makes this same call from fixlenBegin, at the length word. if (offset == 0) { - if (bound.exceededByIndex(id)) { - throw Sofab.limitExceeded( - "array element index " + id + " above configured limit " + CAP); - } - // MESSAGE_SPEC §5.1: every destination slot is initialised to its - // ELEMENT DEFAULT before the array is applied — "" for a string, not - // null. Only a gap case ever looks at a slot nothing was written to. - while (strings.size() <= id) { - strings.add(""); - } + Seq.checkIndex(id, bound); payload = new byte[total]; } System.arraycopy(data, chunkOffset, payload, offset, chunkLength); if (offset + chunkLength == total) { - strings.set(id, new String(payload, StandardCharsets.UTF_8)); + // MESSAGE_SPEC §5.1: a gap below id holds the ELEMENT DEFAULT — "" + // for a string, not null — which placeElem fills in. + Seq.placeElem(strings, id, "", new String(payload, StandardCharsets.UTF_8), bound); } } } From 9b2964c89915e211a49002c3e119f43f0a9abe05 Mon Sep 17 00:00:00 2001 From: Andreas Steinbart Date: Mon, 21 Sep 2026 23:34:43 +0000 Subject: [PATCH 3/3] perf(bound): make Bound a record so a static final bound folds into its compare (generator#587) HotSpot trusts the final fields of a record as constants and does not trust an ordinary class's, so a static final Bound.schema(n) now compiles to a compare against an immediate - the same code the literal guard generated code used to emit in front of the call. Measured on the generator's java bench row (vehicle_telemetry decode, Callgrind subtract): 31852 -> 31745 Ir/op against a 31685 baseline with the literal guard. The rule travels as a public Bound.Rule (SCHEMA, RECEIVER, CALLER_CHECKED). The canonical constructor a record exposes validates exactly as schema(n) and receiver(n) do: a numbered rule needs at least 1, and only CALLER_CHECKED (the numberless SCHEMA_BOUNDED) carries -1. Seq.checkIndex keeps one compare on the fast path and decides the verdict out of line. --- .../java/org/sofabuffers/sofab/Bound.java | 154 ++++++++++-------- src/main/java/org/sofabuffers/sofab/Seq.java | 25 +-- .../sofabuffers/sofab/ForgottenCapTest.java | 23 ++- .../sofabuffers/sofab/HeaderLimitsTest.java | 2 +- .../sofabuffers/sofab/ReceiverCapTest.java | 2 +- 5 files changed, 115 insertions(+), 91 deletions(-) diff --git a/src/main/java/org/sofabuffers/sofab/Bound.java b/src/main/java/org/sofabuffers/sofab/Bound.java index 06ffb01..eabbc7f 100644 --- a/src/main/java/org/sofabuffers/sofab/Bound.java +++ b/src/main/java/org/sofabuffers/sofab/Bound.java @@ -49,16 +49,18 @@ * {@code long} parameter, with a negative sentinel for "the schema bounds this" — * so a caller who had forgotten to state a cap and a caller asserting the * schema's rule handed over the identical bit pattern, and the forgotten one decoded - * uncapped and unreported. Here the verdict travels with the number, and the only - * ways to make a bound carrying a number are the two named factories. + * uncapped and unreported. Here the {@link Rule} travels with the number, and a + * bound carrying a number is made by naming its rule: {@link #schema(long)}, + * {@link #receiver(long)}, or the canonical constructor, which validates exactly as + * those two do. * *

    Both "forgot" values are diagnosed, not obeyed. Java writes an * unassigned {@code long} field as {@code 0} and the retired sentinel was - * {@code -1}; both factories refuse both with {@link SofabError#ARGUMENT}, and a - * {@code null} reference reaching one of the calls is refused the same way rather - * than read as no cap. §6.2.1 admits "no unset state and no unlimited - * mode", and a codec "MUST NOT read an omitted argument as - * unlimited". + * {@code -1}; every way of making a bound refuses both with + * {@link SofabError#ARGUMENT}, and a {@code null} reference reaching one of the + * calls is refused the same way rather than read as no cap. §6.2.1 admits + * "no unset state and no unlimited mode", and a codec "MUST NOT read an + * omitted argument as unlimited". * *

    This library still holds no limit. A {@code Bound} is built by the * caller out of the caller's number, used for one comparison and not retained; @@ -74,42 +76,50 @@ * *

    {@code
      * private static final Bound CAP_DYN_ARRAY_COUNT = Bound.receiver(MAX_DYN_ARRAY_COUNT);
    - * private static final Bound TAGS_COUNT = Bound.schema(8);
    + * private static final Bound SCHEMA_COUNT_8 = Bound.schema(8);
      *
      * // schema `count: 8` -- compared inside, INVALID_MSG at index 8 and above
    - * Seq.placeElem(m.tags, id, "", s, TAGS_COUNT);
    + * Seq.placeElem(m.tags, id, "", s, SCHEMA_COUNT_8);
      * // schema declares no count -- compared inside, LIMIT_EXCEEDED at the cap
      * Seq.placeElem(m.notes, id, "", s, CAP_DYN_ARRAY_COUNT);
      * }
    * - *

    Nothing is allocated per call or per message on that path, and every constant - * is a {@code static final} object with {@code final} fields, which the JIT folds - * into the comparison it guards. + *

    Why a record. HotSpot treats the {@code final} fields of a record as + * true constants, which it does not do for an ordinary class. A + * {@code static final Bound} is therefore folded into the comparison it guards — + * {@code id >= 8} compiles to a compare against an immediate, exactly the guard + * generated code used to emit in front of the call — where a class's field would be + * loaded on every call. Measured on the generator's {@code java} bench row + * (vehicle_telemetry, decode): about 100 Ir/op, a third of a percent. Nothing is + * allocated per call or per message on that path. * *

    Instances are immutable and shareable. + * + * @param max the stated number — a {@code count}, {@code maxlen} or cap, at least + * {@code 1} — or {@code -1} for {@link #SCHEMA_BOUNDED}, whose rule + * carries none + * @param rule which rule the number states, and so which verdict a breach earns */ -public final class Bound { - - /** {@link #SCHEMA_BOUNDED}: a statement with no number. */ - private static final byte STATED = 0; - /** {@link #schema(long)}: the schema's bound, INVALID_MSG past it. */ - private static final byte SCHEMA = 1; - /** {@link #receiver(long)}: the deployment's cap, LIMIT_EXCEEDED past it. */ - private static final byte RECEIVER = 2; +public record Bound(long max, Rule rule) { - /** - * The number, or {@code -1} for {@link #SCHEMA_BOUNDED}. Only the two factories - * produce a non-negative value, and both refuse everything below {@code 1}, so a - * non-negative {@code max} here is always a number a caller deliberately stated. - * - *

    The {@code -1} is also what keeps the index comparison a single compare: - * every index is {@code >= -1}, so {@link #SCHEMA_BOUNDED} always reaches the - * out-of-line rejection, which refuses it as {@link SofabError#ARGUMENT}. - */ - private final long max; - - /** Which rule {@link #max} states: {@link #STATED}, {@link #SCHEMA} or {@link #RECEIVER}. */ - private final byte kind; + /** Which of §6.2.1's answers a {@link Bound} states, and so its verdict. */ + public enum Rule { + /** + * The schema's own {@code count} or {@code maxlen}, compared by the call: + * {@link SofabError#INVALID_MSG} past it. See {@link Bound#schema(long)}. + */ + SCHEMA, + /** + * The deployment's receiver cap, compared by the call: + * {@link SofabError#LIMIT_EXCEEDED} past it. See {@link Bound#receiver(long)}. + */ + RECEIVER, + /** + * The schema's {@code maxlen}, already enforced by the caller at the same + * header, so no number travels. See {@link Bound#SCHEMA_BOUNDED}. + */ + CALLER_CHECKED + } /** * The schema bounds this {@code string} or {@code blob} and the caller has @@ -126,13 +136,37 @@ public final class Bound { *

    It bounds no array index. An index has a reservation to ride, and * the reservation compares the schema {@code count} itself when handed * {@link #schema(long)}; every {@link Seq} call refuses this value as - * {@link SofabError#ARGUMENT} rather than growing a list uncompared. + * {@link SofabError#ARGUMENT} rather than growing a list uncompared. Its + * {@code -1} is what makes that refusal free: every index is {@code >= -1}, so + * the one comparison {@link Seq#checkIndex} makes always sends it to the + * out-of-line path. */ - public static final Bound SCHEMA_BOUNDED = new Bound(-1L, STATED); + public static final Bound SCHEMA_BOUNDED = new Bound(-1L, Rule.CALLER_CHECKED); - private Bound(long max, byte kind) { - this.max = max; - this.kind = kind; + /** + * Validates a bound however it is made: the rule must be stated, a stated + * number is at least {@code 1}, and only {@link Rule#CALLER_CHECKED} carries + * none ({@code -1}). + * + * @throws IllegalArgumentException for any other combination; it refines + * {@link SofabError#ARGUMENT} (§6.3) + */ + public Bound { + if (rule == null) { + throw new IllegalArgumentException( + "sofab: " + SofabError.ARGUMENT + " (a bound states its rule)"); + } + if (rule == Rule.CALLER_CHECKED ? max != -1L : max < 1L) { + throw new IllegalArgumentException( + "sofab: " + SofabError.ARGUMENT + " (" + rule + " bound " + max + + " is not a limit: " + (rule == Rule.CALLER_CHECKED + ? "the caller-checked schema statement carries no number" + : "a count, maxlen or cap is at least 1, and " + + (max == 0L ? "0 is an unassigned field, not a policy" + : "a negative is not \"the schema bounds " + + "this\" -- pass Bound.schema(n) for that")) + + ")"); + } } /** @@ -161,12 +195,7 @@ private Bound(long max, byte kind) { * bound */ public static Bound schema(long n) { - if (n < 1L) { - throw new IllegalArgumentException( - "sofab: " + SofabError.ARGUMENT + " (schema bound " + n - + " is not a count or maxlen: a schema admits 1 and above)"); - } - return new Bound(n, SCHEMA); + return new Bound(n, Rule.SCHEMA); } /** @@ -203,16 +232,7 @@ public static Bound schema(long n) { * on the decode path */ public static Bound receiver(long max) { - if (max < 1L) { - throw new IllegalArgumentException( - "sofab: " + SofabError.ARGUMENT + " (receiver cap " + max - + " is not a limit: a cap is at least 1, and " - + (max == 0L ? "0 is an unassigned field, not a policy" - : "a negative is not \"the schema bounds this\" — " - + "pass Bound.schema(n) for that") - + ")"); - } - return new Bound(max, RECEIVER); + return new Bound(max, Rule.RECEIVER); } /** @@ -224,7 +244,7 @@ public static Bound receiver(long max) { * @return true if a number is stated and {@code length} is above it */ boolean exceededBy(long length) { - return kind != STATED && length > max; + return rule != Rule.CALLER_CHECKED && length > max; } /** @@ -237,7 +257,7 @@ boolean exceededBy(long length) { * @return the exception to throw */ UncheckedIOException rejectLength(String noun, long length) { - if (kind == SCHEMA) { + if (rule == Rule.SCHEMA) { return Sofab.invalid(noun + " " + length + " above schema maxlen " + max); } return Sofab.limitExceeded(noun + " " + length + " above configured limit " + max); @@ -249,22 +269,22 @@ UncheckedIOException rejectLength(String noun, long length) { * {@link #SCHEMA_BOUNDED}. * *

      - *
    • {@link #schema(long)}: INVALID_MSG. An index at or past the schema + *
    • {@link Rule#SCHEMA}: INVALID_MSG. An index at or past the schema * {@code count} makes an array longer than the schema's capacity * (MESSAGE_SPEC §7.1). - *
    • {@link #receiver(long)}: LIMIT_EXCEEDED. An element at index {@code cap} + *
    • {@link Rule#RECEIVER}: LIMIT_EXCEEDED. An element at index {@code cap} * makes a list of {@code cap + 1}, one more than the receiver said it would * hold (§6.2.1). Rejected, never clamped — placing it at {@code cap - 1} * instead would be data corruption. - *
    • {@link #SCHEMA_BOUNDED}: ARGUMENT. It carries no count, so the call has - * nothing to compare; silence would grow the list uncompared. + *
    • {@link Rule#CALLER_CHECKED}: ARGUMENT. It carries no count, so the call + * has nothing to compare; silence would grow the list uncompared. *
    * * @param index the wire's element index * @return the exception to throw */ UncheckedIOException rejectIndex(long index) { - switch (kind) { + switch (rule) { case SCHEMA: return Sofab.invalid("array element index " + index + " above schema capacity " + max); case RECEIVER: @@ -276,16 +296,6 @@ UncheckedIOException rejectIndex(long index) { } } - /** - * The stated number — what {@link Seq#checkIndex} compares an index against, - * and what a diagnostic names. Negative for {@link #SCHEMA_BOUNDED}. - * - * @return the number - */ - long cap() { - return max; - } - /** * The bound that must have been stated, refusing a {@code null} rather than * reading it as no cap (§6.2.1: a codec "MUST NOT read an omitted @@ -312,7 +322,7 @@ static Bound required(Bound bound, String which) { */ @Override public String toString() { - switch (kind) { + switch (rule) { case SCHEMA: return "Bound.schema(" + max + ")"; case RECEIVER: diff --git a/src/main/java/org/sofabuffers/sofab/Seq.java b/src/main/java/org/sofabuffers/sofab/Seq.java index b2d74e4..f1afb73 100644 --- a/src/main/java/org/sofabuffers/sofab/Seq.java +++ b/src/main/java/org/sofabuffers/sofab/Seq.java @@ -65,13 +65,14 @@ * one implementation: a caller that passes the bound does not also guard in * front of the call. * - *

    {@link #checkIndex} is that comparison on its own, published for the one site - * that has no reservation to ride: a generated {@code fixlenBegin} arm bounds a - * {@code string} or {@code blob} element's index at the length word, so that - * a message ending right there is still refused rather than reported - * {@code INCOMPLETE} (MESSAGE_SPEC §5.2). The placement that follows re-runs it, - * which costs one comparison against a folded constant and spares the two sites - * from having to agree by inspection. + *

    {@link #checkIndex} is that comparison on its own, published for the sites + * that must judge the index before the reservation runs: a generated + * {@code fixlenBegin} arm bounds a {@code string} or {@code blob} element's index at + * the length word, so that a message ending right there is still refused + * rather than reported {@code INCOMPLETE} (MESSAGE_SPEC §5.2), and a native matrix + * row's header judges the row's index before the row's own element count. The + * reservation that follows re-runs it, which costs one comparison against a folded + * constant and spares the two sites from having to agree by inspection. * *

    Nothing here holds a limit. The number is the caller's, used for that * one comparison and not retained; there is no default, no fallback and no @@ -80,8 +81,9 @@ * same way. * *

    The two answers are separate values, and an unstated one is refused. - * {@link Bound#schema(long)} and {@link Bound#receiver(long)} are the only ways to - * reach the comparison with a number, and each carries its own verdict, so a + * A {@link Bound} reaches the comparison with a number only by naming its rule — + * {@link Bound#schema(long)} or {@link Bound#receiver(long)} — and each carries its + * own verdict, so a * caller who never configured a cap cannot arrive here spelling what a * schema-bounded array spells. A {@code null}, and {@link Bound#SCHEMA_BOUNDED} * (which carries no count), are {@link Sofab#argument} rather than an uncompared @@ -589,9 +591,8 @@ public static double[] reserveRowDoubles(List rows, int id, int n, Bou * is null or {@link Bound#SCHEMA_BOUNDED} */ public static void checkIndex(int id, Bound bound) { - Bound b = Bound.required(bound, "the array element index"); - if (id >= b.cap()) { - throw b.rejectIndex(id); + if (bound == null || id >= bound.max()) { + throw Bound.required(bound, "the array element index").rejectIndex(id); } } diff --git a/src/test/java/org/sofabuffers/sofab/ForgottenCapTest.java b/src/test/java/org/sofabuffers/sofab/ForgottenCapTest.java index c4b8349..fde2f6a 100644 --- a/src/test/java/org/sofabuffers/sofab/ForgottenCapTest.java +++ b/src/test/java/org/sofabuffers/sofab/ForgottenCapTest.java @@ -123,11 +123,10 @@ void noConstantOfThisLibraryIsANegativeSentinel() throws Exception { } /** - * The numberless schema statement is an object with no number in it, and the - * only ways to produce a bound carrying one are the two named factories, each - * of which fixes the verdict with the number. So a receiver cap and a schema - * bound do not share a representation at all — not merely different values of - * one. + * The numberless schema statement is an object with no number in it, and every + * bound that carries one names its {@link Bound.Rule} beside it — through the + * two named factories, or the validated canonical constructor. So a receiver cap + * and a schema bound differ in their rule, not merely in their value. */ @Test void theSchemaStatementCarriesNoNumber() throws Exception { @@ -187,6 +186,20 @@ void theValuesAForgottenCapArrivesAsAreRefused() throws Exception { assertInstanceOf(IllegalArgumentException.class, e.getCause()); } assertNotNull(schema.invoke(null, 1L), "1 is the smallest schema count"); + + // The canonical constructor a record exposes is not a way around either + // factory: it validates exactly as they do, and the numberless statement + // cannot be given a number (nor a numbered rule go without one). + for (Bound.Rule rule : new Bound.Rule[] {Bound.Rule.SCHEMA, Bound.Rule.RECEIVER}) { + for (long forgotten : new long[] {0L, -1L, Long.MIN_VALUE}) { + assertThrows(IllegalArgumentException.class, () -> new Bound(forgotten, rule), + "new Bound(" + forgotten + ", " + rule + ") must not become a bound"); + } + } + assertThrows(IllegalArgumentException.class, () -> new Bound(5L, Bound.Rule.CALLER_CHECKED)); + assertThrows(IllegalArgumentException.class, () -> new Bound(5L, null)); + assertEquals(Bound.schema(5), new Bound(5L, Bound.Rule.SCHEMA), "the same value either way"); + assertEquals(Bound.SCHEMA_BOUNDED, new Bound(-1L, Bound.Rule.CALLER_CHECKED)); } /** diff --git a/src/test/java/org/sofabuffers/sofab/HeaderLimitsTest.java b/src/test/java/org/sofabuffers/sofab/HeaderLimitsTest.java index 80b901b..449daac 100644 --- a/src/test/java/org/sofabuffers/sofab/HeaderLimitsTest.java +++ b/src/test/java/org/sofabuffers/sofab/HeaderLimitsTest.java @@ -513,7 +513,7 @@ private void boundCount(int count) { } if (boundFor(ceiling.arrayCap()).exceededBy(count)) { throw Sofab.limitExceeded("element count " + count - + " above configured limit " + ceiling.arrayCap().cap()); + + " above configured limit " + ceiling.arrayCap().max()); } } diff --git a/src/test/java/org/sofabuffers/sofab/ReceiverCapTest.java b/src/test/java/org/sofabuffers/sofab/ReceiverCapTest.java index 106117f..4302a6d 100644 --- a/src/test/java/org/sofabuffers/sofab/ReceiverCapTest.java +++ b/src/test/java/org/sofabuffers/sofab/ReceiverCapTest.java @@ -589,7 +589,7 @@ void thisLibraryHoldsNoReceiverLimit() { // Bound this library defines states which RULE governs a field and carries // no number at all, so it cannot be read as a limit. assertEquals("Bound.SCHEMA_BOUNDED", Bound.SCHEMA_BOUNDED.toString()); - assertTrue(Bound.SCHEMA_BOUNDED.cap() < 0, "it states a rule, not a limit value"); + assertTrue(Bound.SCHEMA_BOUNDED.max() < 0, "it states a rule, not a limit value"); assertEquals(Integer.MAX_VALUE, Sofab.ID_MAX); assertEquals(Integer.MAX_VALUE, Sofab.ARRAY_MAX); }