Module: RLP::Encode

Includes:
Constant, Error, Utils
Included in:
RLP
Defined in:
lib/rlp/encode.rb

Constant Summary

Constants included from Utils

Utils::BINARY_ENCODING

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?, #bytes_to_str, #decode_hex, #encode_hex, #int_to_big_endian, #list?, make_immutable!, #primitive?, #str_to_bytes

Instance Method Details

#encode(obj, sedes: nil, infer_serializer: true, cache: false) ⇒ String

Encode a Ruby object in RLP format.

By default, the object is serialized in a suitable way first (using Sedes.infer) and then encoded. Serialization can be explicitly suppressed by setting Sedes.infer to ‘false` and not passing an alternative as `sedes`.

If ‘obj` has an attribute `_cached_rlp` (as, notably, Serializable) and its value is not `nil`, this value is returned bypassing serialization and encoding, unless `sedes` is given (as the cache is assumed to refer to the standard serialization which can be replaced by specifying `sedes`).

If ‘obj` is a Serializable and `cache` is true, the result of the encoding will be stored in `_cached_rlp` if it is empty and Serializable.make_immutable will be invoked on `obj`.

Raises:



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/rlp/encode.rb', line 43

def encode(obj, sedes: nil, infer_serializer: true, cache: false)
  return obj._cached_rlp if obj.is_a?(Sedes::Serializable) && obj._cached_rlp && sedes.nil?

  really_cache = obj.is_a?(Sedes::Serializable) && sedes.nil? && cache

  if sedes
    item = sedes.serialize(obj)
  elsif infer_serializer
    item = Sedes.infer(obj).serialize(obj)
  else
    item = obj
  end

  result = encode_raw(item)

  if really_cache
    obj._cached_rlp = result
    obj.make_immutable!
  end

  result
end