Module: Ciri::RLP::Encode

Included in:
Ciri::RLP, Serializable::Schema
Defined in:
lib/ciri/rlp/encode.rb

Defined Under Namespace

Classes: InputOverflow

Instance Method Summary collapse

Instance Method Details

#encode(input, type = nil) ⇒ Object

Encode input to rlp encoding

Examples:

Ciri::RLP.encode("hello world")


37
38
39
# File 'lib/ciri/rlp/encode.rb', line 37

def encode(input, type = nil)
  type ? encode_with_type(input, type) : encode_simple(input)
end

#encode_simple(input) ⇒ Object



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

def encode_simple(input)
  if input.is_a?(Array)
    encode_list(input) {|i| encode_simple(i)}
  elsif input.is_a?(Integer)
    encode_with_type(input, Integer)
  elsif input.class.respond_to?(:rlp_encode)
    input.class.rlp_encode(input)
  else
    encode_with_type(input, Raw)
  end
end

#encode_with_type(item, type, zero: '') ⇒ Object

Use this method before RLP.encode, this method encode ruby objects to rlp friendly format, string or array. see Ciri::RLP::Serializable::TYPES for supported types

Examples:

item = Ciri::RLP.encode_with_type(number, :int, zero: "\x00".b)
encoded_text = Ciri::RLP.encode(item)


61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/ciri/rlp/encode.rb', line 61

def encode_with_type(item, type, zero: '')
  if type == Integer
    if item == 0
      "\x80".b
    elsif item < 0x80
      Ciri::Utils.big_endian_encode(item, zero)
    else
      buf = Ciri::Utils.big_endian_encode(item, zero)
      [0x80 + buf.size].pack("c*") + buf
    end
  elsif type == Bool
    item ? Bool::ENCODED_TRUE : Bool::ENCODED_FALSE
  elsif type.is_a?(Class) && type.respond_to?(:rlp_encode)
    type.rlp_encode(item)
  elsif type.is_a?(Array)
    if type.size == 1 # array type
      encode_list(item) {|i| encode_with_type(i, type[0])}
    else # unknown
      raise RLP::InvalidValueError.new "type size should be 1, got #{type}"
    end
  elsif type == Raw
    encode_raw(item)
  else
    raise RLP::InvalidValueError.new "unknown type #{type}"
  end
rescue
  STDERR.puts "when encoding #{Utils.to_hex item.to_s} into #{type}"
  raise
end