Class: RLP::Sedes::BigEndianInt

Inherits:
Object
  • Object
show all
Includes:
Constant, Error, Utils
Defined in:
lib/rlp/sedes/big_endian_int.rb

Constant Summary

Constants included from Constant

Constant::BYTE_EMPTY, Constant::BYTE_ZERO, Constant::LIST_PREFIX_OFFSET, Constant::LONG_LENGTH_LIMIT, Constant::PRIMITIVE_PREFIX_OFFSET, Constant::SHORT_LENGTH_LIMIT

Instance Method Summary collapse

Methods included from Utils

#big_endian_to_int, #bytes_to_str, #encode_hex, #int_to_big_endian, #list?, make_immutable!, #primitive?, #str_to_bytes

Constructor Details

#initialize(size = nil) ⇒ BigEndianInt

Returns a new instance of BigEndianInt.


8
9
10
# File 'lib/rlp/sedes/big_endian_int.rb', line 8

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

Instance Method Details

#deserialize(serial) ⇒ Object


26
27
28
29
30
31
32
# File 'lib/rlp/sedes/big_endian_int.rb', line 26

def deserialize(serial)
  raise DeserializationError.new("Invalid serialization (wrong size)", serial) if @size && serial.size != @size
  raise DeserializationError.new("Invalid serialization (not minimal length)", serial) if !@size && serial.size > 0 && serial[0] == BYTE_ZERO

  serial = serial || BYTE_ZERO
  big_endian_to_int(serial)
end

#serialize(obj) ⇒ Object

Raises:


12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/rlp/sedes/big_endian_int.rb', line 12

def serialize(obj)
  raise SerializationError.new("Can only serialize integers", obj) unless obj.is_a?(Integer)
  raise SerializationError.new("Cannot serialize negative integers", obj) if obj < 0

  if @size && obj >= 256**@size
    msg = "Integer too large (does not fit in #{@size} bytes)"
    raise SerializationError.new(msg, obj)
  end

  s = obj == 0 ? BYTE_EMPTY : int_to_big_endian(obj)

  @size ? "#{BYTE_ZERO * [0, @size-s.size].max}#{s}" : s
end