Last active
June 3, 2022 13:26
-
-
Save TooTallNate/80ac2d94b950216a2705 to your computer and use it in GitHub Desktop.
Fixed length "Buffer" type, for use in `ref-struct` type definitions.
This file contains hidden or 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
var ref = require('ref'); | |
module.exports = BufferType; | |
/** | |
* Fixed length "Buffer" type, for use in Struct type definitions. | |
* | |
* Optionally setting the `encoding` param will force to call | |
* `toString(encoding)` on the buffer returning a String instead. | |
*/ | |
function BufferType (length, encoding) { | |
if (!(this instanceof BufferType)) return new BufferType(length); | |
this.size = length | 0; | |
this.encoding = encoding || null; | |
} | |
BufferType.prototype = Object.create(ref.types.byte, { | |
constructor: { | |
value: BufferType, | |
enumerable: false, | |
writable: true, | |
configurable: true | |
} | |
}); | |
BufferType.prototype.get = function (buffer, offset) { | |
var buf = buffer.slice(offset, offset + this.size); | |
if (this.encoding !== null) { | |
buf = buf.toString(this.encoding); | |
} | |
return buf; | |
}; | |
BufferType.prototype.set = function (buffer, offset, value) { | |
if ('string' === typeof value || Array.isArray(value)) { | |
value = new Buffer(value, this.encoding); | |
} else if (!Buffer.isBuffer(value)) { | |
throw new TypeError('Buffer instance expected'); | |
} | |
if (value.length > this.size) { | |
throw new Error('Buffer given is ' + value.length + ' bytes, but only ' | |
+ this.size + ' bytes available'); | |
} | |
value.copy(buffer, offset); | |
}; |
Hi zacharyabresch,
I use the piece of code below, at least I got '\u0000's attached to the end of useful characters, then I guess it shouldn't be too hard to trim the useful part.
headings":["heading 0000000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000"]
const rowData = new T.RowData({row_id:0});
var property0 = Buffer.alloc(32);
Buffer.from("row 0 propety 0 aaaaa").copy(property0);
rowData.property0 = property0;
struct definition:
const RowData = refStruct({
row_id: 'int',
key: 'long',
property0: refBufferType(ROW_STRING_MAX_LEN),
property1: refBufferType(ROW_STRING_MAX_LEN),
property2: refBufferType(ROW_STRING_MAX_LEN),
property3: refBufferType(ROW_STRING_MAX_LEN)
});
I need the same class but typescript
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Any thoughts?