Class: Base32::Chunk
- Inherits:
-
Object
- Object
- Base32::Chunk
- Defined in:
- lib/base32.rb
Instance Method Summary collapse
- #decode ⇒ Object
- #encode ⇒ Object
-
#initialize(bytes) ⇒ Chunk
constructor
A new instance of Chunk.
Constructor Details
#initialize(bytes) ⇒ Chunk
Returns a new instance of Chunk.
13 14 15 |
# File 'lib/base32.rb', line 13 def initialize(bytes) @bytes = bytes end |
Instance Method Details
#decode ⇒ Object
17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/base32.rb', line 17 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 = Base32.table.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 ⇒ Object
29 30 31 32 33 34 35 |
# File 'lib/base32.rb', line 29 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 {|i| Base32.table[(c >> i * 5) & 0x1f].chr}, ("=" * (8-n))] end |