Class: PacketGen::Types::CString
- Inherits:
-
String
- Object
- String
- PacketGen::Types::CString
- Defined in:
- lib/packetgen/types/cstring.rb
Overview
This class handles null-terminated strings (aka C strings).
Instance Method Summary collapse
-
#from_human(str) ⇒ self
Populate CString from a human readable string.
-
#initialize(options = {}) ⇒ CString
constructor
A new instance of CString.
-
#read(str) ⇒ String
Self.
- #sz ⇒ Integer
- #to_human ⇒ String
-
#to_s ⇒ String
get null-terminated string.
Constructor Details
#initialize(options = {}) ⇒ CString
Returns a new instance of CString.
16 17 18 19 |
# File 'lib/packetgen/types/cstring.rb', line 16 def initialize(={}) super() @static_length = [:static_length] end |
Instance Method Details
#from_human(str) ⇒ self
Populate CString from a human readable string
60 61 62 |
# File 'lib/packetgen/types/cstring.rb', line 60 def from_human(str) read str end |
#read(str) ⇒ String
Returns self.
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 |
#sz ⇒ 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_human ⇒ String
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_s ⇒ String
get null-terminated string
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 |