Class: Solana::Ruby::Kit::Codecs::Encoder

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/solana/ruby/kit/codecs/encoder.rb

Overview

Mirrors the TypeScript Encoder<T> interface from @solana/codecs-core.

An Encoder knows how to turn a Ruby value into a binary String. Fixed-size encoders advertise their byte length via fixed_size; variable-size encoders leave it nil and may advertise max_size.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(fixed_size: nil, max_size: nil, &block) ⇒ Encoder

Returns a new instance of Encoder.



27
28
29
30
31
# File 'lib/solana/ruby/kit/codecs/encoder.rb', line 27

def initialize(fixed_size: nil, max_size: nil, &block)
  @fixed_size = fixed_size
  @max_size   = max_size
  @fn         = T.let(block, T.proc.params(value: T.untyped).returns(String))
end

Instance Attribute Details

#fixed_sizeObject (readonly)

Returns the value of attribute fixed_size.



15
16
17
# File 'lib/solana/ruby/kit/codecs/encoder.rb', line 15

def fixed_size
  @fixed_size
end

#max_sizeObject (readonly)

Returns the value of attribute max_size.



18
19
20
# File 'lib/solana/ruby/kit/codecs/encoder.rb', line 18

def max_size
  @max_size
end

Instance Method Details

#encode(value) ⇒ Object



35
36
37
# File 'lib/solana/ruby/kit/codecs/encoder.rb', line 35

def encode(value)
  @fn.call(value).b
end

#encode_into(value, target, offset) ⇒ Object



42
43
44
45
46
47
48
49
# File 'lib/solana/ruby/kit/codecs/encoder.rb', line 42

def encode_into(value, target, offset)
  bytes = encode(value)
  target.b
  # Ensure target is long enough
  target << ("\x00".b * [0, offset + bytes.bytesize - target.bytesize].max)
  target[offset, bytes.bytesize] = bytes
  bytes.bytesize
end