class PacketGen::Types::CString

This class handles null-terminated strings (aka C strings). @author Sylvain Daubert @since 3.1.6 no more a subclass or regular String

Attributes

static_length[R]

@return [Integer]

string[R]

@return [::String]

Public Class Methods

new(options={}) click to toggle source

@param [Hash] options @option options [Integer] :static_length set a static length for this string

# File lib/packetgen/types/cstring.rb, line 31
def initialize(options={})
  register_internal_string(+'')
  @static_length = options[:static_length]
end

Public Instance Methods

<<(str) click to toggle source

Append the given string to CString @param [#to_s] str @return [self]

# File lib/packetgen/types/cstring.rb, line 61
def <<(str)
  @string << str.to_s
  remove_null_character
  self
end
from_human(str) click to toggle source

Populate CString from a human readable string @param [String] str @return [self]

# File lib/packetgen/types/cstring.rb, line 86
def from_human(str)
  read str
end
read(str) click to toggle source

@param [::String] str @return [String] self

# File lib/packetgen/types/cstring.rb, line 38
def read(str)
  s = str.to_s
  s = s[0, static_length] if static_length?
  register_internal_string s
  remove_null_character
  self
end
static_length?() click to toggle source

Say if a static length is defined @return [Boolean] @since 3.1.6

# File lib/packetgen/types/cstring.rb, line 79
def static_length?
  !static_length.nil?
end
sz() click to toggle source

@return [Integer]

# File lib/packetgen/types/cstring.rb, line 68
def sz
  if static_length?
    static_length
  else
    to_s.size
  end
end
to_human() click to toggle source

@return [String]

# File lib/packetgen/types/cstring.rb, line 91
def to_human
  string
end
to_s() click to toggle source

get null-terminated string @return [String]

# File lib/packetgen/types/cstring.rb, line 48
def to_s
  if static_length?
    s = string[0, static_length - 1]
    s << "\x00" * (static_length - s.length)
  else
    s = "#{string}\x00"
  end
  PacketGen.force_binary(s)
end

Private Instance Methods

register_internal_string(str) click to toggle source
# File lib/packetgen/types/cstring.rb, line 97
def register_internal_string(str)
  @string = str
  PacketGen.force_binary(@string)
end
remove_null_character() click to toggle source
# File lib/packetgen/types/cstring.rb, line 102
def remove_null_character
  idx = string.index(0.chr)
  register_internal_string(string[0, idx]) unless idx.nil?
end