Permalink
Browse files

allow packing into existing buffer

  • Loading branch information...
1 parent 2fa7aa5 commit ccf8d8b6dfae6ee12945681fcb6a5b53de8cb2ec @tjfontaine committed Jan 29, 2012
Showing with 30 additions and 8 deletions.
  1. +5 −0 example.js
  2. +7 −3 package.json
  3. +18 −5 struct.js
View
5 example.js
@@ -11,3 +11,8 @@ console.log(util.inspect(r))
var record = new Buffer("raymond \x32\x12\x08\x01\x08")
r = struct.unpack('<10sHHb', record)
console.log(util.inspect(r))
+
+var b = new Buffer(15)
+b.fill(0)
+struct.pack('hhl', b, 3, 1, 2, 3);
+console.log(util.inspect(b));
View
10 package.json
@@ -1,12 +1,16 @@
{
- "name": "struct",
- "version": "0.0.1",
+ "name": "pystruct",
+ "version": "0.0.2",
+ "author": "Timothy J Fontaine <tjfontaine@gmail.com> (http://atxconsulting.com)",
"description": "Buffer based implementation of python's struct module",
"keywords": [
"struct",
"python"
],
"homepage": "http://github.com/tjfontaine/node-struct",
+ "bugs": "http://github.com/tjfontaine/node-struct/issues",
"main": "struct.js",
- "dependencies": []
+ "engines": {
+ "node": ">= 0.5.0"
+ }
}
View
23 struct.js
@@ -203,10 +203,23 @@ var calcsize = function(fmt) {
};
exports.calcsize = calcsize;
-var pack = function(fmt) {
+var pack = function(fmt, buff, buf_pos) {
var calls = fmt_to_list(fmt, 'write');
- var result = new Buffer(calc_size(calls));
- var values = Array.prototype.slice.call(arguments, 1);
+ var size = calc_size(calls);
+ var result, values, position;
+
+ if (buff instanceof Buffer) {
+ if (size + buf_pos > buff.length) {
+ throw new Error("Buffer not large enough for packing");
+ }
+ result = buff;
+ position = buf_pos;
+ values = Array.prototype.slice.call(arguments, 3);
+ } else {
+ result = new Buffer(size);
+ position = 0;
+ values = Array.prototype.slice.call(arguments, 1);
+ }
var expected = 0;
calls.forEach(function(c) {
@@ -225,13 +238,13 @@ var pack = function(fmt) {
var call = calls[i];
var arg = values[arg_pos];
if (call.entry.string) {
- result.write(arg, pos, arg.length);
+ result.write(arg, pos + position, arg.length);
arg_pos += 1;
pos += call.size * call.entry.size;
} else {
var j;
for (j=0; j<call.size; j++) {
- Buffer.prototype[call.meth].call(result, arg, pos);
+ Buffer.prototype[call.meth].call(result, arg, pos + position);
pos += call.entry.size;
arg_pos += 1;
}

0 comments on commit ccf8d8b

Please sign in to comment.