hummus-recipe
Version:
A powerful PDF tool for NodeJS based on HummusJS
92 lines (66 loc) • 2.27 kB
text/coffeescript
Struct = require './Struct'
class VersionedStruct extends Struct
constructor: (, = {}) ->
if typeof is 'string'
= new Function('parent', "return parent.#{@type}")
= new Function('parent', 'version', "return parent.#{@type} = version")
decode: (stream, parent, length = 0) ->
res = stream, parent, length
if typeof is 'string'
res.version = parent
else
res.version = .decode(stream)
if .header
stream, res, .header
fields = [res.version]
if not fields?
throw new Error "Unknown version #{res.version}"
if fields instanceof VersionedStruct
return fields.decode(stream, parent)
stream, res, fields
?.call(res, stream)
return res
size: (val, parent, includePointers = true) ->
unless val
throw new Error 'Not a fixed size'
ctx =
parent: parent
val: val
pointerSize: 0
size = 0
if typeof isnt 'string'
size += .size(val.version, ctx)
if .header
for key, type of .header when type.size?
size += type.size(val[key], ctx)
fields = [val.version]
if not fields?
throw new Error "Unknown version #{val.version}"
for key, type of fields when type.size?
size += type.size(val[key], ctx)
if includePointers
size += ctx.pointerSize
return size
encode: (stream, val, parent) ->
?.call(val, stream)
ctx =
pointers: []
startOffset: stream.pos
parent: parent
val: val
pointerSize: 0
ctx.pointerOffset = stream.pos + (val, ctx, false)
if typeof isnt 'string'
.encode(stream, val.version)
if .header
for key, type of .header when type.encode?
type.encode(stream, val[key], ctx)
fields = [val.version]
for key, type of fields when type.encode?
type.encode(stream, val[key], ctx)
i = 0
while i < ctx.pointers.length
ptr = ctx.pointers[i++]
ptr.type.encode(stream, ptr.val, ptr.parent)
return
module.exports = VersionedStruct