lib/bitwise.rb in bitwise-0.3.1 vs lib/bitwise.rb in bitwise-0.4.0

- old
+ new

@@ -1,25 +1,21 @@ -# coding: ascii-8bit +# encoding: binary require 'bitwise/bitwise' class Bitwise attr_accessor :value - def initialize(value = "") - @value = value.force_encoding(Encoding::ASCII_8BIT) + def initialize(string = "") + self.raw = string end def size @value.bytesize end alias :to_s :size - def to_bits - @value.unpack('B*').first - end - def set_at(index) get_byte(index) @value.setbyte(@div, @byte | bitmask) end @@ -50,11 +46,11 @@ raise IndexError, 'out of bounds' if @div < 0 or @div >= @value.bytesize @byte = @value.getbyte(@div) end def not - Bitwise.new(Bitwise.string_not(self.value)) + Bitwise.new(Bitwise.string_not(self.raw)) end alias :~ :not def intersect(other) assign_max_and_min(other) @@ -73,40 +69,53 @@ Bitwise.new Bitwise.string_xor(@max, @min) end alias :^ :xor def assign_max_and_min(other) - @min, @max = [ self.value, other.value ].sort_by{|i| i.bytesize } + @min, @max = [ self.raw, other.raw ].sort_by{|i| i.bytesize } end - def value=(string) - @value = string.force_encoding(Encoding::ASCII_8BIT) + def bits + @value.unpack('B*').first + end + + def bits=(string) + @value = string.scan(/[01]{1,8}/).map do |slice| + (slice.bytesize == 8 ? slice : (slice + '0' * (8 - slice.bytesize))).to_i(2).chr + end.join @value.bytesize end + def raw + @value + end + + def raw=(string) + @value = string.force_encoding(Encoding::BINARY) + @value.bytesize + end + def indexes=(array) max_index = array.max @value = "\x00" * (max_index.div(8) + 1) array.each do |index| set_at(index) end - array.size + @value.bytesize end def indexes indexes = [] - position = 0 - @value.each_byte do |c| + @value.each_byte.with_index do |c, position| BITS_TABLE[c].each do |i| indexes << (position*8 + i) end - position += 1 end indexes end def cardinality - Bitwise.population_count(self.value) + Bitwise.population_count(self.raw) end BITS_TABLE = (0..255).map do |i| (0..7).map do |j| j = 7 - j