Class: Vagrant::Util::LineBuffer

Inherits:
Object
  • Object
show all
Defined in:
lib/vagrant/util/line_buffer.rb

Constant Summary collapse

MAX_LINE_LENGTH =

Maximum number of characters to buffer before sending to callback without detecting a new line

5000.freeze

Instance Method Summary collapse

Constructor Details

#initialize(&callback) ⇒ LineBuffer

Create a new line buffer. The registered block will be called when a new line is encountered on provided input, or the max line length is reached

Raises:

  • (ArgumentError)


12
13
14
15
16
17
18
# File 'lib/vagrant/util/line_buffer.rb', line 12

def initialize(&callback)
  raise ArgumentError,
    "Expected callback but received none" if callback.nil?
  @mu = Mutex.new
  @callback = callback
  @buffer = ""
end

Instance Method Details

#<<(str) ⇒ self

Add string data to output



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/vagrant/util/line_buffer.rb', line 24

def <<(str)
  @mu.synchronize do
    while i = str.index("\n")
      @callback.call((@buffer + str[0, i+1]).rstrip)
      @buffer.clear
      str = str[i+1, str.length].to_s
    end

    @buffer << str.to_s

    if @buffer.length > MAX_LINE_LENGTH
      @callback.call(@buffer.dup)
      @buffer.clear
    end
  end
  self
end

#closeself

Closes the buffer. Any remaining data that has been buffered will be given to the callback. Once closed the instance will no longer be usable.



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/vagrant/util/line_buffer.rb', line 47

def close
  @mu.synchronize do
    # Send any remaining output on the buffer
    @callback.call(@buffer.dup) if !@buffer.empty?
    # Disable this buffer instance
    @callback = nil
    @buffer.clear
    @buffer.freeze
  end
  self
end