struct.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. /**
  2. * An interface for modeling and instantiating C-style data structures. This is
  3. * not a constructor per-say, but a constructor generator. It takes an array of
  4. * tuples, the left side being the type, and the right side being a field name.
  5. * The order should be the same order it would appear in the C-style struct
  6. * definition. It returns a function that can be used to construct an object that
  7. * reads and writes to the data structure using properties specified by the
  8. * initial field list.
  9. *
  10. * The only verboten field names are "ref", which is used used on struct
  11. * instances as a function to retrieve the backing Buffer instance of the
  12. * struct, and "ref.buffer" which contains the backing Buffer instance.
  13. *
  14. *
  15. * Example:
  16. *
  17. * ``` javascript
  18. * var ref = require('ref')
  19. * var Struct = require('ref-struct')
  20. *
  21. * // create the `char *` type
  22. * var charPtr = ref.refType(ref.types.char)
  23. * var int = ref.types.int
  24. *
  25. * // create the struct "type" / constructor
  26. * var PasswordEntry = Struct({
  27. * 'username': 'string'
  28. * , 'password': 'string'
  29. * , 'salt': int
  30. * })
  31. *
  32. * // create an instance of the struct, backed a Buffer instance
  33. * var pwd = new PasswordEntry()
  34. * pwd.username = 'ricky'
  35. * pwd.password = 'rbransonlovesnode.js'
  36. * pwd.salt = (Math.random() * 1000000) | 0
  37. *
  38. * pwd.username // → 'ricky'
  39. * pwd.password // → 'rbransonlovesnode.js'
  40. * pwd.salt // → 820088
  41. * ```
  42. */
  43. /**
  44. * Module dependencies.
  45. */
  46. var ref = require('ref')
  47. var util = require('util')
  48. var assert = require('assert')
  49. var debug = require('debug')('ref:struct')
  50. /**
  51. * Module exports.
  52. */
  53. module.exports = Struct
  54. /**
  55. * The Struct "type" meta-constructor.
  56. */
  57. function Struct () {
  58. debug('defining new struct "type"')
  59. /**
  60. * This is the "constructor" of the Struct type that gets returned.
  61. *
  62. * Invoke it with `new` to create a new Buffer instance backing the struct.
  63. * Pass it an existing Buffer instance to use that as the backing buffer.
  64. * Pass in an Object containing the struct fields to auto-populate the
  65. * struct with the data.
  66. */
  67. function StructType (arg, data) {
  68. if (!(this instanceof StructType)) {
  69. return new StructType(arg, data)
  70. }
  71. debug('creating new struct instance')
  72. var store
  73. if (Buffer.isBuffer(arg)) {
  74. debug('using passed-in Buffer instance to back the struct', arg)
  75. assert(arg.length >= StructType.size, 'Buffer instance must be at least ' +
  76. StructType.size + ' bytes to back this struct type')
  77. store = arg
  78. arg = data
  79. } else {
  80. debug('creating new Buffer instance to back the struct (size: %d)', StructType.size)
  81. store = new Buffer(StructType.size)
  82. }
  83. // set the backing Buffer store
  84. store.type = StructType
  85. this['ref.buffer'] = store
  86. if (arg) {
  87. for (var key in arg) {
  88. // hopefully hit the struct setters
  89. this[key] = arg[key]
  90. }
  91. }
  92. StructType._instanceCreated = true
  93. }
  94. // make instances inherit from the `proto`
  95. StructType.prototype = Object.create(proto, {
  96. constructor: {
  97. value: StructType
  98. , enumerable: false
  99. , writable: true
  100. , configurable: true
  101. }
  102. })
  103. StructType.defineProperty = defineProperty
  104. StructType.toString = toString
  105. StructType.fields = {}
  106. var opt = (arguments.length > 0 && arguments[1]) ? arguments[1] : {};
  107. // Setup the ref "type" interface. The constructor doubles as the "type" object
  108. StructType.size = 0
  109. StructType.alignment = 0
  110. StructType.indirection = 1
  111. StructType.isPacked = opt.packed ? Boolean(opt.packed) : false
  112. StructType.get = get
  113. StructType.set = set
  114. // Read the fields list and apply all the fields to the struct
  115. // TODO: Better arg handling... (maybe look at ES6 binary data API?)
  116. var arg = arguments[0]
  117. if (Array.isArray(arg)) {
  118. // legacy API
  119. arg.forEach(function (a) {
  120. var type = a[0]
  121. var name = a[1]
  122. StructType.defineProperty(name, type)
  123. })
  124. } else if (typeof arg === 'object') {
  125. Object.keys(arg).forEach(function (name) {
  126. var type = arg[name]
  127. StructType.defineProperty(name, type)
  128. })
  129. }
  130. return StructType
  131. }
  132. /**
  133. * The "get" function of the Struct "type" interface
  134. */
  135. function get (buffer, offset) {
  136. debug('Struct "type" getter for buffer at offset', buffer, offset)
  137. if (offset > 0) {
  138. buffer = buffer.slice(offset)
  139. }
  140. return new this(buffer)
  141. }
  142. /**
  143. * The "set" function of the Struct "type" interface
  144. */
  145. function set (buffer, offset, value) {
  146. debug('Struct "type" setter for buffer at offset', buffer, offset, value)
  147. var isStruct = value instanceof this
  148. if (isStruct) {
  149. // optimization: copy the buffer contents directly rather
  150. // than going through the ref-struct constructor
  151. value['ref.buffer'].copy(buffer, offset, 0, this.size)
  152. } else {
  153. if (offset > 0) {
  154. buffer = buffer.slice(offset)
  155. }
  156. new this(buffer, value)
  157. }
  158. }
  159. /**
  160. * Custom `toString()` override for struct type instances.
  161. */
  162. function toString () {
  163. return '[StructType]'
  164. }
  165. /**
  166. * Adds a new field to the struct instance with the given name and type.
  167. * Note that this function will throw an Error if any instances of the struct
  168. * type have already been created, therefore this function must be called at the
  169. * beginning, before any instances are created.
  170. */
  171. function defineProperty (name, type) {
  172. debug('defining new struct type field', name)
  173. // allow string types for convenience
  174. type = ref.coerceType(type)
  175. assert(!this._instanceCreated, 'an instance of this Struct type has already ' +
  176. 'been created, cannot add new "fields" anymore')
  177. assert.equal('string', typeof name, 'expected a "string" field name')
  178. assert(type && /object|function/i.test(typeof type) && 'size' in type &&
  179. 'indirection' in type
  180. , 'expected a "type" object describing the field type: "' + type + '"')
  181. assert(type.indirection > 1 || type.size > 0,
  182. '"type" object must have a size greater than 0')
  183. assert(!(name in this.prototype), 'the field "' + name +
  184. '" already exists in this Struct type')
  185. var field = {
  186. type: type
  187. }
  188. this.fields[name] = field
  189. // define the getter/setter property
  190. var desc = { enumerable: true , configurable: true }
  191. desc.get = function () {
  192. debug('getting "%s" struct field (offset: %d)', name, field.offset)
  193. return ref.get(this['ref.buffer'], field.offset, type)
  194. }
  195. desc.set = function (value) {
  196. debug('setting "%s" struct field (offset: %d)', name, field.offset, value)
  197. return ref.set(this['ref.buffer'], field.offset, value, type)
  198. }
  199. // calculate the new size and field offsets
  200. recalc(this)
  201. Object.defineProperty(this.prototype, name, desc)
  202. }
  203. function recalc (struct) {
  204. // reset size and alignment
  205. struct.size = 0
  206. struct.alignment = 0
  207. var fieldNames = Object.keys(struct.fields)
  208. // first loop through is to determine the `alignment` of this struct
  209. fieldNames.forEach(function (name) {
  210. var field = struct.fields[name]
  211. var type = field.type
  212. var alignment = type.alignment || ref.alignof.pointer
  213. if (type.indirection > 1) {
  214. alignment = ref.alignof.pointer
  215. }
  216. if (struct.isPacked) {
  217. struct.alignment = Math.min(struct.alignment || alignment, alignment)
  218. } else {
  219. struct.alignment = Math.max(struct.alignment, alignment)
  220. }
  221. })
  222. // second loop through sets the `offset` property on each "field"
  223. // object, and sets the `struct.size` as we go along
  224. fieldNames.forEach(function (name) {
  225. var field = struct.fields[name]
  226. var type = field.type
  227. if (null != type.fixedLength) {
  228. // "ref-array" types set the "fixedLength" prop. don't treat arrays like one
  229. // contiguous entity. instead, treat them like individual elements in the
  230. // struct. doing this makes the padding end up being calculated correctly.
  231. field.offset = addType(type.type)
  232. for (var i = 1; i < type.fixedLength; i++) {
  233. addType(type.type)
  234. }
  235. } else {
  236. field.offset = addType(type)
  237. }
  238. })
  239. function addType (type) {
  240. var offset = struct.size
  241. var align = type.indirection === 1 ? type.alignment : ref.alignof.pointer
  242. var padding = struct.isPacked ? 0 : (align - (offset % align)) % align
  243. var size = type.indirection === 1 ? type.size : ref.sizeof.pointer
  244. offset += padding
  245. if (!struct.isPacked) {
  246. assert.equal(offset % align, 0, "offset should align")
  247. }
  248. // adjust the "size" of the struct type
  249. struct.size = offset + size
  250. // return the calulated offset
  251. return offset
  252. }
  253. // any final padding?
  254. var left = struct.size % struct.alignment
  255. if (left > 0) {
  256. debug('additional padding to the end of struct:', struct.alignment - left)
  257. struct.size += struct.alignment - left
  258. }
  259. }
  260. /**
  261. * this is the custom prototype of Struct type instances.
  262. */
  263. var proto = {}
  264. /**
  265. * set a placeholder variable on the prototype so that defineProperty() will
  266. * throw an error if you try to define a struct field with the name "buffer".
  267. */
  268. proto['ref.buffer'] = ref.NULL
  269. /**
  270. * Flattens the Struct instance into a regular JavaScript Object. This function
  271. * "gets" all the defined properties.
  272. *
  273. * @api public
  274. */
  275. proto.toObject = function toObject () {
  276. var obj = {}
  277. Object.keys(this.constructor.fields).forEach(function (k) {
  278. obj[k] = this[k]
  279. }, this)
  280. return obj
  281. }
  282. /**
  283. * Basic `JSON.stringify(struct)` support.
  284. */
  285. proto.toJSON = function toJSON () {
  286. return this.toObject()
  287. }
  288. /**
  289. * `.inspect()` override. For the REPL.
  290. *
  291. * @api public
  292. */
  293. proto.inspect = function inspect () {
  294. var obj = this.toObject()
  295. // add instance's "own properties"
  296. Object.keys(this).forEach(function (k) {
  297. obj[k] = this[k]
  298. }, this)
  299. return util.inspect(obj)
  300. }
  301. /**
  302. * returns a Buffer pointing to this struct data structure.
  303. */
  304. proto.ref = function ref () {
  305. return this['ref.buffer']
  306. }