Class: IcAgent::Candid::OptClass

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

Overview

Represents an IDL Option

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, encode_type, encode_value

Constructor Details

#initialize(_type) ⇒ OptClass

Returns a new instance of OptClass.



722
723
724
725
# File 'lib/ic_agent/candid.rb', line 722

def initialize(_type)
  super()
  @type = _type
end

Instance Method Details

#_build_type_table_impl(type_table) ⇒ Object



739
740
741
742
743
744
# File 'lib/ic_agent/candid.rb', line 739

def _build_type_table_impl(type_table)
  @type.build_type_table(type_table)
  op_code = LEB128.encode_signed(TypeIds::Opt).string
  buffer = @type.encode_type(type_table)
  type_table.add(self, op_code + buffer)
end

#covariant(x) ⇒ Object



727
728
729
# File 'lib/ic_agent/candid.rb', line 727

def covariant(x)
  x.is_a?(Array) && (x.empty? || (x.length == 1 && @type.covariant(x[0])))
end

#decode_value(b, t) ⇒ Object

Raises:



746
747
748
749
750
751
752
753
754
755
756
757
758
# File 'lib/ic_agent/candid.rb', line 746

def decode_value(b, t)
  opt = check_type(t)
  raise ValueError, 'Not an option type' unless opt.is_a?(OptClass)

  flag = IcAgent::Candid.safe_read_byte(b)
  if flag == '00'
    []
  elsif flag == '01'
    [@type.decode_value(b, opt.instance_variable_get(:@type))]
  else
    raise ValueError, 'Not an option value'
  end
end

#displayObject



768
769
770
# File 'lib/ic_agent/candid.rb', line 768

def display
  "opt (#{@type.display})"
end

#encode_value(val) ⇒ Object



731
732
733
734
735
736
737
# File 'lib/ic_agent/candid.rb', line 731

def encode_value(val)
  if val.empty?
    "\x00".b
  else
    "\x01".b + @type.encode_value(val[0])
  end
end

#idObject



764
765
766
# File 'lib/ic_agent/candid.rb', line 764

def id
  TypeIds::Opt
end

#nameObject



760
761
762
# File 'lib/ic_agent/candid.rb', line 760

def name
  "opt (#{@type.name})"
end