Class: FixedLayoutMapper::Mapper::Layout

Inherits:
Object
  • Object
show all
Defined in:
lib/fixed-layout-mapper.rb

Instance Method Summary collapse

Constructor Details

#initialize(length_condition) ⇒ Layout

Returns a new instance of Layout.



81
82
83
84
85
# File 'lib/fixed-layout-mapper.rb', line 81

def initialize(length_condition)
  @length_condition = length_condition
  @layout = []
  @length = nil
end

Instance Method Details

#add(sym, mapper) ⇒ Object



91
92
93
# File 'lib/fixed-layout-mapper.rb', line 91

def add(sym, mapper)
  @layout << [sym, mapper]
end

#calc_lengthObject



99
100
101
102
103
# File 'lib/fixed-layout-mapper.rb', line 99

def calc_length
  @layout.inject(0) do |acc, (sym, mapper)|
    acc += mapper.length
  end
end

#lengthObject



95
96
97
# File 'lib/fixed-layout-mapper.rb', line 95

def length
  @length ||= calc_length
end

#map(bytes, result_class) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/fixed-layout-mapper.rb', line 105

def map(bytes, result_class)
  case @length_condition
  when LENGTH_CONDITION_STRICT
    raise "byte length is invalid" unless bytes.length == length
  when LENGTH_CONDITION_ALLOW_LONG
    raise "byte length is too short" if bytes.length < length
  else
    raise "unknown LENGTH_CONDIGION #{@length_condition}"
  end
  
  obj = result_class.new
  rest = @layout.inject(bytes) do |acc, (sym, mapper)|
    value, acc = mapper.map(acc)
    obj[sym] = value
    acc
  end
  [obj, rest]
end

#symsObject



87
88
89
# File 'lib/fixed-layout-mapper.rb', line 87

def syms
  @layout.map{|e| e[0]}
end