manveru (owner)

Revisions

gist: 56877 Download_button fork
public
Public Clone URL: git://gist.github.com/56877.git
Embed All Files: show embed
base62.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
module Base62
  CHARS = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a
  MOD = CHARS.size # 62
 
  module_function
 
  def encode_packed(string)
    encode(string.unpack('H*').at(0).to_i(16))
  end
 
  def encode(fixnum)
    out = []
 
    while fixnum > 0
      fixnum, r = fixnum.divmod(MOD)
      out.unshift CHARS[r]
    end
 
    out.join
  end
 
  def decode_packed(string)
    [decode(string).to_s(16)].pack('H*')
  end
 
  def decode(string)
    out = 0
    string.scan(/./mn){|c| out = out * MOD + CHARS.index(c) }
    out
  end
end
 
eval(DATA.read) if __FILE__ == $0
__END__
require 'bacon'
Bacon.summary_on_exit
 
describe Base62 do
should 'encode' do
Base62.encode(999).should == 'qh'
end
 
should 'decode' do
Base62.decode('qh').should == 999
end
 
should 'encode_packed' do
Base62.encode_packed('Hello, World! - snake_case').
should == "ntNEbEbmiA66ycSlgi04nDKpZl1YZM1N7sf"
end
 
should 'decode_packed' do
Base62.decode_packed("ntNEbEbmiA66ycSlgi04nDKpZl1YZM1N7sf").
should == 'Hello, World! - snake_case'
end
end