End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
class method
IO::Buffer.map
IO::Buffer.map(file, [size, [offset, [flags]]]) → io_buffer
io_buffer.c
View on GitHub ↗
static VALUE
io_buffer_map(int argc, VALUE *argv, VALUE klass)
{
if (argc < 1 || argc > 4) {
rb_error_arity(argc, 2, 4);
}
// We might like to handle a string path?
VALUE io = argv[0];
size_t size;
if (argc >= 2 && !RB_NIL_P(argv[1])) {
size = RB_NUM2SIZE(argv[1]);
}
else {
off_t file_size = rb_file_size(io);
// Compiler can confirm that we handled file_size < 0 case:
if (file_size < 0) {
rb_raise(rb_eArgError, "Invalid negative file size!");
}
// Here, we assume that file_size is positive:
else if ((uintmax_t)file_size > SIZE_MAX) {
rb_raise(rb_eArgError, "File larger than address space!");
}
else {
// This conversion should be safe:
size = (size_t)file_size;
}
}
off_t offset = 0;
if (argc >= 3) {
offset = NUM2OFFT(argv[2]);
}
enum rb_io_buffer_flags flags = 0;
if (argc >= 4) {
flags = RB_NUM2UINT(argv[3]);
}
return rb_io_buffer_map(io, size, offset, flags);
}
Create an IO::Buffer for reading from file by memory-mapping the file. file_io should be a File instance, opened for reading.
Optional size and offset of mapping can be specified.
By default, the buffer would be immutable (read only); to create a writable mapping, you need to open a file in read-write mode, and explicitly pass flags argument without IO::Buffer::IMMUTABLE.
Example
File.write('test.txt', 'test') buffer = IO::Buffer.map(File.open('test.txt'), nil, 0, IO::Buffer::READONLY) # => #<IO::Buffer 0x00000001014a0000+4 MAPPED READONLY> buffer.readonly? # => true buffer.get_string # => "test" buffer.set_string('b', 0) # `set_string': Buffer is not writable! (IO::Buffer::AccessError) # create read/write mapping: length 4 bytes, offset 0, flags 0 buffer = IO::Buffer.map(File.open('test.txt', 'r+'), 4, 0) buffer.set_string('b', 0) # => 1 # Check it File.read('test.txt') # => "best"
Note that some operating systems may not have cache coherency between mapped buffers and file reads.