Module: RLP::Utils

Extended by:
Utils
Included in:
Decode, Encode, Sedes::BigEndianInt, Sedes::Binary, Sedes::CountableList, Sedes::List, Sedes::Raw, Utils
Defined in:
lib/rlp/utils.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.make_immutable!(obj) ⇒ Object

Do your best to make `obj` as immutable as possible.

If `obj` is a list, apply this function recursively to all elements and return a new list containing them. If `obj` is an instance of Sedes::Serializable, apply this function to its fields, and set `@_mutable` to `false`. If `obj` is neither of the above, just return `obj`.

Returns:

  • (Object)

    `obj` after making it immutable


15
16
17
18
19
20
21
22
23
# File 'lib/rlp/utils.rb', line 15

def make_immutable!(obj)
  if obj.is_a?(Sedes::Serializable)
    obj.make_immutable!
  elsif list?(obj)
    obj.map {|e| make_immutable!(e) }
  else
    obj
  end
end

Instance Method Details

#big_endian_to_int(v) ⇒ Object


44
45
46
# File 'lib/rlp/utils.rb', line 44

def big_endian_to_int(v)
  v.unpack('H*').first.to_i(16)
end

#bytes_to_str(v) ⇒ Object


36
37
38
# File 'lib/rlp/utils.rb', line 36

def bytes_to_str(v)
  v.unpack('U*').pack('U*')
end

#encode_hex(b) ⇒ Object

Raises:

  • (TypeError)

54
55
56
57
58
# File 'lib/rlp/utils.rb', line 54

def encode_hex(b)
  raise TypeError, "Value must be an instance of String" unless b.instance_of?(String)
  b = str_to_bytes(b) unless b.encoding.name == 'ASCII-8BIT'
  b.unpack("H*").first
end

#int_to_big_endian(v) ⇒ Object


48
49
50
51
52
# File 'lib/rlp/utils.rb', line 48

def int_to_big_endian(v)
  hex = v.to_s(16)
  hex = "0#{hex}" if hex.size.odd?
  [hex].pack('H*')
end

#list?(item) ⇒ Boolean

Returns:

  • (Boolean)

32
33
34
# File 'lib/rlp/utils.rb', line 32

def list?(item)
  item.respond_to?(:each)
end

#primitive?(item) ⇒ Boolean

Returns:

  • (Boolean)

28
29
30
# File 'lib/rlp/utils.rb', line 28

def primitive?(item)
  item.instance_of?(String)
end

#str_to_bytes(v) ⇒ Object


40
41
42
# File 'lib/rlp/utils.rb', line 40

def str_to_bytes(v)
  v.dup.force_encoding('ascii-8bit')
end