Class: FastExists::BitArray
- Inherits:
-
Object
- Object
- FastExists::BitArray
- Defined in:
- lib/fast_exists/bit_array.rb
Instance Attribute Summary collapse
-
#size ⇒ Object
readonly
Returns the value of attribute size.
Class Method Summary collapse
Instance Method Summary collapse
- #bytesize ⇒ Object
- #clear ⇒ Object
- #count_ones ⇒ Object (also: #popcount)
-
#initialize(size) ⇒ BitArray
constructor
A new instance of BitArray.
- #set(index) ⇒ Object
- #set?(index) ⇒ Boolean (also: #get)
- #to_s ⇒ Object
- #to_s_load(raw_bytes) ⇒ Object
Constructor Details
#initialize(size) ⇒ BitArray
Returns a new instance of BitArray.
9 10 11 12 13 14 15 16 |
# File 'lib/fast_exists/bit_array.rb', line 9 def initialize(size) raise InvalidArgumentError, "BitArray size must be positive" if size <= 0 @size = size @bytesize = (size + 7) / 8 @bytes = ("\x00" * @bytesize).b @mutex = Mutex.new end |
Instance Attribute Details
#size ⇒ Object (readonly)
Returns the value of attribute size.
7 8 9 |
# File 'lib/fast_exists/bit_array.rb', line 7 def size @size end |
Class Method Details
.from_s(raw_bytes, size) ⇒ Object
71 72 73 74 75 |
# File 'lib/fast_exists/bit_array.rb', line 71 def self.from_s(raw_bytes, size) bit_array = new(size) bit_array.to_s_load(raw_bytes) bit_array end |
Instance Method Details
#bytesize ⇒ Object
63 64 65 |
# File 'lib/fast_exists/bit_array.rb', line 63 def bytesize @bytesize end |
#clear ⇒ Object
42 43 44 45 46 47 |
# File 'lib/fast_exists/bit_array.rb', line 42 def clear @mutex.synchronize do @bytes = ("\x00" * @bytesize).b end true end |
#count_ones ⇒ Object Also known as: popcount
49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/fast_exists/bit_array.rb', line 49 def count_ones count = 0 @bytes.each_byte do |b| # Kernighan's popcount per byte while b > 0 count += 1 b &= (b - 1) end end count end |
#set(index) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/fast_exists/bit_array.rb', line 18 def set(index) validate_index!(index) byte_idx = index / 8 bit_idx = index % 8 @mutex.synchronize do current_byte = @bytes.getbyte(byte_idx) new_byte = current_byte | (1 << bit_idx) @bytes.setbyte(byte_idx, new_byte) end true end |
#set?(index) ⇒ Boolean Also known as: get
31 32 33 34 35 36 37 38 |
# File 'lib/fast_exists/bit_array.rb', line 31 def set?(index) validate_index!(index) byte_idx = index / 8 bit_idx = index % 8 byte = @bytes.getbyte(byte_idx) (byte & (1 << bit_idx)) != 0 end |
#to_s ⇒ Object
67 68 69 |
# File 'lib/fast_exists/bit_array.rb', line 67 def to_s @mutex.synchronize { @bytes.dup } end |
#to_s_load(raw_bytes) ⇒ Object
77 78 79 80 81 82 |
# File 'lib/fast_exists/bit_array.rb', line 77 def to_s_load(raw_bytes) @mutex.synchronize do raise InvalidArgumentError, "Byte length mismatch" if raw_bytes.bytesize != @bytesize @bytes = raw_bytes.dup.b end end |