Class: Klay::Rlp::Sedes::BigEndianInt

Inherits:
Object
  • Object
show all
Defined in:
lib/klay/rlp/sedes/big_endian_int.rb

Overview

A serializable, big-endian, unsigned integer type.

Instance Method Summary collapse

Constructor Details

#initialize(size = nil) ⇒ BigEndianInt

Create a serializable, big-endian, unsigned integer.

Parameters:

  • size (Integer) (defaults to: nil)

    the size of the big endian.



32
33
34
# File 'lib/klay/rlp/sedes/big_endian_int.rb', line 32

def initialize(size = nil)
  @size = size
end

Instance Method Details

#deserialize(serial) ⇒ Integer

Deserializes an unsigned integer.

Parameters:

  • serial (String)

    the serialized integer.

Returns:

  • (Integer)

    a number.

Raises:



57
58
59
60
61
62
# File 'lib/klay/rlp/sedes/big_endian_int.rb', line 57

def deserialize(serial)
  raise DeserializationError, "Invalid serialization (wrong size)" if @size && serial.size != @size
  raise DeserializationError, "Invalid serialization (not minimal length)" if !@size && serial.size > 0 && serial[0] == Constant::BYTE_ZERO
  serial = serial || Constant::BYTE_ZERO
  Util.big_endian_to_int(serial)
end

#serialize(obj) ⇒ String

Serialize a big-endian integer.

Parameters:

  • obj (Integer)

    the integer to be serialized.

Returns:

  • (String)

    a serialized big-endian integer.

Raises:



43
44
45
46
47
48
49
# File 'lib/klay/rlp/sedes/big_endian_int.rb', line 43

def serialize(obj)
  raise SerializationError, "Can only serialize integers" unless obj.is_a?(Integer)
  raise SerializationError, "Cannot serialize negative integers" if obj < 0
  raise SerializationError, "Integer too large (does not fit in #{@size} bytes)" if @size && obj >= 256 ** @size
  s = obj == 0 ? Constant::BYTE_EMPTY : Util.int_to_big_endian(obj)
  @size ? "#{Constant::BYTE_ZERO * [0, @size - s.size].max}#{s}" : s
end