Class: BinaryCodec::Uint
- Inherits:
-
ComparableSerializedType
- Object
- SerializedType
- ComparableSerializedType
- BinaryCodec::Uint
- Defined in:
- lib/binary-codec/types/uint.rb
Direct Known Subclasses
Int32, Int64, Uint128, Uint16, Uint160, Uint192, Uint256, Uint32, Uint384, Uint512, Uint64, Uint8, Uint96
Instance Attribute Summary
Attributes inherited from SerializedType
Class Method Summary collapse
-
.from(value) ⇒ Uint
Creates a new Uint instance from a value.
-
.from_parser(parser, _hint = nil) ⇒ Uint
Creates a Uint instance from a parser.
-
.width ⇒ Integer
Returns the width of the Uint type in bytes.
Instance Method Summary collapse
-
#compare_to(other) ⇒ Integer
Compares this Uint to another Uint.
-
#initialize(byte_buf = nil) ⇒ Uint
constructor
A new instance of Uint.
-
#value_of ⇒ Integer
Returns the numeric value of the Uint.
Methods inherited from ComparableSerializedType
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.
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.
41 42 43 |
# File 'lib/binary-codec/types/uint.rb', line 41 def self.from_parser(parser, _hint = nil) new(parser.read(width)) end |
.width ⇒ Integer
Returns the width of the Uint type in bytes.
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.
54 55 56 |
# File 'lib/binary-codec/types/uint.rb', line 54 def compare_to(other) value_of <=> other.value_of end |
#value_of ⇒ Integer
Returns the numeric value of the Uint.
47 48 49 |
# File 'lib/binary-codec/types/uint.rb', line 47 def value_of @bytes.reduce(0) { |acc, byte| (acc << 8) + byte } end |