|
1 | 1 | import Serializable from "./Serializable"; |
2 | 2 |
|
3 | 3 | export default class StringEncoder implements Serializable<string> { |
4 | | - // Default size of the decoder buffer that's always reused (in bytes) |
5 | | - private static readonly ENCODER_BUFFER_SIZE = 16384 |
6 | | - |
7 | 4 | private textEncoder = new TextEncoder(); |
8 | 5 | private textDecoder = new TextDecoder(); |
9 | 6 |
|
10 | | - private encoderBuffer: ArrayBuffer = new ArrayBuffer(StringEncoder.ENCODER_BUFFER_SIZE); |
11 | | - private encoderArray: Uint8Array = new Uint8Array(this.encoderBuffer); |
12 | | - private currentDecoderBufferSize: number = StringEncoder.ENCODER_BUFFER_SIZE; |
13 | | - |
14 | 7 | decode(buffer: Uint8Array): string { |
15 | 8 | return this.textDecoder.decode(buffer); |
16 | 9 | } |
17 | 10 |
|
18 | 11 | encode(stringValue: string, destination: Uint8Array): number { |
19 | 12 | // Safari does not support the encodeInto function |
20 | 13 | if (this.textEncoder.encodeInto !== undefined) { |
21 | | - const maxStringLength = stringValue.length * 3; |
22 | | - |
23 | | - if (this.currentDecoderBufferSize < maxStringLength) { |
24 | | - this.encoderBuffer = new ArrayBuffer(maxStringLength); |
25 | | - this.encoderArray = new Uint8Array(this.encoderBuffer); |
26 | | - this.currentDecoderBufferSize = maxStringLength; |
27 | | - } |
28 | | - |
29 | | - const writeResult = this.textEncoder.encodeInto(stringValue, this.encoderArray); |
30 | | - const writeLength = writeResult.written || 0; |
31 | | - destination.set(this.encoderArray.subarray(0, writeLength)); |
32 | | - return writeLength; |
| 14 | + // Optimization: Write directly to destination to avoid intermediate buffer and copy. |
| 15 | + // destination is guaranteed to be large enough (max string length * 3) by the caller (ShareableArray). |
| 16 | + const writeResult = this.textEncoder.encodeInto(stringValue, destination); |
| 17 | + return writeResult.written || 0; |
33 | 18 | } else { |
34 | 19 | const encodedString = this.textEncoder.encode(stringValue); |
35 | 20 | destination.set(encodedString); |
|
0 commit comments