Class: Care::IOWrapper
- Inherits:
-
Object
- Object
- Care::IOWrapper
- 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
-
#clear ⇒ Object
Clears all the cached pages explicitly to help GC.
-
#close ⇒ Object
Clears all the cached pages explicitly to help GC, and calls ‘#close` on the source IO if the IO responds to `#close`.
-
#initialize(io, page_size: DEFAULT_PAGE_SIZE) ⇒ IOWrapper
constructor
Creates a new IOWrapper around the given source IO.
-
#pos ⇒ Object
Returns the current position/offset within the IO.
-
#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.
-
#seek(to) ⇒ Object
Seeks the IO to the given absolute offset from the start of the file/resource.
-
#size ⇒ Object
Returns the size of the resource contained in the IO.
Constructor Details
#initialize(io, page_size: DEFAULT_PAGE_SIZE) ⇒ IOWrapper
Creates a new IOWrapper around the given source IO
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
#clear ⇒ Object
Clears all the cached pages explicitly to help GC
62 63 64 |
# File 'lib/care.rb', line 62 def clear @cache.clear end |
#close ⇒ Object
Clears all the cached pages explicitly to help GC, and calls ‘#close` on the source IO if the IO responds to `#close`
70 71 72 73 |
# File 'lib/care.rb', line 70 def close clear @io.close if @io.respond_to?(:close) end |
#pos ⇒ Object
Returns the current position/offset within the IO
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
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
34 35 36 |
# File 'lib/care.rb', line 34 def seek(to) @pos = to end |
#size ⇒ Object
Returns the size of the resource contained in the IO
26 27 28 |
# File 'lib/care.rb', line 26 def size @io.size end |