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