Class: Multibases::Base2
- Inherits:
-
Object
- Object
- Multibases::Base2
- Defined in:
- lib/multibases/base2.rb
Defined Under Namespace
Classes: Table
Constant Summary collapse
- Default =
Base2.new('01')
Class Method Summary collapse
Instance Method Summary collapse
- #decodable?(encoded) ⇒ Boolean
- #decode(encoded) ⇒ Object
- #default? ⇒ Boolean
- #encode(plain) ⇒ Object
- #eql?(other) ⇒ Boolean (also: #==)
-
#initialize(alphabet, strict: false, encoding: nil) ⇒ Base2
constructor
A new instance of Base2.
- #inspect ⇒ Object
- #table_ords(force_strict: false) ⇒ Object
Constructor Details
Class Method Details
.decode(packed) ⇒ Object
20 21 22 23 24 |
# File 'lib/multibases/base2.rb', line 20 def self.decode(packed) packed = packed.pack('C*') if packed.is_a?(Array) # Pack only works on an array with a single bit string DecodedByteArray.new(Array(String(packed)).pack('B*').bytes) end |
.encode(plain) ⇒ Object
12 13 14 15 16 17 18 |
# File 'lib/multibases/base2.rb', line 12 def self.encode(plain) plain = plain.pack('C*') if plain.is_a?(Array) EncodedByteArray.new( plain.unpack1('B*').bytes, encoding: Encoding::US_ASCII ) end |
Instance Method Details
#decodable?(encoded) ⇒ Boolean
93 94 95 |
# File 'lib/multibases/base2.rb', line 93 def decodable?(encoded) (encoded.uniq - @table.tr_ords).length.zero? end |
#decode(encoded) ⇒ Object
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
# File 'lib/multibases/base2.rb', line 61 def decode(encoded) return DecodedByteArray::EMPTY if encoded.empty? unless encoded.is_a?(Array) encoded = encoded.force_encoding(@table.encoding).bytes end unless decodable?(encoded) raise ArgumentError, "'#{encoded}' contains unknown characters'" end unless default? encoded = ByteArray.new(encoded).transcode( table_ords, Default.table_ords(force_strict: @table.strict?), encoding: Encoding::US_ASCII ) end Multibases::Base2.decode(encoded) end |
#default? ⇒ Boolean
83 84 85 |
# File 'lib/multibases/base2.rb', line 83 def default? eql?(Default) end |
#encode(plain) ⇒ Object
50 51 52 53 54 55 56 57 58 59 |
# File 'lib/multibases/base2.rb', line 50 def encode(plain) encoded = Multibases::Base2.encode(plain) return encoded if default? encoded.transcode( Default.table_ords(force_strict: @table.strict?), table_ords, encoding: @table.encoding ) end |
#eql?(other) ⇒ Boolean Also known as: ==
87 88 89 |
# File 'lib/multibases/base2.rb', line 87 def eql?(other) other.is_a?(Base2) && other.instance_variable_get(:@table) == @table end |
#inspect ⇒ Object
8 9 10 |
# File 'lib/multibases/base2.rb', line 8 def inspect "[Multibases::Base2 alphabet=\"#{@table.alphabet}\"]" end |
#table_ords(force_strict: false) ⇒ Object
97 98 99 |
# File 'lib/multibases/base2.rb', line 97 def table_ords(force_strict: false) @table.tr_ords(force_strict: force_strict) end |