Skip to content
class method

IO::Buffer.map

(::File file, ?::Integer? size, ?::Integer offset, ?::Integer flags) -> ::IO::Buffer
IO::Buffer.map(file, [size, [offset, [flags]]]) → io_buffer

Create an IO::Buffer for reading from file by memory-mapping the file. file should be a File instance, opened for reading or reading and writing.

Optional size and offset of mapping can be specified. Trying to map an empty file or specify size of 0 will raise an error. Valid values for offset are system-dependent.

By default, the buffer is writable and expects the file to be writable. It is also shared, so several processes can use the same mapping.

You can pass IO::Buffer::READONLY in flags argument to make a read-only buffer; this allows to work with files opened only for reading. Specifying IO::Buffer::PRIVATE in flags creates a private mapping, which will not impact other processes or the underlying file. It also allows updating a buffer created from a read-only file.

Example
File.write('test.txt', 'test')

buffer = IO::Buffer.map(File.open('test.txt'), nil, 0, IO::Buffer::READONLY)
# => #<IO::Buffer 0x00000001014a0000+4 EXTERNAL MAPPED FILE SHARED READONLY>

buffer.readonly?   # => true

buffer.get_string
# => "test"

buffer.set_string('b', 0)
# 'IO::Buffer#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.

See also .for .new .size_of also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1