Class: IcAgent::Candid::FixedNatClass

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

#initialize(bits) ⇒ FixedNatClass

Returns a new instance of FixedNatClass.



539
540
541
542
543
544
545
# File 'lib/ic_agent/candid.rb', line 539

def initialize(bits)
  super()
  @bits = bits
  unless [8, 16, 32, 64].include? bits
    raise ArgumentError, 'bits only support 8, 16, 32, 64'
  end
end

Instance Method Details

#covariant(x) ⇒ Object



547
548
549
550
# File 'lib/ic_agent/candid.rb', line 547

def covariant(x)
  max_val = -1 + 2**@bits
  x >= 0 && x <= max_val
end

#decode_value(b, t) ⇒ Object



573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
# File 'lib/ic_agent/candid.rb', line 573

def decode_value(b, t)
  check_type(t)
  by = IcAgent::Candid.safe_read(b, @bits / 8)
  case @bits
  when 8
    return by.hex2str.unpack('C').first # unsigned char -> Nat8
  when 16
    return by.hex2str.unpack('S').first # unsigned short -> Nat16
  when 32
    return by.hex2str.unpack('L').first # unsigned int -> Nat32
  when 64
    return by.hex2str.unpack('Q').first # unsigned long long -> Nat64
  else
    raise ArgumentError, 'bits only support 8, 16, 32, 64'
  end
end

#encode_type(type_table = nil) ⇒ Object



568
569
570
571
# File 'lib/ic_agent/candid.rb', line 568

def encode_type(type_table = nil)
  offset = Math.log2(@bits).to_i - 3
  LEB128.encode_signed(-5 - offset).string
end

#encode_value(val) ⇒ Object



552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
# File 'lib/ic_agent/candid.rb', line 552

def encode_value(val)
  case @bits
  when 8
    buf = [val].pack('C') # unsigned char -> Nat8
  when 16
    buf = [val].pack('S') # unsigned short -> Nat16
  when 32
    buf = [val].pack('L') # unsigned int -> Nat32
  when 64
    buf = [val].pack('Q') # unsigned long long -> Nat64
  else
    raise ArgumentError, 'bits only support 8, 16, 32, 64'
  end
  buf
end

#idObject



594
595
596
597
598
599
600
601
602
603
604
605
# File 'lib/ic_agent/candid.rb', line 594

def id
  case @bits
  when 8
    TypeIds::Nat8
  when 16
    TypeIds::Nat16
  when 32
    TypeIds::Nat32
  when 64
    TypeIds::Nat64
  end
end

#nameObject



590
591
592
# File 'lib/ic_agent/candid.rb', line 590

def name
  "nat#{@bits}"
end