1 # Copyright (C) 2011 Martin A. Hansen.
3 # This program is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU General Public License
5 # as published by the Free Software Foundation; either version 2
6 # of the License, or (at your option) any later version.
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software
15 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 # http://www.gnu.org/copyleft/gpl.html
19 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
21 # This software is part of the Biopieces framework (www.biopieces.org).
23 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
25 # Error class for all exceptions to do with Base36.
26 class Base36Error < StandardError; end
28 ALPH = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
31 # Class containing methods to encode and decode Base 36.
32 # Note that the ALPH is [alph + num] and not [num + alph]
33 # which prevents us from simply using .to_i(36) and .to_s(36).
35 # http://en.wikipedia.org/wiki/Base_36
37 # Method that encodes an integer into a base36 string
40 raise Base36Error unless num.is_a? Fixnum
45 base36 << ALPH[(num % BASE36)]
49 base36 << ALPH[0] if num == 0
54 # Method that decodes a base36 string and returns an integer.
55 def self.decode(base36)
56 raise Base36Error if base36.empty?
61 base36.upcase.reverse.each_char do |char|
62 result += ALPH.index(char) * (BASE36 ** pos)