Class: Depix::Binary::Fields::CharField

Inherits:
Field
  • Object
show all
Defined in:
lib/depix/binary/fields.rb

Overview

null-terminated string field with fixed padding

Direct Known Subclasses

BlankingField

Instance Attribute Summary

Attributes inherited from Field

#desc, #length, #name, #req

Instance Method Summary collapse

Methods inherited from Field

#consume!, #explain

Constructor Details

#initialize(opts = {}) ⇒ CharField

Returns a new instance of CharField.



207
208
209
# File 'lib/depix/binary/fields.rb', line 207

def initialize(opts = {})
  super({:length => 1}.merge(opts))
end

Instance Method Details

#clean(v) ⇒ Object



215
216
217
218
219
220
# File 'lib/depix/binary/fields.rb', line 215

def clean(v)
  # Use the pack->unpack trick to remove null-termination
  v = pack(v.to_s).unpack(pattern)[0]
  # Blanked fields are 0xFF all the way
  blanking?(v) ? nil : v
end

#pack(value) ⇒ Object



231
232
233
234
235
236
237
# File 'lib/depix/binary/fields.rb', line 231

def pack(value)
  unless blanking?(value)
    [value].pack(pattern)
  else
    0xFF.chr * length
  end
end

#patternObject



211
212
213
# File 'lib/depix/binary/fields.rb', line 211

def pattern
  "Z#{length}"
end

#rtypeObject



222
223
224
# File 'lib/depix/binary/fields.rb', line 222

def rtype
  String
end

#validate!(value) ⇒ Object



226
227
228
229
# File 'lib/depix/binary/fields.rb', line 226

def validate!(value)
  super(value)
  raise "#{value} overflows the #{length} bytes allocated" if !value.nil? && value.length > length
end