Class: IcAgent::Candid::FixedIntClass

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) ⇒ FixedIntClass

Returns a new instance of FixedIntClass.



464
465
466
467
468
469
470
# File 'lib/ic_agent/candid.rb', line 464

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



472
473
474
475
476
477
478
479
480
# File 'lib/ic_agent/candid.rb', line 472

def covariant(x)
  min_val = -1 * 2**(@bits - 1)
  max_val = -1 + 2**(@bits - 1)
  if x >= min_val && x <= max_val
    true
  else
    false
  end
end

#decode_value(b, t) ⇒ Object



503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
# File 'lib/ic_agent/candid.rb', line 503

def decode_value(b, t)
  check_type(t)
  by = IcAgent::Candid.safe_read(b, @bits / 8)
  case @bits
  when 8
    by.hex2str.unpack('c')[0] # signed char -> Int8
  when 16
    by.hex2str.unpack('s')[0] # short -> Int16
  when 32
    by.hex2str.unpack('l')[0] # int -> Int32
  when 64
    by.hex2str.unpack('q')[0] # long long -> Int64
  else
    raise ArgumentError, 'bits only support 8, 16, 32, 64'
  end
end

#encode_type(type_table = nil) ⇒ Object



498
499
500
501
# File 'lib/ic_agent/candid.rb', line 498

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

#encode_value(val) ⇒ Object



482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
# File 'lib/ic_agent/candid.rb', line 482

def encode_value(val)
  case @bits
  when 8
    buf = [val].pack('c') # signed char -> Int8
  when 16
    buf = [val].pack('s') # short -> Int16
  when 32
    buf = [val].pack('l') # int -> Int32
  when 64
    buf = [val].pack('q') # long long -> Int64
  else
    raise ArgumentError, 'bits only support 8, 16, 32, 64'
  end
  buf
end

#idObject



524
525
526
527
528
529
530
531
532
533
534
535
# File 'lib/ic_agent/candid.rb', line 524

def id
  case @bits
  when 8
    TypeIds::Int8
  when 16
    TypeIds::Int16
  when 32
    TypeIds::Int32
  when 64
    TypeIds::Int64
  end
end

#nameObject



520
521
522
# File 'lib/ic_agent/candid.rb', line 520

def name
  "int#{@bits.to_s}"
end