-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUInt.ts
101 lines (80 loc) · 2.29 KB
/
UInt.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import { Buffer } from "./deps.ts";
import Parser from "./Parser.ts";
import SimpleGetter from "./SimpleGetter.ts";
abstract class UInt extends Parser implements SimpleGetter<number>
{
public get value() { return this._value; }
public set value(value: number) { this._value = value % this.limit; }
constructor(
protected limit: number,
protected _value: number = 0
) { super(); }
}
export class UInt4 extends UInt
{
constructor(value?: number) { super(16, value); }
/**
* DO NOT USE!
*/
public encode(): Buffer
{
throw new Error("Method not implemented.");
}
/**
* DO NOT USE!
*/
public decode(/* data: Buffer */): number
{
throw new Error("Method not implemented.");
}
}
export class UInt8 extends UInt
{
constructor(value?: number) { super(256, value); }
public encode(): Buffer
{
return Buffer.from([this._value]); // Truncates to lowest 8 bits
}
public decode(data: Buffer): number
{
const value: Buffer = data.slice(0, 1);
this._value = parseInt(value.toString("hex"), 16);
return 1; // octets
}
}
export class UInt16 extends UInt
{
constructor(value?: number) { super(65536, value); }
public encode(): Buffer
{
const rawData: number[] = [];
rawData.push((this._value >> 8)); // Upper 8 bits
rawData.push((this._value)); // Lower 8 bits
return Buffer.from(rawData);
}
public decode(data: Buffer): number
{
const value: Buffer = data.slice(0, 2);
this._value = parseInt(value.toString("hex"), 16);
return 2; // octets
}
}
export class UInt32 extends UInt
{
constructor(value?: number) { super(2147483647, value); }
public encode(): Buffer
{
const rawData: number[] = [];
rawData.push((this._value >> 24)); // Top 8 bits
rawData.push((this._value >> 16)); // Secondary 8 bits
rawData.push((this._value >> 8)); // Tertiary 8 bits
rawData.push((this._value)); // Lower 8 bits
return Buffer.from(rawData);
}
public decode(data: Buffer): number
{
const value: Buffer = data.slice(0, 4);
this._value = parseInt(value.toString("hex"), 16);
return 4; // octets
}
}