2.0.3 • Published 3 years ago
@nickname-ru/borsh v2.0.3
borsh
Simple library for serialize and deserialize objects in borsh encoding
Types:
schema/js type
i8/number- 8-bit signed integeri16/number- 16-bit signed integeri32/number- 32-bit signed integeri64/bigint- 64-bit signed integeri128/?- 128-bit signed integeru8/number- 8-bit unsigned integeru16/number- 16-bit unsigned integeru32/number- 32-bit unsigned integeru64/bigint- 64-bit unsigned integeru128/?- 128-bit unsigned integerboolean/boolean- boolstring/string- strings{ maybe: Object }/?Object- optional object (see Rust Option)[Object]/Array- arrays[Object, number]/Array- fixed arrays[Buffer, number]/Buffer- bytesObject- custom objects (to (de-)serialize them make rules for deserialize or serialize functions)
Example
import {
serialize, deserialize
} from "@nickname-ru/borsh";
const Partial = {
kind: "struct",
fields: [
["chess", "u16"]
]
}
const Job = {
kind: "enum",
fields: [
[ // Shopkeep
["cost", "u64"]
],
[ // Army
["cost", "u64"],
["rank", "u16"]
]
]
}
const Human = {
kind: "struct",
fields: [
["name", "string"],
["age", "u64"],
["job", { maybe: Job }],
["seed", [ Partial, 8 ]]
]
}
const human = {
name: "John",
age: 15,
job: {
type: 0,
cost: 1000
},
seed: [
{ chess: 0 },
{ chess: 1 },
{ chess: 2 },
{ chess: 3 },
{ chess: 4 },
{ chess: 5 },
{ chess: 6 },
{ chess: 9 }
]
};
console.log(human);
const human_buffer = serialize(human, Human);
console.log(human_buffer);
const human_new = deserialize(human_buffer, Human);
// we see it's same object
console.log(human_new);