Class: BinaryCodec::Uint

Inherits:
ComparableSerializedType show all
Defined in:
lib/binary-codec/types/uint.rb

Instance Attribute Summary

Attributes inherited from SerializedType

#bytes

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from ComparableSerializedType

#eq, #gt, #gte, #lt, #lte

Methods inherited from SerializedType

from_bytes, from_hex, from_json, get_type_by_name, #to_byte_sink, #to_bytes, #to_hex, #to_json

Constructor Details

#initialize(byte_buf = nil) ⇒ Uint

Returns a new instance of Uint.



12
13
14
# File 'lib/binary-codec/types/uint.rb', line 12

def initialize(byte_buf = nil)
  super(byte_buf || Array.new(self.class.width, 0))
end

Class Method Details

.from(value) ⇒ Uint

Creates a new Uint instance from a value.

Parameters:

  • value (Uint, String, Integer)

    The value to convert.

Returns:

  • (Uint)

    The created instance.

Raises:

  • (StandardError)


19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/binary-codec/types/uint.rb', line 19

def self.from(value)
  return value if value.is_a?(self)

  if value.is_a?(String)
    # Handle hex strings or numeric strings
    if valid_hex?(value) && value.length == self.width * 2
      return new(hex_to_bytes(value))
    end
    return new(int_to_bytes(value.to_i, width))
  end

  if value.is_a?(Integer)
    return new(int_to_bytes(value, width))
  end

  raise StandardError, "Cannot construct #{self} from the value given"
end

.from_parser(parser, _hint = nil) ⇒ Uint

Creates a Uint instance from a parser.

Parameters:

  • parser (BinaryParser)

    The parser to read from.

  • _hint (Integer, nil) (defaults to: nil)

    Unused hint.

Returns:

  • (Uint)

    The created instance.



41
42
43
# File 'lib/binary-codec/types/uint.rb', line 41

def self.from_parser(parser, _hint = nil)
  new(parser.read(width))
end

.widthInteger

Returns the width of the Uint type in bytes.

Returns:

  • (Integer)

    The width.



8
9
10
# File 'lib/binary-codec/types/uint.rb', line 8

def self.width
  @width
end

Instance Method Details

#compare_to(other) ⇒ Integer

Compares this Uint to another Uint.

Parameters:

  • other (Uint)

    The other Uint to compare to.

Returns:

  • (Integer)

    Comparison result (-1, 0, or 1).



54
55
56
# File 'lib/binary-codec/types/uint.rb', line 54

def compare_to(other)
  value_of <=> other.value_of
end

#value_ofInteger

Returns the numeric value of the Uint.

Returns:

  • (Integer)

    The numeric value.



47
48
49
# File 'lib/binary-codec/types/uint.rb', line 47

def value_of
  @bytes.reduce(0) { |acc, byte| (acc << 8) + byte }
end