Class: BinData::String

Inherits:
Single show all
Defined in:
lib/bindata/string.rb

Overview

A String is a sequence of bytes. This is the same as strings in Ruby. The issue of character encoding is ignored by this class.

Parameters

String objects accept all the params that BinData::Single does, as well as the following:

:initial_length

The initial length to use before a value is either read or set.

:length

The fixed length of the string. If a shorter string is set, it will be padded to this length.

:pad_char

The character to use when padding a string to a set length. Valid values are Integers and Strings of length 1. “0” is the default.

:trim_value

Boolean, default false. If set, #value will return the value with all pad_chars trimmed from the end of the string. The value will not be trimmed when writing.

Instance Method Summary collapse

Methods inherited from Single

#_do_read, #_num_bytes, #_write, #clear, #clear?, #done_read, #field_names, inherited, #snapshot, #value=

Methods inherited from Base

#do_read, #klass_lookup, lookup, mandatory_parameters, #num_bytes, optional_parameters, parameters, #read, read, register, #single_value?, #write

Constructor Details

#initialize(params = {}, env = nil) ⇒ String

Returns a new instance of String.



28
29
30
31
32
33
34
35
36
37
38
# File 'lib/bindata/string.rb', line 28

def initialize(params = {}, env = nil)
  super(cleaned_params(params), env)

  # the only valid param combinations of length and value are:
  #   :initial_length and :value
  #   :length and :initial_value
  ensure_mutual_exclusion(:initial_value, :value)
  ensure_mutual_exclusion(:initial_length, :length)
  ensure_mutual_exclusion(:initial_length, :initial_value)
  ensure_mutual_exclusion(:length, :value)
end

Instance Method Details

#valueObject

Overrides value to return the value padded to the desired length or trimmed as required.



42
43
44
45
46
# File 'lib/bindata/string.rb', line 42

def value
  v = val_to_str(_value)
  v.sub!(/#{eval_param(:pad_char)}*$/, "") if param(:trim_value) == true
  v
end