forked from microsoft/devicescript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuffer.ts
More file actions
83 lines (72 loc) · 2.2 KB
/
buffer.ts
File metadata and controls
83 lines (72 loc) · 2.2 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
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
import * as ds from "@devicescript/core"
declare module "@devicescript/core" {
interface Buffer {
/**
* Reads the bit at the given bit index.
* @param bitindex
*/
getBit(bitindex: number): boolean
/**
* Sets the bit at the given index
* @param bitindex
* @param on
*/
setBit(bitindex: number, on: boolean): void
/**
* Reads an unsigned, low-endian 16-bit integer at the specified offset.
*/
readUInt16LE(offset: number): number
/**
* Reads an unsigned, big-endian 16-bit integer at the specified offset.
*/
readUInt16BE(offset: number): number
/**
* Reads an unsigned, low-endian 32-bit integer at the specified offset.
*/
readUInt32LE(offset: number): number
/**
* Reads an unsigned, big-endian 32-bit integer at the specified offset.
*/
readUInt32BE(offset: number): number
}
}
ds.Buffer.prototype.getBit = function getBit(bitindex: number) {
// find bit to flip
const byte = this[bitindex >> 3]
const bit = bitindex % 8
const on = 1 === ((byte >> bit) & 1)
return on
}
ds.Buffer.prototype.setBit = function setBit(bitindex: number, on: boolean) {
const i = bitindex >> 3
// find bit to flip
let byte = this[i]
const bit = bitindex % 8
// flip bit
if (on) {
byte |= 1 << bit
} else {
byte &= ~(1 << bit)
}
// save
this[i] = byte
}
ds.Buffer.prototype.readUInt16LE = function readUInt16LE(offset: number) {
return this.getAt(offset, "u16")
}
ds.Buffer.prototype.readUInt16BE = function readUInt16BE(offset: number) {
if (offset < 0 || offset + 2 > this.length) return 0
return (this[offset] << 8) | this[offset + 1]
}
ds.Buffer.prototype.readUInt32LE = function readUInt32LE(offset: number) {
return this.getAt(offset, "u32")
}
ds.Buffer.prototype.readUInt32BE = function readUInt32BE(offset: number) {
if (offset < 0 || offset + 4 > this.length) return 0
return (
(this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3]
)
}