Class: PacketGen::Types::String

Inherits:
String
  • Object
show all
Defined in:
lib/packetgen/types/string.rb

Overview

This class is just like regular String. It only adds #read and #sz methods to be compatible with others PacketGen::Types.

Author:

  • Sylvain Daubert

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ String

Returns a new instance of String.

Parameters:

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :length_from (Types::Int, Proc)

    object or proc from which takes length when reading

  • :static_length (Integer)

    set a static length for this string



19
20
21
22
23
# File 'lib/packetgen/types/string.rb', line 19

def initialize(options={})
  super()
  @length_from = options[:length_from]
  @static_length = options[:static_length]
end

Instance Method Details

#read(str) ⇒ String

Returns self.

Parameters:

  • str (::String)

Returns:



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/packetgen/types/string.rb', line 27

def read(str)
  s = str.to_s
  str_end = case @length_from
            when Types::Int
              @length_from.to_i
            when Proc
              @length_from.call
            else
              if @static_length.is_a? Integer
                @static_length
              else
                s.size
              end
            end
  str_end = 0 if str_end < 0
  self.replace(s[0, str_end])
  self
end