From 44f4805d9d54ff857814592118432bd03c4d8f1f Mon Sep 17 00:00:00 2001 From: luaneko Date: Wed, 8 Jan 2025 01:46:54 +1100 Subject: [PATCH] Add integer encoding utils --- bytes.ts | 41 +++++++++++++++++++++++++++++++++++++++++ deno.json | 2 +- mod.ts | 8 ++++++++ 3 files changed, 50 insertions(+), 1 deletion(-) diff --git a/bytes.ts b/bytes.ts index 8915377..1b3971d 100644 --- a/bytes.ts +++ b/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) { diff --git a/deno.json b/deno.json index 6191a9c..b04e117 100644 --- a/deno.json +++ b/deno.json @@ -1,5 +1,5 @@ { "name": "@luaneko/lstd", - "version": "0.1.3", + "version": "0.1.4", "exports": "./mod.ts" } diff --git a/mod.ts b/mod.ts index 0c5d4b1..8f58689 100644 --- a/mod.ts +++ b/mod.ts @@ -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,