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..5ad74d8 100644 --- a/src/main/java/org/sofabuffers/sofab/OStream.java +++ b/src/main/java/org/sofabuffers/sofab/OStream.java @@ -788,6 +788,60 @@ 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 { + int len = text.length(); + int ascii = asciiPrefix(text); + if (ascii == len) { + writeAsciiString(id, text, len); + return; + } + writeMeasuredString(id, text, utf8Length(text, ascii)); + } + + /** + * 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 { + // 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. @@ -803,8 +857,8 @@ public void writeString(int id, String text) 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. @@ -817,23 +871,31 @@ 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 (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; + 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); } - int n = utf8Length(text, ascii); + } + + /** 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); } + /** + * 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()); + } +}