Class: PacketGen::Types::IntString

Inherits:
Object
  • Object
show all
Includes:
Fieldable
Defined in:
lib/packetgen/types/int_string.rb

Overview

Provides a class for creating strings preceeded by their length as a Int. By default, a null string will have one byte length (length byte set to 0).

Author:

  • Sylvain Daubert

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Fieldable

#format_inspect, #type_name

Constructor Details

#initialize(len_type = Int8, string: '') ⇒ IntString

Returns a new instance of IntString.

Parameters:

  • len_type (Class) (defaults to: Int8)

    should be a PacketGen::Types::Int subclass

  • string (::String) (defaults to: '')


23
24
25
26
27
# File 'lib/packetgen/types/int_string.rb', line 23

def initialize(len_type=Int8, string: '')
  @string = Types::String.new.read(string)
  @length = len_type.new
  calc_length
end

Instance Attribute Details

#stringString

internal string

Returns:



19
20
21
# File 'lib/packetgen/types/int_string.rb', line 19

def string
  @string
end

Instance Method Details

#calc_lengthInteger

Set length from internal string length

Returns:

  • (Integer)


84
85
86
# File 'lib/packetgen/types/int_string.rb', line 84

def calc_length
  @length.read @string.length
end

#empty?Boolean

Say if IntString is empty

Returns:

  • (Boolean)


96
97
98
# File 'lib/packetgen/types/int_string.rb', line 96

def empty?
  length.zero?
end

#from_human(str) ⇒ self

Set from a human readable string

Parameters:

Returns:

  • (self)


69
70
71
72
73
# File 'lib/packetgen/types/int_string.rb', line 69

def from_human(str)
  @string.read str
  calc_length
  self
end

#lengthInteger

Returns:

  • (Integer)


49
50
51
# File 'lib/packetgen/types/int_string.rb', line 49

def length
  @length.to_i
end

#length=(len) ⇒ Integer

Parameters:

  • len (Integer)

Returns:

  • (Integer)


43
44
45
46
# File 'lib/packetgen/types/int_string.rb', line 43

def length=(len)
  @length.read len
  len
end

#read(str) ⇒ IntString

Returns self.

Parameters:

  • str (::String)

Returns:



31
32
33
34
35
36
37
38
39
# File 'lib/packetgen/types/int_string.rb', line 31

def read(str)
  unless str[0, @length.width].size == @length.width
    raise ParseError,
          "String too short for type #{@length.class.to_s.gsub(/.*::/, '')}"
  end
  @length.read str[0, @length.width]
  @string.read str[@length.width, @length.to_i]
  self
end

#szInteger

Give binary string length (including length field)

Returns:

  • (Integer)


90
91
92
# File 'lib/packetgen/types/int_string.rb', line 90

def sz
  to_s.size
end

#to_human::String

Get human readable string

Returns:

  • (::String)

Since:

  • 2.2.0



78
79
80
# File 'lib/packetgen/types/int_string.rb', line 78

def to_human
  @string
end

#to_s::String

Get binary string

Returns:

  • (::String)


62
63
64
# File 'lib/packetgen/types/int_string.rb', line 62

def to_s
  @length.to_s << @string.to_s
end