Class: Multibases::IndexedOrdTable

Inherits:
OrdTable
  • Object
show all
Defined in:
lib/multibases/ord_table.rb

Direct Known Subclasses

Base32::Table, BaseX::Table

Instance Attribute Summary

Attributes inherited from OrdTable

#base, #encoding, #factor, #padder

Instance Method Summary collapse

Methods inherited from OrdTable

#alphabet, #eql?, #hash, #strict?, #tr_ords

Constructor Details

#initialize(ords, **opts) ⇒ IndexedOrdTable

Returns a new instance of IndexedOrdTable.



90
91
92
93
94
95
96
# File 'lib/multibases/ord_table.rb', line 90

def initialize(ords, **opts)
  super(ords, **opts)

  @forward = ords.each_with_index.to_h
  @backward = Hash[@forward.to_a.collect(&:reverse)]
  @factor = Math.log(256) / Math.log(base)
end

Instance Method Details

#decoded_length(encoded_bytes) ⇒ Object



117
118
119
# File 'lib/multibases/ord_table.rb', line 117

def decoded_length(encoded_bytes)
  (encoded_bytes.length / factor).round
end

#decoded_zeroes_length(count) ⇒ Object



129
130
131
132
133
134
135
# File 'lib/multibases/ord_table.rb', line 129

def decoded_zeroes_length(count)
  # For power of 2 bases, add "canonical-width"
  return (count / factor).round if pad_to_power?

  # For other bases, add a equivalent count to front
  count
end

#encoded_length(plain_bytes) ⇒ Object



113
114
115
# File 'lib/multibases/ord_table.rb', line 113

def encoded_length(plain_bytes)
  (plain_bytes.length.to_f * factor).ceil
end

#encoded_zeroes_length(count) ⇒ Object



121
122
123
124
125
126
127
# File 'lib/multibases/ord_table.rb', line 121

def encoded_zeroes_length(count)
  # For power of 2 bases, add "canonical-width"
  return (factor * count).floor if pad_to_power?

  # For other bases, add a equivalent count to front
  count
end

#index(byte) ⇒ Object



102
103
104
105
106
107
# File 'lib/multibases/ord_table.rb', line 102

def index(byte)
  @forward[byte] || !strict? && (
    @forward[byte.chr.upcase.ord] ||
    @forward[byte.chr.downcase.ord]
  )
end

#ord_at(index) ⇒ Object



109
110
111
# File 'lib/multibases/ord_table.rb', line 109

def ord_at(index)
  @backward[index]
end

#pad_to_power?Boolean

Returns:

  • (Boolean)


137
138
139
# File 'lib/multibases/ord_table.rb', line 137

def pad_to_power?
  (Math.log2(base) % 1).zero?
end

#zeroObject



98
99
100
# File 'lib/multibases/ord_table.rb', line 98

def zero
  @backward[0]
end