Module: BinStruct::LengthFrom

Included in:
Array, String
Defined in:
lib/bin_struct/length_from.rb

Overview

This module is a mixin adding length_from capacity to a type. length_from capacity is the capacity, for a type, to gets its length from another object.

Author:

  • Sylvain Daubert (2016-2024)

  • LemonTree55

Constant Summary collapse

MAX_SZ_TO_READ =

Max value returned by #sz_to_read.

65_535

Instance Method Summary collapse

Instance Method Details

#initialize_length_from(options) ⇒ void

This method returns an undefined value.

Initialize length_from capacity. Should be called by extended object’s initialize method.

Parameters:

  • options (Hash)

Options Hash (options):

  • :length_from (Int, Proc)

    object or proc from which takes length when reading



25
26
27
# File 'lib/bin_struct/length_from.rb', line 25

def initialize_length_from(options)
  @length_from = options[:length_from]
end

#read_with_length_from(str) ⇒ ::String

Return a substring from str of length given in another object.

Parameters:

  • str (#to_s)

Returns:

  • (::String)


32
33
34
35
# File 'lib/bin_struct/length_from.rb', line 32

def read_with_length_from(str)
  s = BinStruct.force_binary(str.to_s)
  s[0, sz_to_read]
end

#sz_to_readInteger

Size to read, from length_from

Returns:

  • (Integer)


39
40
41
42
43
44
45
46
47
48
49
# File 'lib/bin_struct/length_from.rb', line 39

def sz_to_read
  len = case @length_from
        when Int
          @length_from.to_i
        when Proc
          @length_from.call
        else
          MAX_SZ_TO_READ
        end
  [0, len].max
end