-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStringEncoder.ts
More file actions
31 lines (27 loc) · 1.11 KB
/
StringEncoder.ts
File metadata and controls
31 lines (27 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import Serializable from "./Serializable";
export default class StringEncoder implements Serializable<string> {
private textEncoder = new TextEncoder();
private textDecoder = new TextDecoder();
decode(buffer: Uint8Array): string {
return this.textDecoder.decode(buffer);
}
encode(stringValue: string, destination: Uint8Array): number {
// Safari does not support the encodeInto function
if (this.textEncoder.encodeInto !== undefined) {
const writeResult = this.textEncoder.encodeInto(stringValue, destination);
return writeResult.written || 0;
} else {
const encodedString = this.textEncoder.encode(stringValue);
destination.set(encodedString);
return encodedString.byteLength;
}
}
/**
* An UTF-8 string that's encoded using the built-in TextEncoder will never occupy more than 3 * stringlength bytes.
*
* @param value The string value that should be encoded as a string with this StringEncoder.
*/
maximumLength(value: string): number {
return value.length * 3;
}
}