Skip to content

Instantly share code, notes, and snippets.

@TooTallNate
Last active April 27, 2016 23:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save TooTallNate/0fe04681493a3c32da51 to your computer and use it in GitHub Desktop.
Save TooTallNate/0fe04681493a3c32da51 to your computer and use it in GitHub Desktop.
Fixed length "String" type, for use in `ref-struct` type definitions.
var ref = require('ref');
module.exports = FixedString;
/**
* Fixed length "String" type, for use in Struct type definitions.
* Null-terminates by default.
* Throws an Error if there's not enough space available when setting a string.
*/
function FixedString (length, encoding, nullTerminate) {
if (!(this instanceof FixedString)) {
return new FixedString(length, encoding, nullTerminate);
}
this.size = length | 0;
if (this.size <= 0) {
throw new TypeError('fixed string requires a byte length!');
}
this.encoding = encoding;
//this.nullTerminate = Boolean(nullTerminate);
}
FixedString.prototype = Object.create(ref.types.char, {
constructor: {
value: FixedString,
enumerable: false,
writable: true,
configurable: true
}
});
FixedString.prototype.get = function (buffer, offset) {
var v = buffer.toString(this.encoding, offset, offset + this.size);
// strip at null terminator
var zero = v.indexOf('\0');
if (zero !== -1) {
return v.substring(0, zero);
} else {
return v;
}
};
FixedString.prototype.set = function (buffer, offset, value) {
var v = value + '\0'; // null terminate
var b = Buffer.byteLength(v, this.encoding);
if (this.size < b) {
throw new Error('string ' + JSON.stringify(value) + ' requires ' + b
+ ' bytes, but only ' + this.size + ' available');
}
buffer.write(v, offset, undefined, this.encoding);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment