Class: BinStruct::IntString
- Inherits:
-
Object
- Object
- BinStruct::IntString
- Includes:
- Structable
- Defined in:
- lib/bin_struct/int_string.rb
Overview
Provides a class for creating strings preceeded by their length as an Int. By default, a null string will have one byte length (length byte set to 0).
Instance Attribute Summary collapse
-
#string ⇒ ::String
internal string.
Instance Method Summary collapse
-
#calc_length ⇒ Integer
Set length from internal string length.
-
#empty? ⇒ Boolean
Say if IntString is empty.
-
#from_human(str) ⇒ self
Set from a human readable string.
-
#initialize(options = {}) ⇒ IntString
constructor
A new instance of IntString.
-
#length ⇒ Integer
Get length as registered in
IntLength
. -
#length=(len) ⇒ Integer
Set length.
-
#read(str) ⇒ self
Populate IntString from a binary String.
-
#sz ⇒ Integer
Give binary string length (including
length
attribute). -
#to_human ⇒ ::String
Get human readable string.
-
#to_s ⇒ ::String
Get binary string.
Methods included from Structable
Constructor Details
Instance Attribute Details
#string ⇒ ::String
internal string
19 20 21 |
# File 'lib/bin_struct/int_string.rb', line 19 def string @string end |
Instance Method Details
#calc_length ⇒ Integer
Set length from internal string length
90 91 92 |
# File 'lib/bin_struct/int_string.rb', line 90 def calc_length @length.from_human(@string.length) end |
#empty? ⇒ Boolean
Say if IntString is empty
102 103 104 |
# File 'lib/bin_struct/int_string.rb', line 102 def empty? length.zero? end |
#from_human(str) ⇒ self
Set from a human readable string
76 77 78 79 80 |
# File 'lib/bin_struct/int_string.rb', line 76 def from_human(str) @string.read(str) calc_length self end |
#length ⇒ Integer
Get length as registered in IntLength
55 56 57 |
# File 'lib/bin_struct/int_string.rb', line 55 def length @length.to_i end |
#length=(len) ⇒ Integer
Set length
46 47 48 49 50 51 |
# File 'lib/bin_struct/int_string.rb', line 46 def length=(len) @length.from_human(len) # rubocop:disable Lint/Void len # rubocop:enable Lint/Void end |
#read(str) ⇒ self
Populate IntString from a binary String
33 34 35 36 37 38 39 40 41 |
# File 'lib/bin_struct/int_string.rb', line 33 def read(str) unless str[0, @length.width].size == @length.width raise Error, "String too short for type #{@length.class.to_s.gsub(/.*::/, '')}" end @length.read str[0, @length.width] @string.read str[@length.width, @length.to_i] self end |
#sz ⇒ Integer
Give binary string length (including length
attribute)
96 97 98 |
# File 'lib/bin_struct/int_string.rb', line 96 def sz to_s.size end |
#to_human ⇒ ::String
Get human readable string
84 85 86 |
# File 'lib/bin_struct/int_string.rb', line 84 def to_human @string end |
#to_s ⇒ ::String
Get binary string
69 70 71 |
# File 'lib/bin_struct/int_string.rb', line 69 def to_s @length.to_s << @string.to_s end |