Sha256: 4fc2cd6dca697d83fb02acc6469a82a01c421a7e8035aedb95ebbdf7456bf256

Contents?: true

Size: 1023 Bytes

Versions: 1

Compression:

Stored size: 1023 Bytes

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
  alias_method :<<, :write
  
  def puts(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

1 entries across 1 versions & 1 rubygems

Version Path
tracksperanto-2.1.1 lib/tracksperanto/buffer_io.rb