Module: RLP::Encode

Includes:
Constant, Error, Utils
Included in:
RLP
Defined in:
lib/rlp/encode.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?, #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`.

Parameters:

  • obj (Object)

    object to encode

  • sedes (#serialize(obj)) (defaults to: nil)

    an object implementing a function ‘serialize(obj)` which will be used to serialize `obj` before encoding, or `nil` to use the infered one (if any)

  • infer_serializer (Boolean) (defaults to: true)

    if ‘true` an appropriate serializer will be selected using Sedes.infer to serialize `obj` before encoding

  • cache (Boolean) (defaults to: false)

    cache the return value in ‘obj._cached_rlp` if possible and make `obj` immutable (default `false`)

Returns:

  • (String)

    the RLP encoded item

Raises:



41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/rlp/encode.rb', line 41

def encode(obj, sedes: nil, infer_serializer: true, cache: false)
  # TODO: cache flow

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

  result = encode_raw(item)
  result
end