Class: Bytemapper::Chunk

Inherits:
Hash
  • Object
show all
Includes:
Flattenable, Nameable
Defined in:
lib/bytemapper/chunk.rb

Instance Attribute Summary collapse

Attributes included from Nameable

#name, #names

Instance Method Summary collapse

Methods included from Flattenable

#flatten

Constructor Details

#initialize(bytes, shape, name) ⇒ Chunk

Returns a new instance of Chunk.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/bytemapper/chunk.rb', line 24

def initialize(bytes, shape, name)
  @name = name
  @shape = shape
  @bytes = bytes.is_a?(StringIO) ? bytes : StringIO.new(bytes)
  replace(shape)
  each_pair do |k,v|
    self[k] = if v.is_a?(Hash)
                Chunk.new(@bytes.read(v.size), v, k)
              elsif v.is_a?(Bytemapper::Table)
                if v.empty?
                  v.populate(@bytes.read(@bytes.size-@bytes.pos))
                else
                  v.populate(@bytes.read(v.capacity))
                end
              else
                unpack(v)
              end
    singleton_class.instance_eval { attr_reader k }
    instance_variable_set("@#{k.to_s}", self[k])
  end

  shape.hooks.each {|h| h.call(self) }
end

Instance Attribute Details

#bytesObject (readonly)

Returns the value of attribute bytes.



22
23
24
# File 'lib/bytemapper/chunk.rb', line 22

def bytes
  @bytes
end

#shapeObject (readonly)

Returns the value of attribute shape.



22
23
24
# File 'lib/bytemapper/chunk.rb', line 22

def shape
  @shape
end

Instance Method Details

#capacityObject



60
61
62
# File 'lib/bytemapper/chunk.rb', line 60

def capacity
  shape.size
end

#chrObject



56
57
58
# File 'lib/bytemapper/chunk.rb', line 56

def chr
  bytes.string.split(//).map(&:chr)
end

#consumedObject



68
69
70
# File 'lib/bytemapper/chunk.rb', line 68

def consumed
  size
end

#ordObject



52
53
54
# File 'lib/bytemapper/chunk.rb', line 52

def ord
  bytes.string.split(//).map(&:ord)
end

#remainingObject



72
73
74
# File 'lib/bytemapper/chunk.rb', line 72

def remaining
  capacity - consumed
end

#sizeObject



64
65
66
# File 'lib/bytemapper/chunk.rb', line 64

def size
  bytes.size
end

#stringObject



48
49
50
# File 'lib/bytemapper/chunk.rb', line 48

def string
  bytes.string
end

#unpack(value, endian = nil) ⇒ Object



76
77
78
79
80
# File 'lib/bytemapper/chunk.rb', line 76

def unpack(value, endian = nil)
  num_bytes, flag = value
  _bytes = bytes.read(num_bytes >> 3)
  _bytes.unpack("#{flag}#{endian}")[0] unless _bytes.nil?
end