structjs
Version:
**Structjs** allows mapping of contiguously allocated binary data to JavaScript objects for both Node.js and the Browser.
39 lines (31 loc) • 1.18 kB
JavaScript
var utils = require('../utils')
var StructNumber = module.exports = function(read, write, length) {
this.methods = { read: read, write: write }
Object.defineProperties(this, {
_offset: { value: null, writable: true },
_length: { value: null, writable: true }
})
utils.options.call(this, length)
}
StructNumber.prototype.with = function(opts) {
if (!opts.length) opts.length = this._length
return new StructNumber(this.methods.read, this.methods.write, opts)
}
StructNumber.prototype.from = function(offset) {
return this.with({ external: true, offset: offset })
}
StructNumber.prototype.read = function read(buffer, offset) {
var parent = read.caller.parent
return buffer[this.methods.read](this.external ? this.offsetFor(parent) : offset)
}
StructNumber.prototype.write = function write(buffer, offset, value) {
var parent = write.caller.parent
buffer[this.methods.write](this.external ? this.offsetFor(parent) : offset, value)
}
StructNumber.prototype.lengthFor = function() {
return 1
}
StructNumber.prototype.sizeFor = function() {
return this._length
}
utils.methodsFor(StructNumber.prototype, '_offset', 'offsetFor', 'setOffset')