Class: Nl::DataTypes::VariableInteger

Inherits:
Base
  • Object
show all
Defined in:
nl/lib/nl/datatypes.rb

Constant Summary collapse

UINT32_RANGE =
(0...2**32)
UINT64_RANGE =
(0...2**64)
SINT32_RANGE =
(-(2**31)...2**31)
SINT64_RANGE =
(-(2**63)...2**63)

Instance Method Summary collapse

Methods inherited from Base

#coerce, #nlattr_type_flags

Constructor Details

#initialize(byte_order, signed:, check:) ⇒ VariableInteger

Returns a new instance of VariableInteger.



54
55
56
57
58
59
60
61
# File 'nl/lib/nl/datatypes.rb', line 54

def initialize(byte_order, signed:, check:)
  super(check:)
  prefix = signed ? 'S' : 'U'
  @type32 = byte_order.const_get("#{prefix}32")
  @type64 = byte_order.const_get("#{prefix}64")
  @range32 = signed ? SINT32_RANGE : UINT32_RANGE
  @range64 = signed ? SINT64_RANGE : UINT64_RANGE
end

Instance Method Details

#decode(decoder, context: nil, nlattr_type_flags: 0) ⇒ Object



73
74
75
76
77
78
79
80
81
# File 'nl/lib/nl/datatypes.rb', line 73

def decode(decoder, context: nil, nlattr_type_flags: 0)
  type = case decoder.remaining
  when 4 then @type32
  when 8 then @type64
  else
    raise Decoder::Error, "variable integer payload must be 4 or 8 bytes, got #{decoder.remaining}"
  end
  checked(decoder.get_value(type))
end

#encode(encoder, value, context: nil) ⇒ Object



63
64
65
66
67
68
69
70
71
# File 'nl/lib/nl/datatypes.rb', line 63

def encode(encoder, value, context: nil)
  value = checked(value || 0)
  unless @range64.cover?(value)
    raise RangeError, "integer #{value.inspect} is outside the #{@range64.begin}...#{@range64.end} range"
  end

  type = @range32.cover?(value) ? @type32 : @type64
  encoder.put_value(type, value)
end