UNPKG

structjs

Version:

**Structjs** allows mapping of contiguously allocated binary data to JavaScript objects for both Node.js and the Browser.

55 lines (47 loc) 1.97 kB
var utils = require('../utils') , StructReference = require('./reference') var StructString = module.exports = function(length) { Object.defineProperties(this, { _offset: { value: null, writable: true }, _length: { value: null, writable: true }, _size: { value: null, writable: true } }) utils.options.call(this, length) } StructString.prototype.read = function read(buffer, offset) { var str = [], storage, parent = read.caller.parent , shift = this.external ? this.offsetFor(parent) : (this.storage ? offset + this.offsetFor(parent) : offset) for (var i = 0, len = this.lengthFor(parent), step = this.sizeFor() === 2 ? 2 : 1; i < len; ++i) { str.push(buffer[this.sizeFor() === 2 ? 'getUint16' : 'getUint8'](shift + i * step, this.littleEndian)) } return String.fromCharCode.apply(null, str) } StructString.prototype.write = function write(buffer, offset, value) { var str = [], storage, parent = write.caller.parent , shift = this.external ? this.offsetFor(parent) : (this.storage ? offset + this.offsetFor(parent) : offset) this.setLength(this.lengthFor(parent, true), parent) for (var i = 0, len = this.lengthFor(parent), step = this.sizeFor() === 2 ? 2 : 1; i < len; ++i) { var code = value.charCodeAt(i) || 0x00 buffer[this.sizeFor() === 2 ? 'setUint16' : 'setUint8'](shift + i * step, code, this.littleEndian) } } StructString.prototype.sizeFor = function() { return this._size || 1 } StructString.prototype.lengthFor = function(parent, writing) { if (this._length instanceof StructReference) { if (writing) return parent[this.prop].length return parent[this._length.prop] } return this._length || 0 } StructString.prototype.setLength = function(value, parent) { if (this._length instanceof StructReference) parent[this._length.prop] = value else this._length = value } utils.methodsFor(StructString.prototype, '_offset', 'offsetFor', 'setOffset')