Sha256: c58bb64509219995f2ada0be8e90b84d2e0ad606909bf4a579b33ecbda9bd8ac

Contents?: true

Size: 1.05 KB

Versions: 8

Compression:

Stored size: 1.05 KB

Contents

require "tempfile"

# BufferIO is used for writing big segments of text. When the segment is bigger than a certain number of bytes,
# the underlying memory buffer will be swapped with a tempfile
class Tracksperanto::BufferIO < DelegateClass(IO)
  include Tracksperanto::Returning
  
  MAX_IN_MEM_BYTES = 5_000_000
  
  def initialize
    __setobj__(StringIO.new)
  end
  
  def write(s)
    returning(super) { replace_with_tempfile_if_needed }
  end
  
  def puts(s)
    returning(super) { replace_with_tempfile_if_needed }
  end
  
  def <<(s)
    returning(super) { replace_with_tempfile_if_needed }
  end
  
  def putc(c)
    returning(super) { replace_with_tempfile_if_needed }
  end
  
  def close!
    __getobj__.close! if @tempfile_in
    __setobj__(nil)
  end
  
  private
  
  def replace_with_tempfile_if_needed
    return if @tempfile_in
    io = __getobj__
    if io.pos > MAX_IN_MEM_BYTES
      tf = Tempfile.new("tracksperanto-xbuf")
      tf.write(io.string)
      io.string = ""
      GC.start
      __setobj__(tf)
      @tempfile_in = true
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
tracksperanto-2.1.0 lib/tracksperanto/buffer_io.rb
tracksperanto-2.0.2 lib/tracksperanto/buffer_io.rb
tracksperanto-2.0.1 lib/tracksperanto/buffer_io.rb
tracksperanto-2.0.0 lib/tracksperanto/buffer_io.rb
tracksperanto-1.9.9 lib/tracksperanto/buffer_io.rb
tracksperanto-1.9.8 lib/tracksperanto/buffer_io.rb
tracksperanto-1.9.6 lib/tracksperanto/buffer_io.rb
tracksperanto-1.9.5 lib/tracksperanto/buffer_io.rb