Skip to content

Commit ee2545a

Browse files
committed
add encoder and decoder for regular numbers
1 parent 1fdc6c6 commit ee2545a

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/index.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,3 +60,38 @@ export function toBigInt(data: Record<number, number>, index: { $: number } = {
6060
return result
6161
}
6262
}
63+
64+
export function from(integer: number): number[] {
65+
const result: number[] = []
66+
67+
while (integer >= 0) {
68+
let value = integer & 0x7F
69+
70+
// bitwise operators on numbers trim to 32 bits
71+
// the following is like doing `integer >>= 7` without losing bits
72+
integer = Math.floor(integer / 128)
73+
74+
if (integer--)
75+
value |= 0x80
76+
77+
result.push(value)
78+
}
79+
80+
return result
81+
}
82+
83+
export function to(data: Record<number, number>, index: { $: number } = { $: 0 }): number {
84+
let result = 0
85+
let offset = 0
86+
87+
while (true) {
88+
const byte = data[index.$++]
89+
90+
assert(byte != undefined, HERE)
91+
result += ((byte & 0x7F) + (offset && 1)) * (2 ** offset)
92+
offset += 7
93+
94+
if (!(byte & 0x80))
95+
return result
96+
}
97+
}

0 commit comments

Comments
 (0)