Class: Base32::Chunk
- Inherits:
-
Object
- Object
- Base32::Chunk
- Defined in:
- lib/base32/chunk.rb
Instance Attribute Summary collapse
-
#alphabet ⇒ Object
readonly
Returns the value of attribute alphabet.
Class Method Summary collapse
Instance Method Summary collapse
- #decode ⇒ Object
- #encode ⇒ Object
-
#initialize(bytes, alphabet = Base32::Alphabet::CHARS) ⇒ Chunk
constructor
A new instance of Chunk.
Constructor Details
Instance Attribute Details
#alphabet ⇒ Object (readonly)
Returns the value of attribute alphabet.
5 6 7 |
# File 'lib/base32/chunk.rb', line 5 def alphabet @alphabet end |
Class Method Details
Instance Method Details
#decode ⇒ Object
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 |
#encode ⇒ Object
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 |