Module: PacketGen::Types::LengthFrom

Included in:
Array, String
Defined in:
lib/packetgen/types/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

Since:

  • 3.0.0

Instance Method Summary collapse

Instance Method Details

#initialize_length_from(options) ⇒ void

This method returns an undefined value.

Initialize length from capacity. Should be call by extensed object’s initialize.

Parameters:

  • options (Hash)

Options Hash (options):

  • :length_from (Types::Int, Proc)

    object or proc from which takes length when reading

Since:

  • 3.0.0



23
24
25
# File 'lib/packetgen/types/length_from.rb', line 23

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:

Since:

  • 3.0.0



30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/packetgen/types/length_from.rb', line 30

def read_with_length_from(str)
  s = PacketGen.force_binary(str.to_s)
  str_end = case @length_from
            when Types::Int
              @length_from.to_i
            when Proc
              @length_from.call
            else
              s.size
            end
  str_end = 0 if str_end < 0
  s[0, str_end]
end