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

Class Method Details

.create_clamp_code(nbits) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/bindata/bits.rb', line 53

def create_clamp_code(nbits)
  min = 0
  max = (1 << nbits) - 1
  clamp = "val = (val < #{min}) ? #{min} : (val > #{max}) ? #{max} : val"

  if nbits == 1
    # allow single bits to be used as booleans
    "val = (val == true) ? 1 : (not val) ? 0 : #{clamp}"
  else
    clamp
  end
end

.define_class(nbits, endian) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/bindata/bits.rb', line 9

def define_class(nbits, endian)
  name = "Bit#{nbits}"
  name += "le" if endian == :little
  unless BinData.const_defined?(name)
    BinData.module_eval <<-END
      class #{name} < BinData::BasePrimitive
        register_self
        BitField.define_methods(self, #{nbits}, :#{endian})
      end
    END
  end

  BinData.const_get(name)
end

.define_methods(bit_class, nbits, endian) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/bindata/bits.rb', line 24

def define_methods(bit_class, nbits, endian)
  bit_class.module_eval <<-END
    #---------------
    private

    def _assign(val)
      #{create_clamp_code(nbits)}
      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
      #{nbits / 8.0}
    end

    def read_and_return_value(io)
      io.readbits(#{nbits}, :#{endian})
    end

    def sensible_default
      0
    end
  END
end