Class: Cyc::Connection::DataBuffer

Inherits:
Object
  • Object
show all
Defined in:
lib/cyc/connection/buffer.rb

Overview

Author

Rafal Michalski ([email protected])

Licence

MIT/X11 License

DataBuffer is chunky text data to server answer assembly class.

Usage:

b = DataBuffer.new
b << "200 Some response\n" << "300 Some other" << " response\n" << "additional data\n"
b.next_result
=> [200, "Some response"]
b.next_result
=> [300, "Some other response\nadditional data"]
b.next_result
=> nil
b << "Invalid response\n"
b.next_result("meta data")
Cyc::ProtocolError:
  Unexpected data from server: "Invalid response", check the submitted query in detail:
    "meta data"

Constant Summary collapse

EOL =
"\n"
RESULT_MATCH =
/^(\d\d\d) (.*)$/m

Instance Method Summary collapse

Constructor Details

#initializeDataBuffer

Initializes an empty buffer.



31
32
33
# File 'lib/cyc/connection/buffer.rb', line 31

def initialize
  @buffer = ""
end

Instance Method Details

#<<(data) ⇒ Object

Appends data to the buffer.



36
37
38
# File 'lib/cyc/connection/buffer.rb', line 36

def <<(data)
  @buffer << data
end

#discard!Object

Clears the buffer contents.



64
65
66
# File 'lib/cyc/connection/buffer.rb', line 64

def discard!
  @buffer.clear
end

#next_result(org_message = nil) ⇒ Object

Returns the next complete result stored in the buffer.



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/cyc/connection/buffer.rb', line 41

def next_result(org_message=nil)
  res_end = 0
  size = @buffer.length
  while res_end = @buffer.index(EOL, res_end)
    res_end += 1
    if res_end == size || RESULT_MATCH === @buffer[res_end..-1]
      result = @buffer.slice!(0, res_end).chomp EOL
      if RESULT_MATCH === result
        return [$1.to_i, $2]
      else
        raise ProtocolError.new("Unexpected data from server: #{result.inspect}, " +
          "check the submitted query in detail:\n#{org_message.inspect}")
      end
    end
  end
end

#to_sObject

String representation of the buffer.



59
60
61
# File 'lib/cyc/connection/buffer.rb', line 59

def to_s
  @buffer
end