Class Utf8
string field (CORELIB_PLAN §6.4).
OStream.writeString(int, String) rejects an invalid String while
measuring it, but wherever a string is handled as raw bytes
this validator is what enforces the contract: on encode for the byte-container
entry point OStream.writeFixlen(int, byte[], int, int, FixlenType) with FixlenType.STRING, and on
decode for bytes arriving from a peer, which must be validated before
they are handed to the consumer as a String — which is what
decode(byte[], int, int) does, in that order. Generated code needs this on every
materialized string, so it belongs here rather than being emitted into every
generated message class.
Validation is on the byte range, not on a constructed String:
new String(bytes, UTF_8) silently substitutes U+FFFD for malformed
input, so a check made after that conversion can never fail. Checking first is
what makes the rejection possible at all.
-
Method Summary
-
Method Details
-
valid
public static boolean valid(byte[] b, int i, int end) Reports whetherb[i..end)is well-formed UTF-8.Accepts exactly the Unicode-scalar encoding and no more. Rejected: overlong forms (including the
C0 80"Modified UTF-8" NUL and theC1-lead two-byte forms), surrogate code pointsU+D800..DFFFencoded as three bytes, anything aboveU+10FFFF, a lead byte whose continuation bytes are missing or out of range, and a bare continuation byte.- Parameters:
b- bufferi- first byte of the rangeend- one past the last byte of the range- Returns:
- true when the range is valid UTF-8
-
decode
Materializeb[off, off + len)as aString, rejecting a range that is not well-formed UTF-8.This is what a decoder does with a
stringpayload once it is complete, and it is two steps for a reason:valid(byte[], int, int)first, the conversion second.new String(bytes, UTF_8)silently substitutes U+FFFD for malformed input, so a check made on the result can never fail — validating the bytes is what makes the rejection possible at all, and MESSAGE_SPEC §7 requires the rejection rather than a repaired string.The rejection is
Sofab.invalid(String), i.e. anINVALID_MSGSofabExceptionwrapped so it can leave aVisitorcallback, which is where generated code calls this from.- Parameters:
b- bufferoff- first byte of the payloadlen- payload length in bytes- Returns:
- the decoded string
- Throws:
UncheckedIOException- wrapping anINVALID_MSGSofabExceptionwhen the range is not valid UTF-8
-