Created
December 9, 2010 16:43
-
-
Save sideshowcoder/734947 to your computer and use it in GitHub Desktop.
Pack an Array to a Buffer following given format string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Extend Array to allow packing to Buffer | |
* | |
* Inspired by ruby array pack method | |
* | |
* Takes a format fmt and walks the array | |
* C = Element is interpreted as ASCII character (unsigned char) | |
* a = Element is interpreted as ASCII string | |
* n = Element is interpreted as Short generating a 2 octets | |
* | |
* Just for the hack of it ;) | |
* b = Element is binary but utf8 encoded as string | |
* this is mainly a hack to get hashes from crypto into the buffer since | |
* they are passed as strings, by first converting them into an array and | |
* then writing the array into the buffer via buffer.copy | |
* | |
* | |
* The last fmt element is repeated for the length of the array | |
*/ | |
Array.prototype.pack = function(fmt) { | |
// Fill format sring to length | |
while(fmt.length < this.length) fmt += fmt[fmt.length-1]; | |
var a = new Array(); | |
var len = 0; | |
this.forEach(function(el, idx, ary) { | |
switch(fmt[idx]) { | |
case 'C': | |
var buf = new Buffer(1); | |
buf[0] = el; | |
len += 1; | |
break; | |
case 'a': | |
var buf = new Buffer(el); | |
len += el.length; | |
break; | |
case 'n': | |
var buf = new Buffer(2); | |
// Set lower bits | |
buf[1] = el & 0xff; | |
// Set higher bits | |
buf[0] = el >> 8; | |
len += 2; | |
break; | |
case 'b': | |
var buf = new Buffer(1); | |
buf[0] = el.charCodeAt(el); | |
len += 1; | |
break; | |
default: | |
throw 'Format invalid'; | |
} | |
a.push(buf); | |
}); | |
var res = new Buffer(len); | |
var off = 0; | |
a.forEach(function(el, idx, ary) { | |
el.copy(res, off, 0); | |
off += el.length; | |
}); | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment