class Base32::Chunk
Attributes
alphabet[R]
Public Class Methods
call(str, size, alphabet)
click to toggle source
# File lib/base32/chunk.rb, line 12 def self.call(str, size, alphabet) result = [] bytes = str.bytes while bytes.any? result << Chunk.new(bytes.take(size), alphabet) bytes = bytes.drop(size) end result end
new(bytes, alphabet = Base32::Alphabet::CHARS)
click to toggle source
# File lib/base32/chunk.rb, line 7 def initialize(bytes, alphabet = Base32::Alphabet::CHARS) @bytes = bytes @alphabet = Base32::Alphabet.new alphabet end
Public Instance Methods
decode()
click to toggle source
# File lib/base32/chunk.rb, line 22 def decode bytes = @bytes.take_while { |c| c != 61 } # strip padding n = (bytes.length * 5.0 / 8.0).floor p = bytes.length < 8 ? 5 - (n * 8) % 5 : 0 c = bytes.inject(0) do |m, o| i = alphabet.to_s.index(o.chr) raise ArgumentError, "invalid character '#{o.chr}'" if i.nil? (m << 5) + i end >> p (0..n - 1).to_a.reverse.collect { |i| ((c >> i * 8) & 0xff).chr } end
encode()
click to toggle source
# File lib/base32/chunk.rb, line 37 def encode n = (@bytes.length * 8.0 / 5.0).ceil p = n < 8 ? 5 - (@bytes.length * 8) % 5 : 0 c = @bytes.inject(0) { |m, o| (m << 8) + o } << p [ (0..n - 1).to_a.reverse.collect do |i| alphabet.to_s[(c >> i * 5) & 0x1f].chr end, ('=' * (8 - n)), ] end