Module: IrcDH1080::Base64
- Defined in:
- lib/ircdh1080/base64.rb
Constant Summary collapse
- B64 =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.freeze
Class Method Summary collapse
Class Method Details
.decode(str) ⇒ Object
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 57 58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/ircdh1080/base64.rb', line 31 def self.decode(str) l = str.bytesize return str if l < 2 buf = [0] * 256 B64.each_byte.with_index { |x,i| buf[x] = i } str.reverse.each_byte do |x,i| break if buf[x] == 0 l -= 1 end return str if l < 2 d = [0] * l i, k = 0, 0 while true break unless k + 1 < l d[i] = (buf[str[k].ord] << 2) % 0x100 d[i] |= buf[str[k+=1].ord] >> 4 break unless k + 1 < l i += 1 d[i] = (buf[str[k].ord] << 4) % 0x100 d[i] |= buf[str[k+=1].ord] >> 2 break unless k + 1 < l i += 1 d[i] = (buf[str[k].ord] << 6) % 0x100 d[i] |= buf[str[k+=1].ord] % 0x100 i += 1 k += 1 end d[0,i].map { |x| x.chr }.join('') end |
.encode(bin) ⇒ Object
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 |
# File 'lib/ircdh1080/base64.rb', line 5 def self.encode(bin) str = '' i, j, t, m = 0, 0, 0, 0x80 l = bin.bytesize * 8 while i < l t |= 1 unless bin[i>>3].ord & m == 0 j += 1 m >>= 1 m = 0x80 if m == 0 if j % 6 == 0 str += B64[t] t &= 0 end t = (t << 1) % 0x100 i += 1 end m = 5 - (j % 6) str += B64[(t << m) % 0x100] unless m == 0 str end |