class BinData::Stringz
A BinData::Stringz
object is a container for a zero (“0”) terminated string.
For convenience, the zero terminator is not necessary when setting the value. Likewise, the returned value will not be zero terminated.
require 'bindata' data = "abcd\x00efgh" obj = BinData::Stringz.new obj.read(data) obj.snapshot #=> "abcd" obj.num_bytes #=> 5 obj.to_binary_s #=> "abcd\000"
Parameters¶ ↑
Stringz
objects accept all the params that BinData::BasePrimitive
does, as well as the following:
:max_length
-
The maximum length of the string including the zero byte.
Public Instance Methods
assign(val)
click to toggle source
Calls superclass method
BinData::BasePrimitive#assign
# File lib/bindata/stringz.rb, line 31 def assign(val) super(binary_string(val)) end
snapshot()
click to toggle source
Calls superclass method
BinData::BasePrimitive#snapshot
# File lib/bindata/stringz.rb, line 35 def snapshot # override to always remove trailing zero bytes result = super trim_and_zero_terminate(result).chomp("\0") end
Private Instance Methods
append_zero_byte_if_needed!(str)
click to toggle source
# File lib/bindata/stringz.rb, line 90 def append_zero_byte_if_needed!(str) if str.length == 0 || str[-1, 1] != "\0" str << "\0" end end
read_and_return_value(io)
click to toggle source
# File lib/bindata/stringz.rb, line 48 def read_and_return_value(io) max_length = eval_parameter(:max_length) str = "" i = 0 ch = nil # read until zero byte or we have read in the max number of bytes while ch != "\0" && i != max_length ch = io.readbytes(1) str << ch i += 1 end trim_and_zero_terminate(str) end
sensible_default()
click to toggle source
# File lib/bindata/stringz.rb, line 64 def sensible_default "" end
trim_and_zero_terminate(str)
click to toggle source
# File lib/bindata/stringz.rb, line 68 def trim_and_zero_terminate(str) result = binary_string(str) truncate_after_first_zero_byte!(result) trim_to!(result, eval_parameter(:max_length)) append_zero_byte_if_needed!(result) result end
trim_to!(str, max_length = nil)
click to toggle source
# File lib/bindata/stringz.rb, line 80 def trim_to!(str, max_length = nil) if max_length max_length = 1 if max_length < 1 str.slice!(max_length) if str.length == max_length && str[-1, 1] != "\0" str[-1, 1] = "\0" end end end
truncate_after_first_zero_byte!(str)
click to toggle source
# File lib/bindata/stringz.rb, line 76 def truncate_after_first_zero_byte!(str) str.sub!(/([^\0]*\0).*/, '\1') end
value_to_binary_string(val)
click to toggle source
# File lib/bindata/stringz.rb, line 44 def value_to_binary_string(val) trim_and_zero_terminate(val) end