Class: Cosmos::BufferedFile
Constant Summary collapse
- BUFFER_SIZE =
16 * 1024
Constants inherited from File
Instance Method Summary collapse
-
#initialize(*args) ⇒ BufferedFile
constructor
Initialize the BufferedFile.
-
#pos ⇒ Object
Get the current file position.
-
#read(read_length) ⇒ Object
Read using an internal buffer to avoid system calls.
-
#seek(*args) ⇒ Object
Seek to a given file position.
Methods inherited from File
build_timestamped_filename, find_in_search_path, is_ascii?
Constructor Details
#initialize(*args) ⇒ BufferedFile
Initialize the BufferedFile. Takes the same args as File
19 20 21 22 23 |
# File 'lib/cosmos/io/buffered_file.rb', line 19 def initialize(*args) super(*args) @buffer = '' @buffer_index = 0 end |
Instance Method Details
#pos ⇒ Object
Get the current file position
65 66 67 68 |
# File 'lib/cosmos/io/buffered_file.rb', line 65 def pos parent_pos = super() return parent_pos - (@buffer.length - @buffer_index) end |
#read(read_length) ⇒ Object
Read using an internal buffer to avoid system calls
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/cosmos/io/buffered_file.rb', line 26 def read(read_length) if read_length <= (@buffer.length - @buffer_index) # Return part of the buffer without having to go to the OS result = @buffer[@buffer_index, read_length] @buffer_index += read_length return result elsif read_length > BUFFER_SIZE # Reading more than our buffer if @buffer.length > 0 if @buffer_index > 0 @buffer.slice!(0..(@buffer_index - 1)) @buffer_index = 0 end @buffer << super(read_length - @buffer.length).to_s return @buffer.slice!(0..-1) else return super(read_length) end else # Read into the buffer if @buffer_index > 0 @buffer.slice!(0..(@buffer_index - 1)) @buffer_index = 0 end @buffer << super(BUFFER_SIZE - @buffer.length).to_s if @buffer.length <= 0 return nil end if read_length <= @buffer.length result = @buffer[@buffer_index, read_length] @buffer_index += read_length return result else return @buffer.slice!(0..-1) end end end |
#seek(*args) ⇒ Object
Seek to a given file position
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
# File 'lib/cosmos/io/buffered_file.rb', line 71 def seek(*args) case args.length when 1 amount = args[0] whence = IO::SEEK_SET when 2 amount = args[0] whence = args[1] else # Invalid number of arguments given - let super handle return super(*args) end if whence == IO::SEEK_CUR buffer_index = @buffer_index + amount if (buffer_index >= 0) && (buffer_index < @buffer.length) @buffer_index = buffer_index return 0 end super(self.pos, IO::SEEK_SET) end @buffer.clear @buffer_index = 0 return super(*args) end |