Class: Core::BaseX

Inherits:
Object
  • Object
show all
Defined in:
lib/core/base_x.rb

Direct Known Subclasses

Base58XRP

Instance Method Summary collapse

Constructor Details

#initialize(alphabet) ⇒ BaseX



4
5
6
7
8
9
# File 'lib/core/base_x.rb', line 4

def initialize(alphabet)
  @alphabet = alphabet
  @base = alphabet.length
  @alphabet_map = {}
  alphabet.chars.each_with_index { |char, index| @alphabet_map[char] = index }
end

Instance Method Details

#decode(string) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/core/base_x.rb', line 33

def decode(string)
  return '' if string.empty?

  bytes = [0]
  string.each_char do |char|
    raise ArgumentError, "Invalid character found: #{char}" unless @alphabet_map.key?(char)

    carry = @alphabet_map[char]
    bytes.each_with_index do |byte, i|
      carry += byte * @base
      bytes[i] = carry & 0xff
      carry >>= 8
    end

    while carry > 0 do
      bytes << (carry & 0xff)
      carry >>= 8
    end
  end

  string.chars.take_while { |char| char == @alphabet[0] }.each { bytes << 0 }
  bytes.reverse.pack('C*')
end

#encode(buffer) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/core/base_x.rb', line 11

def encode(buffer)
  return @alphabet[0] if buffer.empty?

  digits = [0]
  buffer.each_byte do |byte|
    carry = byte
    digits.each_with_index do |digit, i|
      carry += digit << 8
      digits[i] = (carry % @base).to_i
      carry = (carry / @base).abs.to_i
    end

    while carry > 0 do
      digits << (carry % @base).to_i
      carry = (carry / @base).abs.to_i
    end
  end

  buffer.each_byte.take_while { |byte| byte == 0 }.each { digits << 0 }
  digits.reverse.map { |digit| @alphabet[digit] }.join
end