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

Initializes a new BaseX instance with the given alphabet.

Parameters:

  • alphabet (String)

    The alphabet to use for encoding and decoding.



8
9
10
11
12
13
# File 'lib/core/base_x.rb', line 8

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) ⇒ String

Decodes a string into a byte string using the alphabet.

Parameters:

  • string (String)

    The string to decode.

Returns:

  • (String)

    The decoded byte string.



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/core/base_x.rb', line 43

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) ⇒ String

Encodes a byte array into a string using the alphabet.

Parameters:

  • buffer (String)

    The byte string to encode.

Returns:

  • (String)

    The encoded string.



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/core/base_x.rb', line 18

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