Class: Base32::Chunk

Inherits:
Object
  • Object
show all
Defined in:
lib/base32/chunk.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(bytes, alphabet = Base32::Alphabet::CHARS) ⇒ Chunk

Returns a new instance of Chunk.



7
8
9
10
# File 'lib/base32/chunk.rb', line 7

def initialize(bytes, alphabet = Base32::Alphabet::CHARS)
  @bytes    = bytes
  @alphabet = Base32::Alphabet.new alphabet
end

Instance Attribute Details

#alphabetObject (readonly)

Returns the value of attribute alphabet.



5
6
7
# File 'lib/base32/chunk.rb', line 5

def alphabet
  @alphabet
end

Class Method Details

.call(str, size, alphabet) ⇒ Object



12
13
14
15
16
17
18
19
20
# 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

Instance Method Details

#decodeObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
# 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

#encodeObject



37
38
39
40
41
42
43
44
45
46
47
48
# 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