From d061132dde1fdecaf14659194da165d121da7f67 Mon Sep 17 00:00:00 2001 From: Andreas Steinbart Date: Fri, 9 Oct 2026 10:00:23 +0000 Subject: [PATCH 1/2] feat(encode): writeString(id, text, maxlen) refuses past the caller's bound A string whose UTF-8 encoding is longer than the caller's maxlen is refused with SofabError.ARGUMENT before any byte of the field is written, the same way an unpaired surrogate is. The byte length is measured by the pass writeString already runs, so the bounded write costs no second pass and no allocation; a string with more UTF-16 chars than maxlen is refused before that pass, since every char encodes to at least one byte. The bound is the caller's: generated code passes the schema maxlen of the field or array element. The library holds no bound of its own, and the two-argument writeString is the bounded one with no bound. Refs sofa-buffers/generator#656 --- README.md | 7 +- .../java/org/sofabuffers/sofab/OStream.java | 43 ++++++- .../sofabuffers/sofab/StringMaxlenTest.java | 108 ++++++++++++++++++ 3 files changed, 156 insertions(+), 2 deletions(-) create mode 100644 src/test/java/org/sofabuffers/sofab/StringMaxlenTest.java diff --git a/README.md b/README.md index 1b5622e..ac64a34 100644 --- a/README.md +++ b/README.md @@ -399,7 +399,12 @@ it is not part of the codec. string type, so the only value it cannot represent as well-formed UTF-8 is an unpaired UTF-16 surrogate, and `writeString` rejects such a string with `SofabException` (`ARGUMENT`) **before** emitting any bytes, never lossily - substituting a replacement character. There is no strict mode to toggle. The + substituting a replacement character. There is no strict mode to toggle. + `writeString(id, text, maxlen)` adds the caller's byte bound: a string that + encodes to more than `maxlen` UTF-8 bytes is refused the same way (`ARGUMENT`, + before any byte), measured in the pass that already computes the length, so a + bounded write costs no second pass and no allocation. Generated code passes the + schema's `maxlen` there; the library holds no bound of its own. The byte-container entry point `writeFixlen(id, data, from, length, FixlenType.STRING)` takes raw bytes, so it validates that range with `Utf8.valid` and refuses a malformed payload with `ARGUMENT`, again before a byte is written. diff --git a/src/main/java/org/sofabuffers/sofab/OStream.java b/src/main/java/org/sofabuffers/sofab/OStream.java index b66e6ab..baaccf1 100644 --- a/src/main/java/org/sofabuffers/sofab/OStream.java +++ b/src/main/java/org/sofabuffers/sofab/OStream.java @@ -788,6 +788,31 @@ public void writeFp64(int id, double value) throws IOException { * @throws IOException on buffer overflow or sink failure */ public void writeString(int id, String text) throws IOException { + writeString(id, text, Integer.MAX_VALUE); + } + + /** + * Write a string field whose UTF-8 byte length must not exceed {@code maxlen}. + * + *

The bound is the caller's -- generated code passes the schema's + * {@code maxlen} for the field (or the element of a string array); this + * library holds no bound of its own. A string longer than {@code maxlen} + * UTF-8 bytes is refused with {@link SofabError#ARGUMENT} before any + * byte of the field is written, exactly like an unpaired surrogate. The byte + * length is only known after the measuring pass this method runs anyway, so + * the comparison costs no second pass and no allocation; a string with more + * UTF-16 chars than {@code maxlen} is refused before that pass, since every + * char contributes at least one byte. + * + * @param id field id + * @param text string value + * @param maxlen the most UTF-8 bytes {@code text} may encode to + * @throws SofabException with {@link SofabError#ARGUMENT} if {@code text} + * encodes to more than {@code maxlen} bytes or contains an unpaired + * surrogate (invalid UTF-8) + * @throws IOException on buffer overflow or sink failure + */ + public void writeString(int id, String text, int maxlen) throws IOException { // Encode UTF-8 straight into the output buffer instead of allocating an // intermediate byte[] per call (String.getBytes). One pass measures the // byte length for the fixlen header, the second emits the bytes. @@ -817,8 +842,11 @@ public void writeString(int id, String text) throws IOException { // not the offset the payload starts at. A string that does not fit falls // through to writeUtf8, which is what this path replaces and handles both // the in-room loop and the buffer-spanning one. - int ascii = asciiPrefix(text); int len = text.length(); + if (len > maxlen) { + throw overMaxlen(len, maxlen); + } + int ascii = asciiPrefix(text); if (ascii == len) { writeIdTypeValue(id, T_FIXLEN, ((long) len << 3) | FixlenType.STRING.raw()); if (len >= ASCII_BULK_MIN && end - offset >= len) { @@ -830,10 +858,23 @@ public void writeString(int id, String text) throws IOException { return; } int n = utf8Length(text, ascii); + if (n > maxlen) { + throw overMaxlen(n, maxlen); + } writeIdTypeValue(id, T_FIXLEN, ((long) n << 3) | FixlenType.STRING.raw()); writeUtf8(text, n); } + /** + * The refusal of a string past the caller's {@code maxlen}. {@code atLeast} + * is the UTF-8 byte length when it was measured, or the char count -- a lower + * bound of it -- when the string was refused before the measuring pass. + */ + private static SofabException overMaxlen(int atLeast, int maxlen) { + return new SofabException(SofabError.ARGUMENT, + "string of at least " + atLeast + " UTF-8 bytes is above maxlen " + maxlen); + } + /** * Shortest string the ASCII bulk copy in {@link #writeString} is used for. * Below it the char-at-a-time loop is cheaper than the copy's call and bounds diff --git a/src/test/java/org/sofabuffers/sofab/StringMaxlenTest.java b/src/test/java/org/sofabuffers/sofab/StringMaxlenTest.java new file mode 100644 index 0000000..638a3ec --- /dev/null +++ b/src/test/java/org/sofabuffers/sofab/StringMaxlenTest.java @@ -0,0 +1,108 @@ +/* + * SofaBuffers Java - writeString(id, text, maxlen): the caller's byte bound. + * + * SPDX-License-Identifier: MIT + */ +package org.sofabuffers.sofab; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Arrays; + +import org.junit.jupiter.api.Test; + +/** + * The bounded string write refuses a value past the caller's {@code maxlen} -- + * counted in UTF-8 bytes, not chars -- with {@link SofabError#ARGUMENT} and + * before a single byte of the field is written; a value at or below the bound + * encodes to exactly the bytes the unbounded write produces. + */ +class StringMaxlenTest { + + private static byte[] unbounded(int id, String text) throws IOException { + byte[] buf = new byte[256]; + OStream os = new OStream(buf); + os.writeString(id, text); + return Arrays.copyOf(buf, os.bytesUsed()); + } + + private static byte[] bounded(int id, String text, int maxlen) throws IOException { + byte[] buf = new byte[256]; + OStream os = new OStream(buf); + os.writeString(id, text, maxlen); + return Arrays.copyOf(buf, os.bytesUsed()); + } + + private static void assertRefused(String text, int maxlen, String detail) { + OStream os = new OStream(new byte[256]); + SofabException e = assertThrows(SofabException.class, () -> os.writeString(3, text, maxlen)); + assertEquals(SofabError.ARGUMENT, e.error()); + assertTrue(e.getMessage().contains(detail), e.getMessage()); + assertEquals(0, os.bytesUsed(), "a refused string writes no byte"); + } + + @Test + void atTheBoundIsTheUnboundedEncoding() throws IOException { + // ASCII below and above the bulk-copy threshold, every UTF-8 width, empty. + for (String s : new String[] {"", "abcd", "x".repeat(40), "éé", "€", "😀", "aä€😀z"}) { + int n = s.getBytes(java.nio.charset.StandardCharsets.UTF_8).length; + assertArrayEquals(unbounded(5, s), bounded(5, s, n), s); + assertArrayEquals(unbounded(5, s), bounded(5, s, n + 7), s); + } + } + + @Test + void asciiOverTheBoundIsRefusedBeforeMeasuring() { + // More chars than bytes allowed: refused on the char count alone. + assertRefused("xxxxx", 4, "at least 5 UTF-8 bytes is above maxlen 4"); + assertRefused("x".repeat(60), 4, "at least 60 UTF-8 bytes is above maxlen 4"); + assertRefused("a", 0, "above maxlen 0"); + } + + @Test + void multiByteOverTheBoundIsRefusedOnTheByteLength() { + // Fewer chars than the bound, more bytes: only the measuring pass sees it. + assertRefused("ééé", 4, "at least 6 UTF-8 bytes is above maxlen 4"); + assertRefused("xxxé", 4, "at least 5 UTF-8 bytes is above maxlen 4"); + assertRefused("😀", 3, "at least 4 UTF-8 bytes is above maxlen 3"); + assertRefused("é".repeat(40), 79, "at least 80 UTF-8 bytes is above maxlen 79"); + } + + @Test + void anUnpairedSurrogateInsideTheBoundIsStillInvalidUtf8() { + assertRefused("a\uD800", 8, "unpaired surrogate"); + } + + @Test + void aRefusalLeavesTheStreamUsable() throws IOException { + byte[] buf = new byte[64]; + OStream os = new OStream(buf); + os.writeSequenceBeginLazy(9); + assertThrows(SofabException.class, () -> os.writeString(0, "toolong", 3)); + // The lazily held sequence header was not committed by the refused field. + assertEquals(0, os.bytesUsed()); + os.writeString(1, "ok", 3); + os.writeSequenceEnd(); + byte[] refBuf = new byte[64]; + OStream ref = new OStream(refBuf); + ref.writeSequenceBeginLazy(9); + ref.writeString(1, "ok"); + ref.writeSequenceEnd(); + assertArrayEquals(Arrays.copyOf(refBuf, ref.bytesUsed()), + Arrays.copyOf(buf, os.bytesUsed())); + } + + @Test + void aRefusalReachesNoSink() throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + OStream os = new OStream(new byte[4], 0, out::write); + assertThrows(SofabException.class, () -> os.writeString(0, "é".repeat(40), 79)); + os.flush(); + assertEquals(0, out.size()); + } +} From 707169c91211e7b45f76c07719af43f2af522f7c Mon Sep 17 00:00:00 2001 From: Andreas Steinbart Date: Fri, 9 Oct 2026 12:40:32 +0000 Subject: [PATCH 2/2] perf(encode): keep the unbounded writeString free of the bound The two-argument writeString delegated to the bounded one with Integer.MAX_VALUE, which cost the generator's java bench row 44 Ir per encode on schemas whose strings carry no maxlen (17022 -> 17066). Both public writes now share the two private tails (ASCII header + bulk copy, measured header + UTF-8 loop) and only the bounded one compares: 16985 Ir/op for the same unbounded workload. Refs sofa-buffers/generator#656 --- .../java/org/sofabuffers/sofab/OStream.java | 63 ++++++++++++------- 1 file changed, 42 insertions(+), 21 deletions(-) diff --git a/src/main/java/org/sofabuffers/sofab/OStream.java b/src/main/java/org/sofabuffers/sofab/OStream.java index baaccf1..5ad74d8 100644 --- a/src/main/java/org/sofabuffers/sofab/OStream.java +++ b/src/main/java/org/sofabuffers/sofab/OStream.java @@ -788,7 +788,13 @@ public void writeFp64(int id, double value) throws IOException { * @throws IOException on buffer overflow or sink failure */ public void writeString(int id, String text) throws IOException { - writeString(id, text, Integer.MAX_VALUE); + int len = text.length(); + int ascii = asciiPrefix(text); + if (ascii == len) { + writeAsciiString(id, text, len); + return; + } + writeMeasuredString(id, text, utf8Length(text, ascii)); } /** @@ -813,6 +819,29 @@ public void writeString(int id, String text) throws IOException { * @throws IOException on buffer overflow or sink failure */ public void writeString(int id, String text, int maxlen) throws IOException { + // Same shape as the unbounded write, with the bound compared where each + // length becomes known: the char count first (a lower bound of the byte + // length), the byte length after the measuring pass. + int len = text.length(); + if (len > maxlen) { + throw overMaxlen(len, maxlen); + } + int ascii = asciiPrefix(text); + if (ascii == len) { + writeAsciiString(id, text, len); + return; + } + int n = utf8Length(text, ascii); + if (n > maxlen) { + throw overMaxlen(n, maxlen); + } + writeMeasuredString(id, text, n); + } + + /** + * Header and payload of an all-ASCII string of {@code len} chars (= bytes). + */ + private void writeAsciiString(int id, String text, int len) throws IOException { // Encode UTF-8 straight into the output buffer instead of allocating an // intermediate byte[] per call (String.getBytes). One pass measures the // byte length for the fixlen header, the second emits the bytes. @@ -828,8 +857,8 @@ public void writeString(int id, String text, int maxlen) throws IOException { // // getBytes(int,int,byte[],int) is deprecated for the reason that makes it // right here: it copies low bytes, not an encoding, so it is wrong for any - // string that is not known to be single-byte. This one is -- the scan above - // proved every char below 0x80 -- and it is the only way to reach the + // string that is not known to be single-byte. This one is -- the caller's scan + // (asciiPrefix) proved every char below 0x80 -- and it is the only way to reach the // string's storage without allocating a byte[] first (which is exactly what // encoding into the output buffer exists to avoid). Deprecated since 1.1, // never marked forRemoval. @@ -842,25 +871,17 @@ public void writeString(int id, String text, int maxlen) throws IOException { // not the offset the payload starts at. A string that does not fit falls // through to writeUtf8, which is what this path replaces and handles both // the in-room loop and the buffer-spanning one. - int len = text.length(); - if (len > maxlen) { - throw overMaxlen(len, maxlen); - } - int ascii = asciiPrefix(text); - if (ascii == len) { - writeIdTypeValue(id, T_FIXLEN, ((long) len << 3) | FixlenType.STRING.raw()); - if (len >= ASCII_BULK_MIN && end - offset >= len) { - text.getBytes(0, len, buffer, offset); - offset += len; - } else { - writeUtf8(text, len); - } - return; - } - int n = utf8Length(text, ascii); - if (n > maxlen) { - throw overMaxlen(n, maxlen); + writeIdTypeValue(id, T_FIXLEN, ((long) len << 3) | FixlenType.STRING.raw()); + if (len >= ASCII_BULK_MIN && end - offset >= len) { + text.getBytes(0, len, buffer, offset); + offset += len; + } else { + writeUtf8(text, len); } + } + + /** Header and payload of a string whose UTF-8 length {@code n} is measured. */ + private void writeMeasuredString(int id, String text, int n) throws IOException { writeIdTypeValue(id, T_FIXLEN, ((long) n << 3) | FixlenType.STRING.raw()); writeUtf8(text, n); }