Class: IcAgent::Candid::FloatClass

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

Overview

Represents an IDL Float

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

Returns a new instance of FloatClass.

Raises:

  • (ArgumentError)


418
419
420
421
422
# File 'lib/ic_agent/candid.rb', line 418

def initialize(bits)
  super()
  @bits = bits
  raise ArgumentError, 'not a valid float type' unless [32, 64].include?(@bits)
end

Instance Method Details

#covariant(x) ⇒ Object



424
425
426
# File 'lib/ic_agent/candid.rb', line 424

def covariant(x)
  x.is_a?(Float)
end

#decode_value(b, t) ⇒ Object



447
448
449
450
451
452
453
454
455
456
457
# File 'lib/ic_agent/candid.rb', line 447

def decode_value(b, t)
  check_type(t)
  by = IcAgent::Candid.safe_read(b, @bits / 8)
  if @bits == 32
    by.hex2str.unpack('f')[0]
  elsif @bits == 64
    by.hex2str.unpack('d')[0]
  else
    raise ValueError, 'The length of float have to be 32 bits or 64 bits '
  end
end

#encode_type(type_table = nil) ⇒ Object



438
439
440
441
442
443
444
445
# File 'lib/ic_agent/candid.rb', line 438

def encode_type(type_table = nil)
  opcode = if @bits == 32
             TypeIds::Float32
           else
             TypeIds::Float64
           end
  LEB128.encode_signed(opcode).string
end

#encode_value(val) ⇒ Object



428
429
430
431
432
433
434
435
436
# File 'lib/ic_agent/candid.rb', line 428

def encode_value(val)
  if @bits == 32
    [val].pack('f')
  elsif @bits == 64
    [val].pack('d')
  else
    raise ValueError, 'The length of float have to be 32 bits or 64 bits '
  end
end

#idObject



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

def id
  if @bits == 32
    TypeIds::Float32
  else
    TypeIds::Float64
  end
end

#nameObject



459
460
461
# File 'lib/ic_agent/candid.rb', line 459

def name
  "float#{@bits}"
end