-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
string.ts
31 lines (25 loc) · 1.02 KB
/
string.ts
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 { concat } from '@ethersproject/bytes';
import { toUtf8Bytes, toUtf8String } from '@ethersproject/strings';
import Coder from './abstract-coder';
export default class StringCoder<TLength extends number = number> extends Coder<string, string> {
length: TLength;
#paddingLength: number;
constructor(length: TLength) {
let paddingLength = (8 - length) % 8;
paddingLength = paddingLength < 0 ? paddingLength + 8 : paddingLength;
super('string', `str[${length}]`, length + paddingLength);
this.length = length;
this.#paddingLength = paddingLength;
}
encode(value: string): Uint8Array {
const encoded = toUtf8Bytes(value.slice(0, this.length));
const padding = new Uint8Array(this.#paddingLength);
return concat([encoded, padding]);
}
decode(data: Uint8Array, offset: number): [string, number] {
const bytes = data.slice(offset, offset + this.length);
const value = toUtf8String(bytes);
const padding = this.#paddingLength;
return [value, offset + this.length + padding];
}
}