Class: BufferedIO

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

Overview

Simple class to allow for streamed (i.e. without pos support) IO to use the BinaryBlocker utilities, but buffering until flushed previously read information.

Constant Summary collapse

BLOCK_SIZE =
512

Instance Method Summary collapse

Constructor Details

#initialize(io) ⇒ BufferedIO

Rdoc



7
8
9
10
11
12
13
# File 'lib/buffered_io.rb', line 7

def initialize(io)
  super
  @io = io
  @buffer = ''
  @pos = 0
  @iobase = @io.pos
end

Instance Method Details

#flushObject



15
16
17
18
19
20
# File 'lib/buffered_io.rb', line 15

def flush
  @iobase += @pos
  @buffer = ''
  @pos = 0
  @io.flush
end

#posObject



32
33
34
# File 'lib/buffered_io.rb', line 32

def pos
  @iobase + @pos
end

#pos=(newpos) ⇒ Object



36
37
38
# File 'lib/buffered_io.rb', line 36

def pos=(newpos)
  seek(newpos) 
end

#read(size, buffer = nil) ⇒ Object



22
23
24
25
26
27
28
29
30
# File 'lib/buffered_io.rb', line 22

def read(size, buffer = nil)
  if (@buffer.size - @pos) < size
    @buffer += @io.read(BLOCK_SIZE)
  end
  result = @buffer[@pos,size]
  @pos += result.size
  buffer.replace(result) if buffer
  result
end

#seek(amount, whence = IO::SEEK_SET) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/buffered_io.rb', line 40

def seek(amount, whence=IO::SEEK_SET)
  case whence
  when IO::SEEK_CUR
    raise "rewind before buffer start" if (amount < @pos)
    @pos -= amount
    @iobase + @pos
    
  when IO::SEEK_END
    raise "Sorry this operation is not supported"
    
  when IO::SEEK_SET
    raise "rewind before buffer start" if (amount < @iobase)
    @pos = amount - @iobase
    @iobase + @pos      
  end
end