Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
assume TextEncoder.prototype.encodeInto() is always available
  • Loading branch information
gfx committed Mar 3, 2023
commit cc62c682379d02e58c11a12ee2389229b72211cb
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"source.fixAll.eslint": true
},
"cSpell.words": [
"tsdoc"
"tsdoc",
"whatwg"
]
}
13 changes: 6 additions & 7 deletions src/utils/utf8.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,19 +84,18 @@ export function utf8EncodeJs(str: string, output: Uint8Array, outputOffset: numb
}
}

// TextEncoder and TextDecoder are standardized in whatwg encoding:
// https://encoding.spec.whatwg.org/
// and available in all the modern browsers:
// https://caniuse.com/textencoder

const sharedTextEncoder = new TextEncoder();
const TEXT_ENCODER_THRESHOLD = 200;

function utf8EncodeTEencode(str: string, output: Uint8Array, outputOffset: number): void {
output.set(sharedTextEncoder.encode(str), outputOffset);
}

function utf8EncodeTEencodeInto(str: string, output: Uint8Array, outputOffset: number): void {
export function utf8EncodeTE(str: string, output: Uint8Array, outputOffset: number): void {
sharedTextEncoder.encodeInto(str, output.subarray(outputOffset));
}

export const utf8EncodeTE = (sharedTextEncoder.encodeInto as unknown) ? utf8EncodeTEencodeInto : utf8EncodeTEencode;

export function utf8Encode(str: string, output: Uint8Array, outputOffset: number): void {
if (str.length > TEXT_ENCODER_THRESHOLD) {
utf8EncodeTE(str, output, outputOffset);
Expand Down