Add integer encoding utils
This commit is contained in:
parent
0403a8611a
commit
44f4805d9d
41
bytes.ts
41
bytes.ts
@ -39,6 +39,47 @@ export function to_base64(b: BinaryLike): string {
|
||||
return encodeBase64(to_utf8(b));
|
||||
}
|
||||
|
||||
export function read_u16_be(b: Uint8Array, i = 0) {
|
||||
return (b[i++] << 8) + b[i++];
|
||||
}
|
||||
|
||||
export function read_i16_be(b: Uint8Array, i = 0) {
|
||||
const n = (b[i++] << 8) + b[i++];
|
||||
return n | ((n & 0x8000) * 0x1fffe);
|
||||
}
|
||||
|
||||
export function read_u32_be(b: Uint8Array, i = 0) {
|
||||
return ((b[i++] << 24) + (b[i++] << 16) + (b[i++] << 8) + b[i++]) >>> 0;
|
||||
}
|
||||
|
||||
export function read_i32_be(b: Uint8Array, i = 0) {
|
||||
return (b[i++] << 24) + (b[i++] << 16) + (b[i++] << 8) + b[i++];
|
||||
}
|
||||
|
||||
export function write_u16_be(b: Uint8Array, n: number, i = 0) {
|
||||
if (n < 0 || 0xffff < n)
|
||||
throw new TypeError(`input out of range, expected u16`);
|
||||
(b[i++] = n >>> 8), (b[i++] = n);
|
||||
}
|
||||
|
||||
export function write_i16_be(b: Uint8Array, n: number, i = 0) {
|
||||
if (n < -0x8000 || 0x7fff < n)
|
||||
throw new TypeError(`input out of range, expected i16`);
|
||||
(b[i++] = n >>> 8), (b[i++] = n);
|
||||
}
|
||||
|
||||
export function write_u32_be(b: Uint8Array, n: number, i = 0) {
|
||||
if (n < 0 || 0xffffffff < n)
|
||||
throw new TypeError(`input out of range, expected u32`);
|
||||
(b[i++] = n >>> 24), (b[i++] = n >>> 16), (b[i++] = n >>> 8), (b[i++] = n);
|
||||
}
|
||||
|
||||
export function write_i32_be(b: Uint8Array, n: number, i = 0) {
|
||||
if (n < -0x80000000 || 0x7fffffff < n)
|
||||
throw new TypeError(`input out of range, expected i32`);
|
||||
(b[i++] = n >>> 24), (b[i++] = n >>> 16), (b[i++] = n >>> 8), (b[i++] = n);
|
||||
}
|
||||
|
||||
export { equals as buf_eq, concat as buf_concat } from "jsr:@std/bytes@^1.0.4";
|
||||
|
||||
export function buf_concat_fast(a: Uint8Array, b: Uint8Array) {
|
||||
|
@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "@luaneko/lstd",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.4",
|
||||
"exports": "./mod.ts"
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user