diff --git a/README.md b/README.md
index 3ffe796..1b5622e 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). 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 |
@@ -272,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
@@ -293,7 +296,12 @@ 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 |
+
+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
@@ -303,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..eabbc7f 100644
--- a/src/main/java/org/sofabuffers/sofab/Bound.java
+++ b/src/main/java/org/sofabuffers/sofab/Bound.java
@@ -6,92 +6,126 @@
*/
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 {@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}; {@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
- * 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;
* 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 SCHEMA_COUNT_8 = 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, 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 both constants
- * are {@code static final} objects with a {@code final} field, 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 {
+public record Bound(long max, Rule rule) {
- /**
- * 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.
- */
- private final long cap;
+ /** 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 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 +133,69 @@ 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. 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);
+ public static final Bound SCHEMA_BOUNDED = new Bound(-1L, Rule.CALLER_CHECKED);
- private Bound(long cap) {
- this.cap = cap;
+ /**
+ * 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"))
+ + ")");
+ }
+ }
+
+ /**
+ * 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) {
+ return new Bound(n, Rule.SCHEMA);
}
/**
@@ -129,7 +216,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.
*
*
@@ -145,50 +232,68 @@ private Bound(long cap) {
* 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_BOUNDED for that")
- + ")");
- }
- return new Bound(max);
+ return new Bound(max, Rule.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 value) {
- return cap >= 0L && value > cap;
+ boolean exceededBy(long length) {
+ return rule != Rule.CALLER_CHECKED && length > 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 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 index the wire's element index
- * @return true if a receiver cap is stated and {@code index} is at or past it
+ * @param noun {@code "string length"} or {@code "blob length"}
+ * @param length the announced length
+ * @return the exception to throw
*/
- boolean exceededByIndex(long index) {
- return cap >= 0L && index >= cap;
+ UncheckedIOException rejectLength(String noun, long length) {
+ if (rule == Rule.SCHEMA) {
+ return Sofab.invalid(noun + " " + length + " above schema maxlen " + max);
+ }
+ return Sofab.limitExceeded(noun + " " + length + " above configured limit " + max);
}
/**
- * The configured limit, for the rejection message. Negative for
- * {@link #SCHEMA_BOUNDED}, which never rejects.
+ * 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 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 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 Rule#CALLER_CHECKED}: ARGUMENT. It carries no count, so the call
+ * has nothing to compare; silence would grow the list uncompared.
+ *
*
- * @return the cap
+ * @param index the wire's element index
+ * @return the exception to throw
*/
- long cap() {
- return cap;
+ UncheckedIOException rejectIndex(long index) {
+ switch (rule) {
+ 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");
+ }
}
/**
@@ -197,14 +302,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 +317,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 (rule) {
+ 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 2ee1901..f1afb73 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,34 +49,57 @@
* 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.
+ *
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 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
* 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".
+ * 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
+ * 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
+ * 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.
*
- *
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
+ *
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 +144,123 @@ 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}, {@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
+ * 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#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 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};
+ * 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);
+ 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#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 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};
+ * the list is left untouched in all three
+ */
+ 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
@@ -132,23 +283,25 @@ private Seq() {
*
*
{@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);
@@ -180,17 +333,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);
@@ -212,17 +368,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);
@@ -244,17 +403,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);
@@ -276,17 +438,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);
@@ -308,17 +473,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);
@@ -340,17 +508,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);
@@ -367,37 +538,64 @@ 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, 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
+ * 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
- * 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}
*/
- private static void checkIndex(int id, Bound bound) {
- if (Bound.required(bound, "max_dyn_array_count").exceededByIndex(id)) {
- throw overIndexCap(id, bound);
+ public static void checkIndex(int id, Bound bound) {
+ if (bound == null || id >= bound.max()) {
+ throw Bound.required(bound, "the array element index").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 dd54286..fde2f6a 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");
@@ -122,9 +123,10 @@ 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 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 {
@@ -144,9 +146,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());
}
}
@@ -171,6 +174,32 @@ 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");
+
+ // 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));
}
/**
@@ -202,6 +231,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