Class: BinaryCodec::Uint

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

Direct Known Subclasses

Uint16, Uint32, Uint64, Uint8

Class Attribute Summary collapse

Attributes inherited from SerializedType

#bytes

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from ComparableSerializedType

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

Methods inherited from SerializedType

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

Constructor Details

#initialize(byte_buf = nil) ⇒ Uint

Returns a new instance of Uint.



10
11
12
# File 'lib/binary-codec/types/uint.rb', line 10

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

Class Attribute Details

.widthObject (readonly)

Returns the value of attribute width.



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

def width
  @width
end

Class Method Details

.from(value) ⇒ Object

Raises:

  • (StandardError)


14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/binary-codec/types/uint.rb', line 14

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

  if value.is_a?(String)
    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

Instance Method Details

#value_ofObject



28
29
30
# File 'lib/binary-codec/types/uint.rb', line 28

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