Class: Nl::Bitfield32

Inherits:
Object
  • Object
show all
Defined in:
nl/lib/nl/bitfield32.rb

Overview

A 32-bit value paired with a mask selecting the meaningful bits.

Constant Summary collapse

UINT32_RANGE =
(0...2**32)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value, selector) ⇒ Bitfield32

Returns a new instance of Bitfield32.

Parameters:

  • value (Integer)
  • selector (Integer)


17
18
19
20
21
22
23
24
25
26
# File 'nl/lib/nl/bitfield32.rb', line 17

def initialize(value, selector)
  validate_uint32(value, :value)
  validate_uint32(selector, :selector)
  if value & ~selector != 0
    raise ArgumentError, 'value contains bits which are not selected'
  end

  @value = value
  @selector = selector
end

Instance Attribute Details

#selector ⇒ Integer (readonly)

A 32-bit mask selecting the meaningful bits

Returns:

  • (Integer)


12
13
14
# File 'nl/lib/nl/bitfield32.rb', line 12

def selector
  @selector
end

#value ⇒ Integer (readonly)

A 32-bit flags

Returns:

  • (Integer)


8
9
10
# File 'nl/lib/nl/bitfield32.rb', line 8

def value
  @value
end

Instance Method Details

#[](index) ⇒ 0, ...

Returns 1 or 0 for a selected bit, or nil for an unselected bit.

Parameters:

  • index (Integer) —

    Bits are indexed from the least significant bit, starting at zero.

Returns:

  • (0, 1, nil)


32
33
34
35
36
37
# File 'nl/lib/nl/bitfield32.rb', line 32

def [](index)
  mask = bit_mask(index)
  return nil if selector & mask == 0

  value & mask == 0 ? 0 : 1
end

#[]=(index, state) ⇒ Object

Selects and sets or clears a bit. Assigning nil unselects it.

Parameters:

  • index (Integer) —

    Bits are indexed from the least significant bit, starting at zero.

  • state (0, 1, nil)


43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'nl/lib/nl/bitfield32.rb', line 43

def []=(index, state)
  mask = bit_mask(index)
  case state
  when 1
    @selector |= mask
    @value |= mask
  when 0
    @selector |= mask
    @value &= ~mask
  when nil
    @selector &= ~mask
    @value &= ~mask
  else
    raise TypeError, 'bit state must be 0, 1, or nil'
  end

  state
end