Class: Rlp::Sedes::Binary
- Inherits:
-
Object
- Object
- Rlp::Sedes::Binary
- Defined in:
- lib/rlp-lite/sedes/binary.rb
Overview
A sedes type for binary values.
Class Method Summary collapse
-
.fixed_length(l, allow_empty: false) ⇒ Eth::Rlp::Sedes::Binary
Create a serializable binary of fixed size.
-
.valid_type?(obj) ⇒ Boolean
Checks wether the given object is of a valid binary type.
Instance Method Summary collapse
-
#deserialize(serial) ⇒ String
Deserializes a binary.
-
#initialize(min_length: 0, max_length: INFINITY, allow_empty: false) ⇒ Binary
constructor
Create a serializable binary of variable size.
-
#serialize(obj) ⇒ Object
Serializes a binary.
-
#valid_length?(length) ⇒ Boolean
Checks wether the given length fits the defined size boundaries of the binary type.
Constructor Details
#initialize(min_length: 0, max_length: INFINITY, allow_empty: false) ⇒ Binary
Create a serializable binary of variable size.
32 33 34 35 36 |
# File 'lib/rlp-lite/sedes/binary.rb', line 32 def initialize( min_length: 0, max_length: INFINITY, allow_empty: false ) @min_length = min_length @max_length = max_length @allow_empty = allow_empty end |
Class Method Details
.fixed_length(l, allow_empty: false) ⇒ Eth::Rlp::Sedes::Binary
Create a serializable binary of fixed size.
12 13 14 15 16 |
# File 'lib/rlp-lite/sedes/binary.rb', line 12 def self.fixed_length( l, allow_empty: false ) new( min_length: l, max_length: l, allow_empty: allow_empty ) end |
.valid_type?(obj) ⇒ Boolean
Checks wether the given object is of a valid binary type.
22 23 24 |
# File 'lib/rlp-lite/sedes/binary.rb', line 22 def self.valid_type?( obj ) obj.instance_of?( String ) end |
Instance Method Details
#deserialize(serial) ⇒ String
Deserializes a binary.
61 62 63 64 65 |
# File 'lib/rlp-lite/sedes/binary.rb', line 61 def deserialize(serial) raise DeserializationError, "Objects of type #{serial.class} cannot be deserialized" unless serial.instance_of?(String) raise DeserializationError, "#{serial.class} has invalid length" unless valid_length?( serial.size ) serial end |
#serialize(obj) ⇒ Object
Serializes a binary.
44 45 46 47 48 49 50 51 52 |
# File 'lib/rlp-lite/sedes/binary.rb', line 44 def serialize( obj ) raise SerializationError, "Object is not a serializable (#{obj.class})" unless self.class.valid_type?( obj ) ## make sure string is with binary encoding (ASCII-8BIT) ## note: was Util.str_to_bytes( obj ) serial = obj.encoding.name == 'ASCII-8BIT' ? obj : obj.b raise SerializationError, "Object has invalid length" unless valid_length?( serial.size ) serial end |
#valid_length?(length) ⇒ Boolean
Checks wether the given length fits the defined size boundaries of the binary type.
72 73 74 75 |
# File 'lib/rlp-lite/sedes/binary.rb', line 72 def valid_length?( length ) (@min_length <= length && length <= @max_length) || (@allow_empty && length == 0) end |