Class: IcAgent::Candid::ServiceClass

Inherits:
ConstructType show all
Defined in:
lib/ic_agent/candid.rb

Instance Method Summary collapse

Methods inherited from ConstructType

#check_type, #encode_type

Methods inherited from BaseType

_build_type_table_impl, #build_type_table, check_type, covariant, decode_value, #display, encode_type, encode_value

Constructor Details

#initialize(field) ⇒ ServiceClass

Returns a new instance of ServiceClass.



1174
1175
1176
1177
# File 'lib/ic_agent/candid.rb', line 1174

def initialize(field)
  super()
  @fields = Hash[field.sort_by { |k, _| IcAgent::Utils.label_hash(k.to_s) }]
end

Instance Method Details

#_build_type_table_impl(type_table) ⇒ Object



1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
# File 'lib/ic_agent/candid.rb', line 1203

def _build_type_table_impl(type_table)
  @fields.each_value { |v| v.build_type_table(type_table) }
  op_code = LEB128.encode_signed(TypeIds::Service).string
  length = LEB128.encode_signed(@fields.length).string
  fields = ''.b
  @fields.each { |k, v|
    fields += LEB128.encode_signed(k.to_s.bytesize).string + k.to_s + v.encode_type(type_table)
  }
  type_table.add(self, op_code + length + fields)
end

#covariant(x) ⇒ Object



1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
# File 'lib/ic_agent/candid.rb', line 1179

def covariant(x)
  if x.is_a?(String)
    p = IcAgent::Principal.from_str(x)
  elsif x.is_a?(Array)
    p = IcAgent::Principal.from_hex(x.pack('C*').unpack1('H*'))
  else
    raise ArgumentError, 'only support string or bytes format'
  end
  p.is_a?(IcAgent::Principal)
end

#decode_value(b, t) ⇒ Object

Raises:

  • (ArgumentError)


1214
1215
1216
1217
1218
1219
1220
# File 'lib/ic_agent/candid.rb', line 1214

def decode_value(b, t)
  res = IcAgent::Candid.safe_read_byte(b)
  raise ArgumentError, 'Cannot decode principal' unless res == '01'

  length = IcAgent::Candid.leb128u_decode(b)
  IcAgent::Principal.from_hex(IcAgent::Candid.safe_read(b, length)).to_str
end

#encode_value(val) ⇒ Object



1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
# File 'lib/ic_agent/candid.rb', line 1190

def encode_value(val)
  tag = [1].pack('C')
  if val.is_a?(String)
    buf = IcAgent::Principal.from_str(val).bytes
  elsif val.is_a?(Array)
    buf = val
  else
    raise ArgumentError, 'Principal should be string or bytes.'
  end
  l = LEB128.encode_signed(buf.length).string
  tag + l + buf
end

#idObject



1227
1228
1229
# File 'lib/ic_agent/candid.rb', line 1227

def id
  TypeIds::Service
end

#nameObject



1222
1223
1224
1225
# File 'lib/ic_agent/candid.rb', line 1222

def name
  fields = @fields.map { |k, v| "#{k} : #{v.name}" }.join(', ')
  "service #{fields}"
end