Class: Xot::BitFlag

Inherits:
Object
  • Object
show all
Includes:
BitUtil
Defined in:
lib/xot/bit_flag.rb

Instance Method Summary collapse

Methods included from BitUtil

bit

Constructor Details

#initialize(auto: false, none: 0, **flags, &block) ⇒ BitFlag

Returns a new instance of BitFlag.



13
14
15
16
17
# File 'lib/xot/bit_flag.rb', line 13

def initialize(auto: false, none: 0, **flags, &block)
  @bit2sym, @sym2bit, @auto, @next = {}, {none: none, no: none}, auto, 1
  flags.each {|sym, value| flag sym, value}
  BlockUtil.instance_eval_or_block_call self, &block if block
end

Instance Method Details

#bits2symbols(bits) ⇒ Object



35
36
37
38
39
40
41
42
43
44
# File 'lib/xot/bit_flag.rb', line 35

def bits2symbols(bits)
  array = []
  bits.to_s(2).reverse.each_char.with_index do |char, index|
    next unless char == '1'
    symbol = @bit2sym[bit index]
    raise "unknown bit #{index} for flag." unless symbol
    array << symbol
  end
  array
end

#flag(symbol, value = nil, bit: nil) ⇒ Object

Raises:

  • (ArgumentError)


19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/xot/bit_flag.rb', line 19

def flag(symbol, value = nil, bit: nil)
  bit = value || make_bit(bit) || (@auto ? @next : nil)

  raise ArgumentError if !bit
  raise "flag: symbol #{symbol.inspect} or bit #{bit} is already registered." if
    @sym2bit.key?(symbol) || @bit2sym.key?(bit)

  single_bit = bit.to_s(2).count('1') == 1

  @sym2bit[symbol] = bit
  @bit2sym[bit]    = symbol   if single_bit
  @next            = bit << 1 if single_bit && bit >= @next

  bit
end

#symbols2bits(*symbols) ⇒ Object



46
47
48
# File 'lib/xot/bit_flag.rb', line 46

def symbols2bits(*symbols)
  symbols.flatten.reduce(0) {|value, symbol| value | sym2bit(symbol)}
end