Class: PacketGen::Types::CString

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

Overview

This class handles null-terminated strings (aka C strings).

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ CString

Returns a new instance of CString.

Parameters:

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

Options Hash (options):

  • :static_length (Integer)

    set a static length for this string



16
17
18
19
# File 'lib/packetgen/types/cstring.rb', line 16

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

Instance Method Details

#from_human(str) ⇒ self

Populate CString from a human readable string

Parameters:

Returns:

  • (self)


60
61
62
# File 'lib/packetgen/types/cstring.rb', line 60

def from_human(str)
  read str
end

#read(str) ⇒ String

Returns self.

Parameters:

  • str (::String)

Returns:



23
24
25
26
27
28
29
30
# File 'lib/packetgen/types/cstring.rb', line 23

def read(str)
  s = str.to_s
  s = s[0, @static_length] if @static_length.is_a? Integer
  idx = s.index(0.chr)
  s = s[0, idx] unless idx.nil?
  self.replace s
  self
end

#szInteger

Returns:

  • (Integer)


49
50
51
52
53
54
55
# File 'lib/packetgen/types/cstring.rb', line 49

def sz
  if @static_length.is_a? Integer
    @static_length
  else
    to_s.size
  end
end

#to_humanString

Returns:



65
66
67
68
# File 'lib/packetgen/types/cstring.rb', line 65

def to_human
  idx = self.index(+"\x00".encode(self.encoding)) || self.sz
  self[0, idx]
end

#to_sString

get null-terminated string

Returns:



34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/packetgen/types/cstring.rb', line 34

def to_s
  if defined?(@static_length) && @static_length.is_a?(Integer)
    if self.size >= @static_length
      s = self[0, @static_length]
      s[-1] = "\x00".encode(s.encoding)
      PacketGen.force_binary s
    else
      PacketGen.force_binary(self + "\0" * (@static_length - self.length))
    end
  else
    PacketGen.force_binary(self + +"\x00".encode(self.encoding))
  end
end