Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

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. The offset must be a multiple of IO::Buffer::MAP_ALIGNMENT. The size does not need to be aligned. Trying to map an empty file or specify size of 0 will raise an error.

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.

The mapping mode may be explicitly selected with IO::Buffer::SHARED or IO::Buffer::PRIVATE, but the two flags are mutually exclusive. IO::Buffer::MAPPED is accepted but redundant because this method always creates a mapped buffer. IO::Buffer::INTERNAL and IO::Buffer::EXTERNAL cannot be specified.

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.0 · 3.4 · 3.3 · 3.2 · 3.1