c-st-js
v1.0.3
Published
c-style binary data pack & unpack
Downloads
2
Maintainers
Readme
cstruct-js
c-style binary data pack & unpack
安装
npm install c-st-js --save
例子
(function () {
'use strict';
var _ = require('c-struct');
var NetMsgHead = require('../netmsg_head.js');
var NetMsgMsgId = require('../netmsg_msgid.js');
module.exports = ClientVertifyReq;
var CMD = NetMsgMsgId.ClientVertifyReqMsgID;
var structName = 'ClientVertifyReq';
function ClientVertifyReq() {
this.Source = 0;
this.UID = 0;
this.Token = "";
}
var _ClientVertifyReq = new _.Schema({
Source: _.type.uint8,
UID: _.type.uint64,
Token: _.type.string(32)
});
_.register(structName, _ClientVertifyReq);
var proto = ClientVertifyReq.prototype;
proto.encode = function () {
var self = this;
var msgbuf = _.packSync(structName, {
Source: self.Source,
UID: self.UID,
Token: self.Token
});
return Buffer.concat([new NetMsgHead(msgbuf.length, CMD).encode(), msgbuf]);
};
proto.decode = function (buf) {
var head = new NetMsgHead(0, 0);
head.decode(buf);
var obj = _.unpackSync(structName, buf.slice(NetMsgHead.len));
this.Source = obj.Source;
this.UID = obj.UID;
this.Token = obj.Token;
};
})();
编写目的
本项目参考了 https://github.com/majimboo/c-struct
但是 c-struct 有以下问题:
- 有BUG,打包的数据是错误的...
- 不能对接其他系统。主要原因,打包的string类型,不带长度信息。
- 无法简单的fork修改。因为项目使用npm做包管理。fork修改的,不方便npm publish。
因以上原因,将基于c-struct项目代码,做如下功能:
- 修复BUG,正确pack & unpack
- string类型数据,打包后格式为 [string length + string data]
参考项目
https://github.com/majimboo/c-struct
TODO
去除Schema,本质上Schema是多余的,存在多次定义,可以合并到一块。
提供2进制数据字段
提供浮点数类型