Class: PDTP::Client::FileBuffer

Inherits:
Object
  • Object
show all
Defined in:
lib/pdtp/client/file_buffer.rb

Overview

Handle a file buffer, which may be written to and read from randomly

Instance Method Summary collapse

Constructor Details

#initialize(output = nil) ⇒ FileBuffer

Returns a new instance of FileBuffer.



31
32
33
34
35
36
37
38
39
# File 'lib/pdtp/client/file_buffer.rb', line 31

def initialize(output = nil)
  # The output stream.  Treated as non-seekable since it may be a pipe
  @output = output
  @cursor = 0
  
  # The tempfile backbuffer.  This will always be seekable
  @buffer = Tempfile.new 'distribustream'
  @populated = []
end

Instance Method Details

#read(range) ⇒ Object



60
61
62
63
64
65
66
67
68
69
# File 'lib/pdtp/client/file_buffer.rb', line 60

def read(range)
  chunk = containing_chunk range.begin
  
  unless chunk and chunk.end >= range.end
    raise RuntimeError, "#{chunk.inspect} cannot satisfy range #{range.inspect}" 
  end
  
  @buffer.pos = range.begin
  @buffer.read(range.end - range.begin + 1)
end

#write(position, data) ⇒ Object

Write to the backbuffer. Write contiguous data to the output stream



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/pdtp/client/file_buffer.rb', line 42

def write(position, data)
  length = data.size
  return 0 if length.zero?
  
  range = position..(position + length - 1)
  
  # Insert the chunk into the buffer and return a new range of contiguous data
  writeable_range = insert_chunk range, data
  
  # If this chunk begins at the cursor, write it out
  if @output and writeable_range.begin == @cursor
    @cursor += @output.write read(writeable_range) 
  end
  
  # Return the length we just wrote
  length
end