Class: Multibases::Base32::Chunk
- Inherits:
-
Object
- Object
- Multibases::Base32::Chunk
- Defined in:
- lib/multibases/base32.rb
Instance Method Summary collapse
- #decode ⇒ Object
- #encode ⇒ Object
-
#initialize(bytes, table) ⇒ Chunk
constructor
A new instance of Chunk.
Constructor Details
#initialize(bytes, table) ⇒ Chunk
Returns a new instance of Chunk.
49 50 51 52 |
# File 'lib/multibases/base32.rb', line 49 def initialize(bytes, table) @bytes = bytes @table = table end |
Instance Method Details
#decode ⇒ Object
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/multibases/base32.rb', line 54 def decode bytes = @bytes.take_while { |c| c != @table.padder } 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 = @table.index(o) raise ArgumentError, "Invalid character '#{[o].pack('C*')}'" if i.nil? (m << 5) + i end >> p (0..(n - 1)).to_a.reverse.collect { |i| ((c >> i * 8) & 0xff) } end |
#encode ⇒ Object
70 71 72 73 74 75 76 77 78 79 |
# File 'lib/multibases/base32.rb', line 70 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 output = (0..(n - 1)).to_a.reverse.collect do |i| @table.ord_at((c >> i * 5) & 0x1f) end @table.padder ? output + Array.new((8 - n), @table.padder) : output end |