Class: Cyclid::API::StringFIFO

Inherits:
Object
  • Object
show all
Defined in:
app/cyclid/log_buffer.rb

Overview

Simple in-memory FIFO; inspired by StringIO but reads & writes maintain their own position. It’s unlike a file enough to not be derived from IO.

Instance Method Summary collapse

Constructor Details

#initializeStringFIFO

Returns a new instance of StringFIFO.



23
24
25
26
27
# File 'app/cyclid/log_buffer.rb', line 23

def initialize
  @buffer = String.new
  @write_pos = 0
  @read_pos = 0
end

Instance Method Details

#clearObject

Reset the buffer, read & write positions



61
62
63
64
65
# File 'app/cyclid/log_buffer.rb', line 61

def clear
  @buffer = ''
  @write_pos = 0
  @read_pos = 0
end

#read(length = nil) ⇒ Object

Read data from the buffer. If length is given, read at most length characters from the buffer or whatever is available, whichever is smaller.

Completely non-blocking; if no data is available, returns an empty string.



41
42
43
44
45
46
47
48
49
50
51
# File 'app/cyclid/log_buffer.rb', line 41

def read(length = nil)
  len = if length
          [length, @write_pos].min
        else
          @write_pos
        end
  start = @read_pos
  @read_pos += len

  @buffer[start, len]
end

#stringObject Also known as: to_s

Return the entire contents of the buffer



54
55
56
# File 'app/cyclid/log_buffer.rb', line 54

def string
  @buffer
end

#write(data) ⇒ Object

Append data to the buffer & update the write position



30
31
32
33
# File 'app/cyclid/log_buffer.rb', line 30

def write(data)
  @buffer += data
  @write_pos += data.length
end