js add Struct to ArrayBuffer

使用struct-buffer为ArrayBuffer添加结构体

$ npm i struct-buffer

1. 创建结构体

import { DWORD, string_t, StructBuffer, uint32_t } from "struct-buffer";

const struct = new StructBuffer("Player",{
  hp: DWORD, // 4字节大小
  mp: uint32_t, // 4字节大小
  name: string_t[3], // 3字节大小
});

2. 解析ArrayBuffer

const buffer = new Uint8Array([ 
  0, 0, 0, 0x0a, 
  0, 0, 0, 0x64, 
  0x61, 0x62, 0x63, 
]);

const data = struct.decode(buffer);
// data => { hp: 10, mp: 100, name: 'abc' };

将Object数据转换为ArrayBuffer

// 注意key要和结构体定义时的一样
const view = struct.encode({
  hp: 10,
  mp: 100,
  name: "abc",
});
// view =>  <00 00 00 0a 00 00 00 64 61 62 63>

可以注册类型

// registerType(typeName: string | string[], size: 1 | 2 | 4 | 8, unsigned = true): StructType

const short = registerType("short", 2, false);

可以使用typedef继承别的类型

// typedef(typeName: string | string[], type: StructType): StructType

const HANDLE = typedef("HANDLE", DWORD);

See alse:

原文地址:https://www.cnblogs.com/ajanuw/p/14191120.html