-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNumberEncoder.ts
More file actions
32 lines (28 loc) · 1.04 KB
/
NumberEncoder.ts
File metadata and controls
32 lines (28 loc) · 1.04 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
32
import Serializable from "./Serializable";
export default class NumberEncoder implements Serializable<number> {
decode(buffer: Uint8Array): number {
const bufferView = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
// First byte indicates if we did store a float or an int
const numberType = bufferView.getUint8(0);
if (numberType === 0) {
return bufferView.getInt32(1);
} else {
return bufferView.getFloat64(1);
}
}
encode(value: number, destination: Uint8Array): number {
const dataView = new DataView(destination.buffer, destination.byteOffset, destination.byteLength);
if (Number.isInteger(value)) {
dataView.setUint8(0, 0);
dataView.setInt32(1, value);
return 5;
} else {
dataView.setUint8(0, 1);
dataView.setFloat64(1, value);
return 9;
}
}
maximumLength(value: number): number {
return Number.isInteger(value) ? 5 : 9;
}
}