module Writable
A module providing writable stream functionality.
You must implement the syswrite
method to write data to the underlying IO.
Definitions
def initialize(minimum_write_size: MINIMUM_WRITE_SIZE, **, &block)
Initialize writable stream functionality.
Signature
-
parameter
minimum_write_size
Integer
The minimum buffer size before flushing.
Implementation
def initialize(minimum_write_size: MINIMUM_WRITE_SIZE, **, &block)
@writing = ::Thread::Mutex.new
@write_buffer = StringBuffer.new
@minimum_write_size = minimum_write_size
super(**, &block) if defined?(super)
end
def flush
Flushes buffered data to the stream.
Implementation
def flush
return if @write_buffer.empty?
@writing.synchronize do
self.drain(@write_buffer)
end
end
def write(string, flush: false)
Writes string
to the buffer. When the buffer is full or #sync is true the
buffer is flushed to the underlying io
.
Signature
-
parameter
string
String
the string to write to the buffer.
-
returns
Integer
the number of bytes appended to the buffer.
Implementation
def write(string, flush: false)
@writing.synchronize do
@write_buffer << string
flush |= (@write_buffer.bytesize >= @minimum_write_size)
if flush
self.drain(@write_buffer)
end
end
return string.bytesize
end
def <<(string)
Appends string
to the buffer and returns self for method chaining.
Signature
-
parameter
string
String
the string to write to the stream.
Implementation
def <<(string)
write(string)
return self
end
def puts(*arguments, separator: $/)
Write arguments to the stream followed by a separator and flush immediately.
Signature
-
parameter
arguments
Array
The arguments to write to the stream.
-
parameter
separator
String
The separator to append after each argument.
Implementation
def puts(*arguments, separator: $/)
return if arguments.empty?
@writing.synchronize do
arguments.each do |argument|
@write_buffer << argument << separator
end
self.drain(@write_buffer)
end
end
def close_write
Close the write end of the stream by flushing any remaining data.
Implementation
def close_write
flush
end