From 6fdfd7e847ca610e00435fe10d8fad54e06572ac Mon Sep 17 00:00:00 2001 From: Tau Date: Wed, 11 Mar 2020 22:22:56 -0400 Subject: [PATCH] idz: Add utilities for binary I/O --- src/idz/util/bin.ts | 62 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/idz/util/bin.ts diff --git a/src/idz/util/bin.ts b/src/idz/util/bin.ts new file mode 100644 index 0000000..79cf7c2 --- /dev/null +++ b/src/idz/util/bin.ts @@ -0,0 +1,62 @@ +import iconv from "iconv-lite"; + +const ASCII = "ascii"; +const SHIFT_JIS = "shift_jis"; + +function readStr(buf: Buffer, begin: number, end: number, encoding: string) { + end = Math.min(buf.indexOf(0, begin), end); + + return iconv.decode(buf.slice(begin, end), encoding); +} + +export function readAsciiStr(buf: Buffer, begin: number, end: number) { + return readStr(buf, begin, end, ASCII); +} + +export function readSjisStr(buf: Buffer, begin: number, end: number) { + return readStr(buf, begin, end, SHIFT_JIS); +} + +// WARNING: This is sent little-endian. +export function writeIpAddr(buf: Buffer, str: string, pos: number) { + const bits = str.split("."); + + for (let i = 0; i < 4; i++) { + buf.writeUInt8(parseInt(bits[3 - i]), pos + i); + } +} + +function writeStr( + buf: Buffer, + begin: number, + end: number, + str: string, + encoding: string +) { + const tmp = iconv.encode(str + "\0", encoding); + + if (tmp.length >= end - begin) { + throw new Error("String field overflow"); + } + + tmp.copy(buf, begin); + buf.writeUInt8(0, begin + tmp.length); +} + +export function writeAsciiStr( + buf: Buffer, + begin: number, + end: number, + str: string +) { + writeStr(buf, begin, end, str, ASCII); +} + +export function writeSjisStr( + buf: Buffer, + begin: number, + end: number, + str: string +) { + writeStr(buf, begin, end, str, SHIFT_JIS); +}