-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
vec.ts
63 lines (50 loc) · 1.92 KB
/
vec.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import { bn } from '@fuel-ts/math';
import type { Uint8ArrayWithDynamicData } from '../utilities';
import { concatWithDynamicData, BASE_VECTOR_OFFSET, chunkByLength } from '../utilities';
import type { TypesOfCoder } from './abstract-coder';
import { Coder } from './abstract-coder';
import { U64Coder } from './u64';
type InputValueOf<TCoder extends Coder> = Array<TypesOfCoder<TCoder>['Input']>;
type DecodedValueOf<TCoder extends Coder> = Array<TypesOfCoder<TCoder>['Decoded']>;
export class VecCoder<TCoder extends Coder> extends Coder<
InputValueOf<TCoder>,
DecodedValueOf<TCoder>
> {
coder: TCoder;
constructor(coder: TCoder) {
super('struct', `struct Vec`, coder.encodedLength + BASE_VECTOR_OFFSET);
this.coder = coder;
}
encode(value: InputValueOf<TCoder>): Uint8Array {
if (!Array.isArray(value)) {
this.throwError('expected array value', value);
}
const parts: Uint8Array[] = [];
// pointer (ptr)
const pointer: Uint8ArrayWithDynamicData = new U64Coder().encode(BASE_VECTOR_OFFSET);
// pointer dynamicData, encode the vector now and attach to its pointer
pointer.dynamicData = {
0: concatWithDynamicData(Array.from(value).map((v) => this.coder.encode(v))),
};
parts.push(pointer);
// capacity (cap)
parts.push(new U64Coder().encode(value.length));
// length (len)
parts.push(new U64Coder().encode(value.length));
return concatWithDynamicData(parts);
}
decode(data: Uint8Array, offset: number): [DecodedValueOf<TCoder>, number] {
const len = data.slice(16, 24);
const length = bn(new U64Coder().decode(len, 0)[0]).toNumber();
const vectorRawData = data.slice(
BASE_VECTOR_OFFSET,
BASE_VECTOR_OFFSET + length * this.coder.encodedLength
);
return [
chunkByLength(vectorRawData, this.coder.encodedLength).map(
(chunk) => this.coder.decode(chunk, 0)[0]
),
offset + BASE_VECTOR_OFFSET,
];
}
}