Sha256: 9fe5a1ea24a6e06ab389c7e7b6540f86891e2ae03b3804a49bd32448f2e57740
Contents?: true
Size: 1.23 KB
Versions: 2
Compression:
Stored size: 1.23 KB
Contents
class Anybase attr_reader :chars UnrecognizedCharacterError = Class.new(RuntimeError) def initialize(chars, opts = nil) @chars = chars @ignore_case = opts && opts[:ignore_case] || false @char_map = Hash.new{|h,k| raise UnrecognizedCharacterError.new("the character `#{k.chr}' is not included in #{@chars}")} @num_map = {} @chars.split('').each_with_index do |c, i| if @ignore_case @char_map[c[0]] = i @char_map[c.swapcase[0]] = i else @char_map[c[0]] = i end @num_map[i] = c end end def to_i(val) num = 0 (0...val.size).each{|i| num += (chars.size ** (val.size - i - 1)) * @char_map[val[i]] } num end def to_native(val) str = '' until val.zero? digit = val % chars.size val /= chars.size str[0, 0] = @num_map[digit] end str end Hex = Anybase.new('0123456789abcdef', :ignore_case => true) Base64 = Anybase.new('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/') Base64ForURL = Anybase.new('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_') Base62 = Anybase.new('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') end
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
anybase-0.0.2 | lib/anybase.rb |
anybase-0.0.1 | lib/anybase.rb |