Module: ScaleRb::CodecUtils::InternalEncodeUtils

Extended by:
TypeEnforcer
Includes:
Types
Included in:
ScaleRb::CodecUtils
Defined in:
lib/scale_rb/codec_utils.rb

Constant Summary

Constants included from Types

Types::DecodeResult, Types::HashMap, Types::Hex, Types::PortableType, Types::Primitive, Types::Registry, Types::Ti, Types::TypedArray, Types::U8, Types::U8Array, Types::UnsignedInteger, Types::VariantKind

Instance Method Summary collapse

Methods included from TypeEnforcer

__, extended, method_added

Instance Method Details

#encode_boolean(value) ⇒ Object

Raises:

  • (InvalidValueError)


107
108
109
110
111
112
# File 'lib/scale_rb/codec_utils.rb', line 107

def encode_boolean(value)
  return [0x00] if value == false
  return [0x01] if value == true

  raise InvalidValueError, "type: Bool, value: #{value.inspect}"
end

#encode_compact(value) ⇒ Object



115
116
117
118
119
120
121
122
# File 'lib/scale_rb/codec_utils.rb', line 115

def encode_compact(value)
  return [value << 2] if value.between?(0, 63)
  return Utils.int_to_u8a(((value << 2) + 1)).reverse if value < 2**14
  return Utils.int_to_u8a(((value << 2) + 2)).reverse if value < 2**30

  bytes = Utils.int_to_u8a(value).reverse
  [(((bytes.length - 4) << 2) + 3)] + bytes
end

#encode_int(_type, _value) ⇒ Object

Raises:

  • (NotImplemented)


92
93
94
95
96
97
98
# File 'lib/scale_rb/codec_utils.rb', line 92

def encode_int(_type, _value)
  raise NotImplemented, 'encode_int'
  # raise InvalidValueError, "type: #{type}, value: #{value.inspect}" unless value.is_a?(Integer)
  #
  # bit_length = type[1..].to_i
  # Utils.int_to_u8a(value, bit_length).reverse
end

#encode_str(string) ⇒ Object



101
102
103
104
# File 'lib/scale_rb/codec_utils.rb', line 101

def encode_str(string)
  body = string.unpack('C*')
  encode_compact(body.length) + body
end

#encode_uint(type, value) ⇒ Object

Raises:

  • (InvalidValueError)


84
85
86
87
88
89
# File 'lib/scale_rb/codec_utils.rb', line 84

def encode_uint(type, value)
  raise InvalidValueError, "type: #{type}, value: #{value.inspect}" unless value.is_a?(::Integer)

  bit_length = type[1..].to_i
  Utils.int_to_u8a(value, bit_length).reverse
end