Module: BinData::BitField
- Defined in:
- lib/bindata/bits.rb
Overview
Defines a number of classes that contain a bit based integer. The integer is defined by endian and number of bits.
Class Method Summary collapse
- .create_methods(bit_class, nbits, endian) ⇒ Object
-
.define_class(nbits, endian) ⇒ Object
:nodoc: all.
- .define_methods(bit_class, nbits, endian, clamp) ⇒ Object
Class Method Details
.create_methods(bit_class, nbits, endian) ⇒ Object
20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/bindata/bits.rb', line 20 def self.create_methods(bit_class, nbits, endian) min = 0 max = (1 << nbits) - 1 clamp = "val = (val < #{min}) ? #{min} : (val > #{max}) ? #{max} : val" # allow single bits to be used as booleans if nbits == 1 clamp = "val = (val == true) ? 1 : (not val) ? 0 : #{clamp}" end define_methods(bit_class, nbits, endian.to_s, clamp) end |
.define_class(nbits, endian) ⇒ Object
:nodoc: all
8 9 10 11 12 13 14 15 16 17 18 |
# File 'lib/bindata/bits.rb', line 8 def self.define_class(nbits, endian) name = "Bit#{nbits}" name += "le" if endian == :little BinData.module_eval <<-END class #{name} < BinData::BasePrimitive register(self.name, self) BitField.create_methods(self, #{nbits}, :#{endian.to_s}) end END end |
.define_methods(bit_class, nbits, endian, clamp) ⇒ Object
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 |
# File 'lib/bindata/bits.rb', line 33 def self.define_methods(bit_class, nbits, endian, clamp) bit_class.module_eval <<-END #--------------- private def _assign(val) #{clamp} super(val) end def _do_write(io) raise "can't write whilst reading \#{debug_name}" if @in_read io.writebits(_value, #{nbits}, :#{endian}) end def _do_num_bytes(ignored) #{nbits} / 8.0 end def read_and_return_value(io) io.readbits(#{nbits}, :#{endian}) end def sensible_default 0 end END end |