class QuartzTorrent::OutputBuffer

Simple class used to buffer output for an IO until it’s ready for writing. This is not part of the public API; it’s used internally by the IOInfo class.

Public Class Methods

new(io, seekable = false) click to toggle source

Create a new OutputBuffer for the specified IO. The parameter seekable should be true or false. If true, then this output buffer will support seek at the cost of performance.

# File lib/quartz_torrent/reactor.rb, line 152
def initialize(io, seekable = false)
  @io = io
  @seekable = seekable
  if seekable
    @buffer = []
  else
    @buffer = ''
  end
end

Public Instance Methods

append(data) click to toggle source

Append data to the buffer.

# File lib/quartz_torrent/reactor.rb, line 173
def append(data)
  if ! @seekable
    @buffer << data
  else
    @buffer.push [@io.tell, data]
  end
end
empty?() click to toggle source

Is the buffer empty?

# File lib/quartz_torrent/reactor.rb, line 163
def empty?
  @buffer.length == 0
end
flush(max = nil) click to toggle source

Write the contents of the output buffer to the io. This method throws all of the exceptions that write would throw (EAGAIN, EWOULDBLOCK, etc) If max is specified and this is a non-seekable io, at most that many bytes are written.

# File lib/quartz_torrent/reactor.rb, line 184
def flush(max = nil)
  if ! @seekable
    toWrite = @buffer.length
    toWrite = max if max && max < @buffer.length
    numWritten = 0
    while toWrite > 0
      numWritten = @io.write_nonblock(@buffer[0,toWrite])
      raise Errno::EAGAIN if numWritten == 0
      @buffer = @buffer[numWritten,@buffer.length]
      toWrite -= numWritten
    end
  else
    while @buffer.length > 0
      @io.seek @buffer.first[0], IO::SEEK_SET
      while @buffer.first[1].length > 0
        numWritten = @io.write_nonblock(@buffer.first[1])
        raise Errno::EAGAIN if numWritten == 0
        @buffer.first[1] = @buffer.first[1][numWritten,@buffer.first[1].length]
      end
      # This chunk has been fully written. Remove it
      @buffer.shift
    end
  end
end
size() click to toggle source

Number of bytes in the buffer.

# File lib/quartz_torrent/reactor.rb, line 168
def size
  @buffer.length
end