Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions changelog.d/sdk-short-text-encoding.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## Changed

- The TypeScript SDK serializes short ASCII record fields directly into query and sync frames, reducing allocation overhead.
8 changes: 8 additions & 0 deletions runtime/packages/sdk/src/cbor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,13 @@ class Writer {
this.len += b.length;
}

/** For short ASCII text, the UTF-8 length fits in the initial CBOR byte. */
shortAscii(s: string): void {
this.ensure(1 + s.length);
this.buf[this.len++] = 0x60 | s.length;
for (let i = 0; i < s.length; i++) this.buf[this.len++] = s.charCodeAt(i);
}

head(major: number, arg: number | bigint): void {
const m = major << 5;
if (typeof arg === "number" && arg < 24) {
Expand Down Expand Up @@ -189,6 +196,7 @@ function encodeMap(w: Writer, m: CborMap, depth: number): void {
}

function encodeText(w: Writer, s: string): void {
if (s.length < 24 && !/[^\x00-\x7f]/u.test(s)) return w.shortAscii(s);
if (!isWellFormed(s)) throw new CborError("utf8", "text is not well-formed UTF-16");
const b = textEncoder.encode(s);
try {
Expand Down
2 changes: 1 addition & 1 deletion runtime/packages/sdk/test/cbor-secrets.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ describe("secret-bearing CBOR scratch lifetime", () => {
temporary.push(bytes);
return bytes;
});
const input = new Map([["key", "value"]]);
const input = new Map([["clé", "valeur privée"]]);
const output = encodeSecret(input);
expect(decode(output)).toEqual(input);
expect(temporary).toHaveLength(2);
Expand Down
8 changes: 8 additions & 0 deletions runtime/packages/sdk/test/cbor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,14 @@ describe("mdb-cbor/1", () => {
expect(() => encode("\ud800")).toThrow(CborError);
});

it("uses the UTF-8 byte count at the short-text boundary", () => {
for (const text of ["", "\0\x7f", "x".repeat(23), "x".repeat(24), "x".repeat(22) + "é", "😀"]) {
const utf8 = new TextEncoder().encode(text);
const header = utf8.length < 24 ? [0x60 + utf8.length] : [0x78, utf8.length];
expect(encode(text)).toEqual(Uint8Array.from([...header, ...utf8]));
}
});

it("bounds depth", () => {
const b = new Uint8Array(130).fill(0x81);
b[129] = 0;
Expand Down
Loading