Class: MultiCompress::Reader

Inherits:
Object
  • Object
show all
Defined in:
lib/multi_compress.rb,
ext/multi_compress/multi_compress.c

Overview

Streaming compressed reader.

Supports block form via Reader.open or manual lifecycle management.

Constant Summary collapse

CHUNK_SIZE =
8192

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(io, algo: nil, dictionary: nil) ⇒ Reader

Returns a new instance of Reader.



182
183
184
185
186
187
188
189
# File 'lib/multi_compress.rb', line 182

def initialize(io, algo: nil, dictionary: nil)
  @io       = io
  @inflater = Inflater.new(algo: algo, dictionary: dictionary)
  @closed   = false
  @owned_io = false
  @buffer   = +""
  @eof      = false
end

Class Method Details

.open(path_or_io, algo: nil, dictionary: nil, &block) ⇒ Object



168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/multi_compress.rb', line 168

def self.open(path_or_io, algo: nil, dictionary: nil, &block)
  io, algo, owned = resolve_io(path_or_io, algo, mode: "rb")
  reader = new(io, algo: algo, dictionary: dictionary)
  reader.instance_variable_set(:@owned_io, owned)

  return reader unless block

  begin
    yield reader
  ensure
    reader.close
  end
end

Instance Method Details

#closeObject



210
211
212
213
214
215
216
217
# File 'lib/multi_compress.rb', line 210

def close
  return if @closed

  @inflater.close
  @io.close if @owned_io && @io.respond_to?(:close)
  @closed = true
  nil
end

#closed?Boolean

Returns:

  • (Boolean)


219
220
221
# File 'lib/multi_compress.rb', line 219

def closed?
  @closed
end

#each_chunk(size) ⇒ Object



235
236
237
238
239
240
241
242
# File 'lib/multi_compress.rb', line 235

def each_chunk(size)
  return enum_for(:each_chunk, size) unless block_given?

  while (chunk = read(size))
    yield chunk
    break if chunk.bytesize < size
  end
end

#each_lineObject



227
228
229
230
231
232
233
# File 'lib/multi_compress.rb', line 227

def each_line
  return enum_for(:each_line) unless block_given?

  while (line = gets)
    yield line
  end
end

#eof?Boolean

Returns:

  • (Boolean)


223
224
225
# File 'lib/multi_compress.rb', line 223

def eof?
  @eof && @buffer.empty?
end

#gets(separator = "\n") ⇒ Object



198
199
200
201
202
203
204
205
206
207
208
# File 'lib/multi_compress.rb', line 198

def gets(separator = "\n")
  ensure_open!
  return nil if @eof && @buffer.empty?

  fill_buffer_until { @buffer.include?(separator) }

  return extract_line(separator) if @buffer.include?(separator)
  return consume_buffer unless @buffer.empty?

  nil
end

#read(length = nil) ⇒ Object



191
192
193
194
195
196
# File 'lib/multi_compress.rb', line 191

def read(length = nil)
  ensure_open!
  return read_all if length.nil?

  read_exactly(length)
end

#readlineObject



244
245
246
# File 'lib/multi_compress.rb', line 244

def readline
  gets || raise(EOFError, "end of file reached")
end