@chengaoyuan/struct

结构体的序列化与反序列化

Usage no npm install needed!

<script type="module">
  import chengaoyuanStruct from 'https://cdn.skypack.dev/@chengaoyuan/struct';
</script>

README

struct

npm version install size NPM Downloads Build Status Coverage Status

Installation

$ npm install @chengaoyuan/struct

Usage

import * as assert from "assert";
import Struct from "@chengaoyuan/struct";
const struct = new Struct([
    ["DWORD", "len"],
    ["UINT8", "data", 0]
]);

const arr = [1, 2, 2, 2, 3, 3, 4, 2, 3, 34, 5, 42, 2, 21, 87, 4, 3, 2];
const oldObj = {
    len: arr.length,
    data: arr
};

{
    const ab = struct.serialize(oldObj);
    const newObj = struct.unserialize(ab);
    assert.deepEqual(newObj, oldObj);
}

{
    const size = struct.getRealSize(oldObj);
    const buf = new ArrayBuffer(size);
    const bufView = new DataView(buf);
    struct.encode(bufView, 0, data);
    const newObj = struct.decode(bufView, 0);
    assert.deepEqual(newObj, oldObj);
}

Testing

$ npm test