Skip to content
Closed
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
16 changes: 16 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -466,6 +466,22 @@ test('StringTable', async (t) => {
table.dedup('hello')
assert.strictEqual(bufToHex(table.encode()), encodings[''] + encodings['hello'])
})

await t.test('encodes non-ASCII strings as TextEncoder does', async () => {
const strings = ['é', '日本語', '😀 emoji', 'lone \uD800 high', 'lone \uDC00 low', 'x'.repeat(200) + 'ü']
const table = new StringTable()
for (const s of strings) table.dedup(s)
const encoded = table.encode()
assert.strictEqual(encoded.length, table.encodedLength)
assert.strictEqual(bufToHex(encoded), encodeStringTable(table))
})

await t.test('re-encodes decoded strings byte for byte', async () => {
// 0xff is not valid UTF-8, so the decoded string alone can't reproduce it
const raw = hexToBuf('3200' + '3203' + '61ff62')
const decoded = Profile.decode(raw).stringTable
assert.strictEqual(bufToHex(decoded.encode()), bufToHex(raw))
})
})

function profileToObject(profile: any): object {
Expand Down
84 changes: 64 additions & 20 deletions src/string-table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,51 @@ function encodeLengthDelimited(utf8: Uint8Array | Buffer): Uint8Array {
return buffer
}

// The UTF-8 length of a string, counting a lone surrogate as U+FFFD the way
// Buffer and TextEncoder write it
function utf8Length(value: string): number {
let length = value.length
for (let i = 0; i < value.length; i++) {
const code = value.charCodeAt(i)
if (code < 0x80) continue
if (code < 0x800) {
length += 1
} else if (code >= 0xd800 && code <= 0xdbff && i + 1 < value.length &&
(value.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {
length += 2
i++
} else {
length += 2
}
}
return length
}

const utf8ByteLength = typeof Buffer === 'undefined'
? utf8Length
: (value: string) => Buffer.byteLength(value, 'utf8')

// Writes a string's UTF-8 bytes into `buffer` at `offset`
function utf8Writer(buffer: Uint8Array): (value: string, offset: number) => void {
if (typeof Buffer === 'undefined') {
const encoder = new TextEncoder()
return (value, offset) => { encoder.encodeInto(value, buffer.subarray(offset)) }
}
const view = Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
return (value, offset) => { view.write(value, offset, 'utf8') }
}

/**
* The strings of a profile, each encoded once as it is added. The enclosing
* message supplies the field number when it encodes the table, so one table
* type serves both pprof and OTel.
* The strings of a profile. A string's UTF-8 bytes are written straight into
* the output when the table is encoded, so adding a string allocates no
* buffer. The enclosing message supplies the field number when it encodes the
* table, so one table type serves both pprof and OTel.
*/
export class StringTable {
strings = new Array<string>()
#encodings = new Array<Uint8Array>()
#byteLengths = new Array<number>()
// The bytes of strings read from a profile, which re-encoding reproduces exactly
#decoded = new Array<Uint8Array | undefined>()
#positions = new Map<string, number>()
#encodedLength = 0

Expand All @@ -54,15 +91,23 @@ export class StringTable {

/** Measures the strings as the repeated string field `field`. */
_measure(field: number): number {
return this.#encodings.length * measureTag(field) + this.#encodedLength
return this.#byteLengths.length * measureTag(field) + this.#encodedLength
}

/** Encodes the strings as the repeated string field `field`. */
_encodeToBuffer(buffer: Uint8Array, offset: number, field: number): number {
for (const encoded of this.#encodings) {
const writeUtf8 = utf8Writer(buffer)
for (let i = 0; i < this.#byteLengths.length; i++) {
const byteLength = this.#byteLengths[i]
offset = encodeTag(buffer, offset, field, kTypeLengthDelim)
buffer.set(encoded, offset)
offset += encoded.length
offset = encodeNumber(buffer, offset, byteLength)
const decoded = this.#decoded[i]
if (decoded !== undefined) {
buffer.set(decoded, offset)
} else if (byteLength > 0) {
writeUtf8(this.strings[i], offset)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unlike the previous buffer.set(), both Buffer.write() and TextEncoder.encodeInto() can silently write only what fits. Since their return values are ignored, table.encode(new Uint8Array(table.encodedLength - 1)) can now return truncated protobuf output rather than throwing. Could we validate capacity in StringTable.encode(), using the existing prepareBuffer helper, restore the previous throwing behavior, and add a regression test?

}
offset += byteLength
}
return offset
}
Expand All @@ -89,22 +134,21 @@ export class StringTable {
if (typeof value === 'number') return value
let position = this.#positions.get(value)
if (position === undefined) {
position = this.strings.push(value) - 1
this.#positions.set(value, position)

// Encode strings on insertion
const encoded = encodeLengthDelimited(toUtf8(value))
this.#encodings.push(encoded)
this.#encodedLength += encoded.length
position = this.#add(value, utf8ByteLength(value))
}
return position
}

_decodeString(buffer: Uint8Array) {
const value = decodeString(buffer)
this.#positions.set(value, this.strings.push(value) - 1)
const encoded = encodeLengthDelimited(buffer)
this.#encodings.push(encoded)
this.#encodedLength += encoded.length
const position = this.#add(decodeString(buffer), buffer.length)
this.#decoded[position] = buffer.slice()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I am not mistaken, this could cause mistakes because slice just creates a reference.

The following would fix that by creating an actual copy and using a fast path for small entries:

Suggested change
this.#decoded[position] = buffer.slice()
this.#decoded[position] = buffer.length <= 64 || typeof Buffer === 'undefined'
? new Uint8Array(buffer)
: Buffer.from(buffer)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

seconding this

}

#add(value: string, byteLength: number): number {
const position = this.strings.push(value) - 1
this.#positions.set(value, position)
this.#byteLengths.push(byteLength)
this.#encodedLength += varintLength(byteLength) + byteLength
return position
}
}