Declaratively encode and decode binary data
Inspired by restructure and binary-parser
import * as b from "@sighmir/bstruct";
export const login = b.struct({
length: b.int16le,
op: b.int16le,
s1: b.skip(20),
account: b.string(33, "utf8"),
s2: b.skip(26),
password: b.string(16, "base64"),
});
const loginObj = {
length: 4080,
op: 3,
account: "abcde",
password: "ZWZnaGkK",
};
const buf = login.encode(loginObj);
const obj = login.decode<typeof loginObj>(buf);
Create a binary structure encoder/decoder, functions encode and decode are available, property struct returns the argument used to build the structure encode/decoder, property size returns the added size of all binary parsers used on the structure.
Skip a certain amount of bytes, if the variable is a buffer on the encoded object, simply copy it to the new buffer, if it's something else, create a new buffer and fill it with zeros. When decoding it simply copies part of the buffer to the new object.
Parse bytes as a string. Encoding can be any BufferEncoding.
Parse bytes as boolean.
Parse bytes as integer.
Parse bytes as float.
Parse bytes as double.
Copy part of the buffer to the object when decoding, or a buffer variable from the object to the new buffer when encoding.
Parse an array using one of the previous parsers.
Uses the value of a variable on the parent object to pick a parser for a nested object. You can also use b.struct as a parser for nested objects.
bstruct - Declaratively encode and decode binary data
Copyright (C) 2020 Guilherme Caulada
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.