Class: Care::IOWrapper

Inherits:
Object
  • Object
show all
Defined in:
lib/care.rb

Overview

Wraps any given IO with Care caching superpowers. Supports the subset of IO declared in IOConstraint.

Instance Method Summary collapse

Constructor Details

#initialize(io, page_size: DEFAULT_PAGE_SIZE) ⇒ IOWrapper

Creates a new IOWrapper around the given source IO

Parameters:

  • io (#seek, #pos, #size)

    the IO to wrap

  • page_size (Integer) (defaults to: DEFAULT_PAGE_SIZE)

    the size of the cache page to use for this wrapper



17
18
19
20
21
# File 'lib/care.rb', line 17

def initialize(io, page_size: DEFAULT_PAGE_SIZE)
  @cache = Cache.new(page_size)
  @io = io
  @pos = 0
end

Instance Method Details

#clearObject

Clears all the cached pages explicitly to help GC

Returns:

  • void



62
63
64
# File 'lib/care.rb', line 62

def clear
  @cache.clear
end

#closeObject

Clears all the cached pages explicitly to help GC, and calls ‘#close` on the source IO if the IO responds to `#close`

Returns:

  • void



70
71
72
73
# File 'lib/care.rb', line 70

def close
  clear
  @io.close if @io.respond_to?(:close)
end

#posObject

Returns the current position/offset within the IO

Returns:

  • Integer



41
42
43
# File 'lib/care.rb', line 41

def pos
  @pos
end

#read(n_bytes) ⇒ String?

Returns at most ‘n_bytes` of data from the IO or less if less data was available before the EOF was hit

Parameters:

  • n_bytes (Integer)

Returns:

  • (String, nil)

    the content read from the IO or ‘nil` if no data was available

Raises:

  • (ArgumentError)


50
51
52
53
54
55
56
57
# File 'lib/care.rb', line 50

def read(n_bytes)
  return '' if n_bytes == 0 # As hardcoded for all Ruby IO objects
  raise ArgumentError, "negative length #{n_bytes} given" if n_bytes < 0 # also as per Ruby IO objects
  read = @cache.byteslice(@io, @pos, n_bytes)
  return unless read && !read.empty?
  @pos += read.bytesize
  read
end

#seek(to) ⇒ Object

Seeks the IO to the given absolute offset from the start of the file/resource

Parameters:

  • to (Integer)

    offset in the IO

Returns:

  • Integer



34
35
36
# File 'lib/care.rb', line 34

def seek(to)
  @pos = to
end

#sizeObject

Returns the size of the resource contained in the IO

Returns:

  • Integer



26
27
28
# File 'lib/care.rb', line 26

def size
  @io.size
end