Class: Omnizip::IO::BufferedOutput

Inherits:
Object
  • Object
show all
Defined in:
lib/omnizip/io/buffered_output.rb

Overview

Buffered output stream for efficient writing.

This class provides buffered writing capabilities to minimize I/O operations and improve performance.

Constant Summary collapse

DEFAULT_BUFFER_SIZE =
65_536

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(destination, buffer_size: DEFAULT_BUFFER_SIZE) ⇒ BufferedOutput

Initialize buffered output.

Parameters:

  • destination (IO, #write)

    Output destination

  • buffer_size (Integer) (defaults to: DEFAULT_BUFFER_SIZE)

    Size of internal buffer



34
35
36
37
38
39
# File 'lib/omnizip/io/buffered_output.rb', line 34

def initialize(destination, buffer_size: DEFAULT_BUFFER_SIZE)
  @destination = destination
  @buffer_size = buffer_size
  @buffer = String.new(capacity: buffer_size)
  @position = 0
end

Instance Attribute Details

#buffer_sizeObject (readonly)

Returns the value of attribute buffer_size.



28
29
30
# File 'lib/omnizip/io/buffered_output.rb', line 28

def buffer_size
  @buffer_size
end

#destinationObject (readonly)

Returns the value of attribute destination.



28
29
30
# File 'lib/omnizip/io/buffered_output.rb', line 28

def destination
  @destination
end

#positionObject (readonly)

Returns the value of attribute position.



28
29
30
# File 'lib/omnizip/io/buffered_output.rb', line 28

def position
  @position
end

Instance Method Details

#closevoid

This method returns an undefined value.

Close the stream and flush remaining data.



85
86
87
88
# File 'lib/omnizip/io/buffered_output.rb', line 85

def close
  flush
  @destination.close if @destination.respond_to?(:close)
end

#flushvoid

This method returns an undefined value.

Flush buffered data to destination.



75
76
77
78
79
80
# File 'lib/omnizip/io/buffered_output.rb', line 75

def flush
  return if @buffer.empty?

  @destination.write(@buffer)
  @buffer.clear
end

#write(data) ⇒ Integer

Write data to the stream.

Parameters:

  • data (String)

    Data to write

Returns:

  • (Integer)

    Number of bytes written



45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/omnizip/io/buffered_output.rb', line 45

def write(data)
  return 0 if data.nil? || data.empty?

  bytes_written = 0
  offset = 0

  while offset < data.bytesize
    offset = write_chunk(data, offset)
    bytes_written = offset
  end

  bytes_written
end

#write_byte(byte) ⇒ Integer

Write a single byte.

Parameters:

  • byte (Integer)

    Byte value (0-255)

Returns:

  • (Integer)

    Number of bytes written (1)



63
64
65
66
67
68
69
70
# File 'lib/omnizip/io/buffered_output.rb', line 63

def write_byte(byte)
  @buffer << byte.chr
  @position += 1

  flush if @buffer.bytesize >= @buffer_size

  1
end