Add integer encoding utils

This commit is contained in:
luaneko 2025-01-08 01:46:54 +11:00
parent 0403a8611a
commit 44f4805d9d
Signed by: luaneko
GPG Key ID: 406809B8763FF07A
3 changed files with 50 additions and 1 deletions

View File

@ -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) {

View File

@ -1,5 +1,5 @@
{
"name": "@luaneko/lstd",
"version": "0.1.3",
"version": "0.1.4",
"exports": "./mod.ts"
}

8
mod.ts
View File

@ -7,6 +7,14 @@ export {
to_hex,
from_base64,
to_base64,
read_u16_be,
read_i16_be,
read_u32_be,
read_i32_be,
write_u16_be,
write_i16_be,
write_u32_be,
write_i32_be,
buf_eq,
buf_concat,
buf_concat_fast,