-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
number.ts
52 lines (42 loc) · 1.25 KB
/
number.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
import { toNumber, toArray } from '@fuel-ts/math';
import Coder from './abstract-coder';
type NumberCoderType = 'u8' | 'u16' | 'u32';
export default class NumberCoder extends Coder<number, number> {
// This is to align the bits to the total bytes
// See https://github.com/FuelLabs/fuel-specs/blob/master/specs/protocol/abi.md#unsigned-integers
length: number;
baseType: NumberCoderType;
constructor(baseType: NumberCoderType) {
super('number', baseType, 8);
this.baseType = baseType;
switch (baseType) {
case 'u8':
this.length = 1;
break;
case 'u16':
this.length = 2;
break;
case 'u32':
default:
this.length = 4;
break;
}
}
encode(value: number | string): Uint8Array {
let bytes;
try {
bytes = toArray(value);
} catch (error) {
this.throwError(`Invalid ${this.baseType}`, value);
}
if (bytes.length > this.length) {
this.throwError(`Invalid ${this.baseType}. Too many bytes.`, value);
}
return toArray(bytes, 8);
}
decode(data: Uint8Array, offset: number): [number, number] {
let bytes = data.slice(offset, offset + 8);
bytes = bytes.slice(8 - this.length, 8);
return [toNumber(bytes), offset + 8];
}
}