Sha256: f1897fae79e2039093ecd4e85c890101fef626b069bc4e6b0c8b620e75e604c0
Contents?: true
Size: 1.19 KB
Versions: 2
Compression:
Stored size: 1.19 KB
Contents
# frozen_string_literal: true module Base32 class Chunk attr_reader :alphabet def initialize(bytes, alphabet = Base32::Alphabet::CHARS) @bytes = bytes @alphabet = Base32::Alphabet.new alphabet end 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 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 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 end end
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
base32.rb-0.4.2 | lib/base32/chunk.rb |
base32.rb-0.4.1 | lib/base32/chunk.rb |