Class: PDTP::LengthPrefixProtocol::Prefix
- Inherits:
-
Object
- Object
- PDTP::LengthPrefixProtocol::Prefix
- Defined in:
- lib/pdtp/common/length_prefix_protocol.rb
Overview
Class for processing size prefixes in packet frames
Instance Attribute Summary collapse
-
#data ⇒ Object
readonly
Returns the value of attribute data.
-
#size ⇒ Object
readonly
Returns the value of attribute size.
Instance Method Summary collapse
-
#append(data) ⇒ Object
Append data to the prefix and return any extra.
-
#initialize(size = 2) ⇒ Prefix
constructor
A new instance of Prefix.
-
#payload_length ⇒ Object
Length of the payload extracted from the prefix.
-
#read? ⇒ Boolean
Has the entire prefix been read yet?.
- #reset! ⇒ Object
Constructor Details
#initialize(size = 2) ⇒ Prefix
Returns a new instance of Prefix.
33 34 35 36 37 38 39 40 |
# File 'lib/pdtp/common/length_prefix_protocol.rb', line 33 def initialize(size = 2) unless size == 2 or size == 4 raise ArgumentError, 'only 2 or 4 byte prefixes are supported' end @size = size reset! end |
Instance Attribute Details
#data ⇒ Object (readonly)
Returns the value of attribute data.
31 32 33 |
# File 'lib/pdtp/common/length_prefix_protocol.rb', line 31 def data @data end |
#size ⇒ Object (readonly)
Returns the value of attribute size.
31 32 33 |
# File 'lib/pdtp/common/length_prefix_protocol.rb', line 31 def size @size end |
Instance Method Details
#append(data) ⇒ Object
Append data to the prefix and return any extra
48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/pdtp/common/length_prefix_protocol.rb', line 48 def append(data) toread = @size - @read new_data = data[0..(toread - 1)] @data << new_data @read += new_data.size return nil unless @read == @size @payload_length = @data.unpack(@size == 2 ? 'n' : 'N').first result = data[toread..data.length] return nil if result.nil? or result.empty? result end |
#payload_length ⇒ Object
Length of the payload extracted from the prefix
64 65 66 67 |
# File 'lib/pdtp/common/length_prefix_protocol.rb', line 64 def payload_length raise RuntimeError, 'payload_length called before prefix extracted' unless read? @payload_length end |
#read? ⇒ Boolean
Has the entire prefix been read yet?
43 44 45 |
# File 'lib/pdtp/common/length_prefix_protocol.rb', line 43 def read? @size == @read end |
#reset! ⇒ Object
69 70 71 72 73 |
# File 'lib/pdtp/common/length_prefix_protocol.rb', line 69 def reset! @payload_length = nil @read = 0 @data = '' end |