class IcAgent::Candid::FixedNatClass

Represents an IDL fixed-width Nat(n)

Public Class Methods

new(bits) click to toggle source
Calls superclass method IcAgent::Candid::PrimitiveType::new
# File lib/ic_agent/candid.rb, line 550
def initialize(bits)
  super()
  @bits = bits
  unless [8, 16, 32, 64].include? bits
    raise ArgumentError, 'bits only support 8, 16, 32, 64'
  end
end

Public Instance Methods

covariant(x) click to toggle source
# File lib/ic_agent/candid.rb, line 558
def covariant(x)
  max_val = -1 + 2**@bits
  x >= 0 && x <= max_val
end
decode_value(b, t) click to toggle source
# File lib/ic_agent/candid.rb, line 584
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) click to toggle source
# File lib/ic_agent/candid.rb, line 579
def encode_type(type_table = nil)
  offset = Math.log2(@bits).to_i - 3
  LEB128.encode_signed(-5 - offset).string
end
encode_value(val) click to toggle source
# File lib/ic_agent/candid.rb, line 563
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
id() click to toggle source
# File lib/ic_agent/candid.rb, line 605
def id
  case @bits
  when 8
    TypeIds::Nat8
  when 16
    TypeIds::Nat16
  when 32
    TypeIds::Nat32
  when 64
    TypeIds::Nat64
  end
end
name() click to toggle source
# File lib/ic_agent/candid.rb, line 601
def name
  "nat#{@bits}"
end