Class: ThreadQueues::StringBuffer

Inherits:
Object
  • Object
show all
Defined in:
lib/thread_queues/string_buffer.rb

Instance Method Summary collapse

Constructor Details

#initialize(queue) ⇒ StringBuffer

Returns a new instance of StringBuffer.



4
5
6
7
8
# File 'lib/thread_queues/string_buffer.rb', line 4

def initialize(queue)
  @queue = queue
  @buffer = ""
  @mutex = Monitor.new
end

Instance Method Details

#getsObject



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/thread_queues/string_buffer.rb', line 10

def gets
  @mutex.synchronize do
    loop do
      if match = @buffer.match(/\A(.+)\n/)
        @buffer.gsub!(/\A(.+)\n/, "")
        return match[0]
      end

      begin
        store_more_in_buffer
      rescue EOFError => e
        return @buffer if @buffer.length > 0
        raise e
      end
    end
  end
end

#read(length) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/thread_queues/string_buffer.rb', line 28

def read(length)
  @mutex.synchronize do
    loop do
      if @buffer.length >= length
        return @buffer.slice!(0, length)
      end

      begin
        store_more_in_buffer
      rescue EOFError => e
        return @buffer if @buffer.length > 0
        raise e
      end
    end
  end
end