Class: IcAgent::Candid::PrincipalClass

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

Instance Method Summary collapse

Methods inherited from PrimitiveType

#_build_type_table_impl, #check_type

Methods inherited from BaseType

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

Constructor Details

#initializePrincipalClass

Returns a new instance of PrincipalClass.



609
610
611
# File 'lib/ic_agent/candid.rb', line 609

def initialize
  super
end

Instance Method Details

#covariant(x) ⇒ Object



613
614
615
616
617
618
619
620
621
622
# File 'lib/ic_agent/candid.rb', line 613

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 ValueError, 'only support string or bytes format'
  end
  p.is_a?(IcAgent::Principal)
end

#decode_value(b, t) ⇒ Object



641
642
643
644
645
646
647
648
649
650
# File 'lib/ic_agent/candid.rb', line 641

def decode_value(b, t)
  check_type(t)
  res = IcAgent::Candid.safe_read_byte(b)
  if res != '01'
    raise ValueError, 'Cannot decode principal'
  end

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

#encode_type(type_table = nil) ⇒ Object



637
638
639
# File 'lib/ic_agent/candid.rb', line 637

def encode_type(type_table = nil)
  LEB128.encode_signed(TypeIds::Principal).string
end

#encode_value(val) ⇒ Object



624
625
626
627
628
629
630
631
632
633
634
635
# File 'lib/ic_agent/candid.rb', line 624

def encode_value(val)
  tag = 1.chr(Encoding::ASCII_8BIT)
  if val.is_a?(String)
    buf = IcAgent::Principal.from_str(val).bytes
  elsif val.is_a?(Array)
    buf = val.pack('C*')
  else
    raise ValueError, 'Principal should be string or bytes.'
  end
  l = LEB128.encode_signed(buf.size).string
  tag + l + buf
end

#idObject



656
657
658
# File 'lib/ic_agent/candid.rb', line 656

def id
  TypeIds::Principal
end

#nameObject



652
653
654
# File 'lib/ic_agent/candid.rb', line 652

def name
  'principal'
end