Class: SolanaRuby::DataTypes::UnsignedInt
- Inherits:
-
Object
- Object
- SolanaRuby::DataTypes::UnsignedInt
- Defined in:
- lib/solana_ruby/data_types/unsigned_int.rb
Constant Summary collapse
- BITS =
{ 8 => { directive: 'C', size: 1 }, # 8-bit unsigned integer 32 => { directive: 'L<', size: 4 }, # 32-bit little-endian unsigned integer 64 => { directive: 'Q<', size: 8 } # 64-bit little-endian unsigned integer }
Instance Attribute Summary collapse
-
#size ⇒ Object
readonly
Returns the value of attribute size.
Instance Method Summary collapse
-
#deserialize(bytes) ⇒ Object
Deserialize bytes into the unsigned integer.
-
#initialize(bits) ⇒ UnsignedInt
constructor
A new instance of UnsignedInt.
-
#serialize(obj) ⇒ Object
Serialize the unsigned integer into properly aligned bytes.
Constructor Details
#initialize(bits) ⇒ UnsignedInt
Returns a new instance of UnsignedInt.
12 13 14 15 16 17 18 |
# File 'lib/solana_ruby/data_types/unsigned_int.rb', line 12 def initialize(bits) @bits = bits type = BITS[@bits] raise "Unsupported size. Supported sizes: #{BITS.keys.join(', ')} bits" unless type @size = type[:size] @directive = type[:directive] end |
Instance Attribute Details
#size ⇒ Object (readonly)
Returns the value of attribute size.
4 5 6 |
# File 'lib/solana_ruby/data_types/unsigned_int.rb', line 4 def size @size end |
Instance Method Details
#deserialize(bytes) ⇒ Object
Deserialize bytes into the unsigned integer
33 34 35 36 37 |
# File 'lib/solana_ruby/data_types/unsigned_int.rb', line 33 def deserialize(bytes) raise "Invalid serialization (expected #{@size} bytes, got #{bytes.size})" if bytes.size != @size bytes.pack('C*').unpack(@directive).first end |
#serialize(obj) ⇒ Object
Serialize the unsigned integer into properly aligned bytes
21 22 23 24 25 26 27 28 29 30 |
# File 'lib/solana_ruby/data_types/unsigned_int.rb', line 21 def serialize(obj) raise "Can only serialize integers" unless obj.is_a?(Integer) raise "Cannot serialize negative integers" if obj.negative? if obj >= 256**@size raise "Integer too large to fit in #{@size} bytes" end [obj].pack(@directive).bytes end |