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

Constant Summary collapse

BINARY_ENCODING =
'ASCII-8BIT'.freeze

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



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

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



46
47
48
# File 'lib/rlp/utils.rb', line 46

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

#bytes?(s) ⇒ Boolean

Returns:

  • (Boolean)


67
68
69
# File 'lib/rlp/utils.rb', line 67

def bytes?(s)
  s && s.instance_of?(String) && s.encoding.name == BINARY_ENCODING
end

#bytes_to_str(v) ⇒ Object



38
39
40
# File 'lib/rlp/utils.rb', line 38

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

#decode_hex(s) ⇒ Object

Raises:

  • (TypeError)


61
62
63
64
# File 'lib/rlp/utils.rb', line 61

def decode_hex(s)
  raise TypeError, "Value must be an instance of string" unless s.instance_of?(String)
  [s].pack("H*")
end

#encode_hex(b) ⇒ Object

Raises:

  • (TypeError)


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

def encode_hex(b)
  raise TypeError, "Value must be an instance of String" unless b.instance_of?(String)
  b.unpack("H*").first
end

#int_to_big_endian(v) ⇒ Object



50
51
52
53
54
# File 'lib/rlp/utils.rb', line 50

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)


34
35
36
# File 'lib/rlp/utils.rb', line 34

def list?(item)
  !primitive?(item) && item.respond_to?(:each)
end

#primitive?(item) ⇒ Boolean

Returns:

  • (Boolean)


30
31
32
# File 'lib/rlp/utils.rb', line 30

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

#str_to_bytes(v) ⇒ Object



42
43
44
# File 'lib/rlp/utils.rb', line 42

def str_to_bytes(v)
  bytes?(v) ? v : v.b
end