Make message.encode more consistent

This commit is contained in:
Kagami Hiiragi 2015-01-07 05:18:41 +03:00
parent 2dc2f48a47
commit 85798fa619
2 changed files with 11 additions and 13 deletions

View File

@ -65,22 +65,20 @@ var message = exports.message = {
/**
* Encode message structure.
* @param {string} command - ASCII string identifying the packet
* content
* @param {Buffer} payload - The actual data, a message or an object
* @param {{command: string, payload: Buffer}} opts - Encode options
* @return {Buffer} Encoded message structure.
*/
encode: function(command, payload) {
assert(command.length <= 12, "Command is too long");
assert(isAscii(command), "Non-ASCII characters in command");
assert(payload.length <= 262144, "Payload is too big");
var buf = new Buffer(24 + payload.length);
encode: function(opts) {
assert(opts.command.length <= 12, "Command is too long");
assert(isAscii(opts.command), "Non-ASCII characters in command");
assert(opts.payload.length <= 262144, "Payload is too big");
var buf = new Buffer(24 + opts.payload.length);
buf.fill(0);
buf.writeUInt32BE(message.MAGIC, 0, true);
buf.write(command, 4);
buf.writeUInt32BE(payload.length, 16, true);
getchecksum(payload).copy(buf, 20);
payload.copy(buf, 24);
buf.write(opts.command, 4);
buf.writeUInt32BE(opts.payload.length, 16, true);
getchecksum(opts.payload).copy(buf, 20);
opts.payload.copy(buf, 24);
return buf;
},
};

View File

@ -57,7 +57,7 @@ describe("Crypto", function() {
describe("Common structures", function() {
describe("message", function() {
it("should encode", function() {
expect(message.encode("test", Buffer("payload")).toString("hex")).to.equal("e9beb4d97465737400000000000000000000000770b33ce97061796c6f6164");
expect(message.encode({command: "test", payload: Buffer("payload")}).toString("hex")).to.equal("e9beb4d97465737400000000000000000000000770b33ce97061796c6f6164");
});
it("should decode", function() {