Module: Ciri::RLP::Encode
- Includes:
- Utils::Logger
- Included in:
- Ciri::RLP, Serializable::Schema
- Defined in:
- lib/ciri/rlp/encode.rb
Defined Under Namespace
Classes: InputOverflow
Instance Method Summary collapse
-
#encode(input, type = nil) ⇒ Object
Encode input to rlp encoding.
- #encode_simple(input) ⇒ Object
-
#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.
Instance Method Details
#encode(input, type = nil) ⇒ Object
41 42 43 |
# File 'lib/ciri/rlp/encode.rb', line 41 def encode(input, type = nil) type ? encode_with_type(input, type) : encode_simple(input) end |
#encode_simple(input) ⇒ Object
45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/ciri/rlp/encode.rb', line 45 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
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 90 91 92 93 94 95 96 97 98 99 |
# File 'lib/ciri/rlp/encode.rb', line 65 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::InvalidError.new "type size should be 1, got #{type}" end elsif type == Raw encode_raw(item) elsif type == Bytes raise RLP::InvalidError.new "expect String, got #{item.class}" unless item.is_a?(String) encode_raw(item) elsif type == List raise RLP::InvalidError.new "expect Array, got #{item.class}" unless item.is_a?(Array) encode_raw(item) else raise RLP::InvalidError.new "unknown type #{type}" end rescue error "when encoding #{Utils.to_hex item.to_s} into #{type}" raise end |