Sha256: 12ded9d9fb425ab428de80f282ea0623d5f4faa9b6333bef1a8b99f76525212c

Contents?: true

Size: 1.01 KB

Versions: 5

Compression:

Stored size: 1.01 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 = 100_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)
      __setobj__(tf)
      @tempfile_in = true
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
tracksperanto-1.9.4 lib/tracksperanto/buffer_io.rb
tracksperanto-1.9.3 lib/tracksperanto/buffer_io.rb
tracksperanto-1.9.2 lib/tracksperanto/buffer_io.rb
tracksperanto-1.9.1 lib/tracksperanto/buffer_io.rb
tracksperanto-1.9.0 lib/tracksperanto/buffer_io.rb