iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
💎

Understanding Ruby IO::Buffer

に公開

This is the article for the 4th day of the Ruby/Rails Advent Calendar 2025.

https://qiita.com/advent-calendar/2025/ruby

IO::Buffer was added starting from Ruby 3.1, and since I wasn't very familiar with it, I decided to look into it.

https://docs.ruby-lang.org/en/master/IO/Buffer.html

It seems it was originally introduced for the Fiber Scheduler, but I'm not entirely sure about the details.

It appears to be designed for reading and modifying binary data directly from strings or file data. Since it is marked as experimental, I'll proceed with that in mind.

The following is what I've tried out on Linux while reading the documentation and source code. During my research, I found a bug in each_byte and fixed it.

Instance Creation

Creating with a specified size - IO::Buffer.new(size=IO::Buffer::DEFAULT_SIZE, flags=0)

Flags can be specified using a logical OR of IO::Buffer::INTERNAL and IO::Buffer::MAPPED.

IO::Buffer::INTERNAL allocates memory using malloc(3).
IO::Buffer::MAPPED uses mmap(2).

If neither is specified, it defaults to IO::Buffer::INTERNAL if the size is less than IO::Buffer::PAGE_SIZE (4096), or IO::Buffer::MAPPED otherwise.

If you specify IO::Buffer::INTERNAL | IO::Buffer::MAPPED, IO::Buffer::INTERNAL takes precedence. However, since the flags remain set as-is, both internal? and mapped? will be true, which feels somewhat problematic for subsequent operations.

Creating from a string (without a block) - IO::Buffer.for(string)

If the string is frozen, it is used as is; if not, it is copied and held within the IO::Buffer instance. The instance becomes read-only.
Modifying the string does not affect the buffer.

str = 'abcdefg'
b = IO::Buffer.for(str)
b.readonly?  #=> true
str[2,1] = 'x'
str  #=> "abxdefg"
b.get_string  #=> "abcdefg"

Creating from a string (with a block) - IO::Buffer.for(string) {|io_buffer| ...}

The string is not copied. Therefore, if you modify the IO::Buffer instance within the block, the string will also change. If the string is frozen, the instance becomes read-only.
The return value is the result of evaluating the block.
Attempting to modify the string within the block results in an error.

str = 'abcdefg'
IO::Buffer.for(str) do |b|
  b.set_string('hoge')
  b.get_string  #=> "hogeefg"
  str  #=> "hogeefg"
  str[0,4] = '0123'  #=> can't modify string; temporarily locked (RuntimeError)
end

Referencing the instance outside the block leaves it empty.

b = IO::Buffer.for('abcdefg'){ _1 }
b.get_string  #=> ""
b.null?  #=> true

Creating from a file - IO::Buffer.map(file, size=nil, offset=0, flags=0)

The contents of the file are mapped into memory, allowing read/write access. On Linux, it seems to internally use mmap(2).

File.write('/tmp/hoge', 'abcdefg')
f = File.open('/tmp/hoge', 'r+')
b = IO::Buffer.map(f)
b.set_string('hoge')
File.read('/tmp/hoge')  #=> "hogeefg"

If size is specified, it maps only that size. If offset is specified, it sets the position in the file to map.
Flags can be specified as a logical OR of IO::Buffer::READONLY and IO::Buffer::PRIVATE.
If the file is opened in read-only mode, you must specify IO::Buffer::READONLY or IO::Buffer::PRIVATE in the flags.
If IO::Buffer::READONLY is specified, the created object becomes non-writable.
IO::Buffer::PRIVATE is the same as MAP_PRIVATE in mmap(2). It maps to the file, but writes are held in private memory and are not reflected in the file.

f = File.open('/tmp/hoge', 'r')
IO::Buffer.map(f)  #=> Permission denied - io_buffer_map_file:mmap (Errno::EACCES)
IO::Buffer.map(f, nil, 0, IO::Buffer::READONLY)  #=> OK

Though it feels like an mmap(2) constraint, specifying a 0-byte file causes an error.

File.write('/tmp/empty', '')
f = File.open('/tmp/empty', 'r+')
IO::Buffer.map(f)  #=> Invalid argument - io_buffer_map_file:mmap (Errno::EINVAL)

If you create an instance specifying a size larger than the file size (specifically exceeding page boundaries), reading data will cause Ruby to crash with a Bus Error. This is not ideal.

File.write('/tmp/hoge', 'abcdefg')  #=> 7
IO::Buffer::PAGE_SIZE  #=> 4096
b = IO::Buffer.map(File.open('/tmp/hoge', 'r+'), 4097)
b.get_string
#=> [BUG] Bus Error at 0x000073c1bd0ca000
...

Also, seemingly a constraint of mmap(2), the offset must be specified in units of the OS page size, otherwise it causes an error.

File.write('/tmp/hoge', 'abcdefg'*1000) #=> 7000
f = File.open('/tmp/hoge', 'r+')
b = IO::Buffer.map(f, nil, 1024)  #=> Invalid argument - io_buffer_map_file:mmap (Errno::EINVAL)
b = IO::Buffer.map(f, nil, 4096)  #=> OK

map looks interesting, but it seems there are various things to be careful about, which makes it challenging.

Executing a block with a specified size and returning a string - IO::Buffer.string(length) {|io_buffer| ...}

Specifies the buffer size, executes the block, and returns an internally generated string object.

IO::Buffer.string(4){|b| b.set_string('hoge')}  #=> "hoge"

Reading from a Buffer

Extracting as a string - get_string(offset=0, length=nil, encoding=Encoding::BINARY)

Extracts buffer data as a string. Offset is the position in the buffer, length is the size. Both are in bytes.
If length is nil, it reads from the offset to the end.
Encoding is the encoding of the extracted string object.
Note that offset and length are always in bytes, even if an encoding is specified.

b = IO::Buffer.for('abcdefg')
b.get_string  #=> "abcdefg"
b.get_string(2, 4)  #=> "cdef"
b = IO::Buffer.for('ほげほげ')
b.get_string  #=> "\xE3\x81\xBB\xE3\x81\x92\xE3\x81\xBB\xE3\x81\x92"
b.get_string(0, nil, 'utf-8')  #=> "ほげほげ"
b.get_string(2, 5, 'utf-8')  #=> "\xBBげ\xE3"

The returned string is an ordinary string object not mapped to a file, so be aware that it consumes memory accordingly.

system "cat /proc/#$$/status | grep -E 'VmSize|VmData'"
# VmSize:	  593408 kB
# VmData:	  517288 kB

f = File.open('/tmp/largefile')
b = IO::Buffer.map(f, nil, 0, IO::Buffer::READONLY)
system "cat /proc/#$$/status | grep -E 'VmSize|VmData'"
# VmSize:	 1572916 kB  Virtual memory increases, but
# VmData:	  520232 kB  data area does not increase

s = b.get_string;
system "cat /proc/#$$/status | grep -E 'VmSize|VmData'"
# VmSize:	 2549868 kB
# VmData:	 1497184 kB  Data area increased by the size of the string

Extracting as a numeric value - get_value(buffer_type, offset)

Extracts data as a number by specifying the format. buffer_type is the format, offset is the position in the buffer.

s = "\x01\x02\x03\x04"
b = IO::Buffer.for(s)
b.get_value(:U8, 0)  #=> 0x01
b.get_value(:U16, 0)  #=> 0x102
b.get_value(:u16, 0)  #=> 0x201
b.get_value(:U32, 0)  #=> 0x01020304
b.get_value(:u32, 0)  #=> 0x04030201

Buffer type is specified as a symbol. U/u are unsigned integers, S/s are signed integers, and F/f are floating-point numbers. Uppercase is big-endian, lowercase is little-endian. The trailing number indicates the bit width.

  • :U8 - 1-byte unsigned integer
  • :S8 - 1-byte signed integer
  • :u16 - 2-byte unsigned integer (little-endian)
  • :U16 - 2-byte unsigned integer (big-endian)
  • :s16 - 2-byte signed integer (little-endian)
  • :S16 - 2-byte signed integer (big-endian)
  • :u32 - 4-byte unsigned integer (little-endian)
  • :U32 - 4-byte unsigned integer (big-endian)
  • :s32 - 4-byte signed integer (little-endian)
  • :S32 - 4-byte signed integer (big-endian)
  • :u64 - 8-byte unsigned integer (little-endian)
  • :U64 - 8-byte unsigned integer (big-endian)
  • :s64 - 8-byte signed integer (little-endian)
  • :S64 - 8-byte signed integer (big-endian)
  • :f32 - 4-byte floating-point number (little-endian)
  • :F32 - 4-byte floating-point number (big-endian)
  • :f64 - 8-byte floating-point number (little-endian)
  • :F64 - 8-byte floating-point number (big-endian)

Extracting multiple numeric values - get_values(buffer_types, offset)

Extracts values as an array of numbers by specifying the format as an array.

b = IO::Buffer.for("\x01\x02\x03\x04\x05\x06\x07\x08")
b.get_values([:U8, :U16, :U32], 0)  #=> [0x01, 0x0203, 0x04050607]

Extracting values repeatedly - values(buffer_type=:U8, offset=0, [count])

Extracts values repeatedly count times in the format of buffer_type.
If count is not specified, it reads until the end of the buffer.

b = IO::Buffer.for("\x01\x02\x03\x04\x05")
b.values  #=> [0x01, 0x02, 0x03, 0x04, 0x05]
b.values(:U16)  #=> [0x0102, 0x0304]
b.values(:U8, 2)  #=> [0x03, 0x4, 0x5]
b.values(:U8, 3, 1)  #=> [0x4]

Writing to a Buffer

Setting a string - set_string(string, offset=0, length=nil, source_offset=0)

Writes string to the buffer.

b = IO::Buffer.new(10)
b.set_string('abcdefg')
b.get_string  #=> "abcdefg\0\0\0"

b = IO::Buffer.new(10)
b.set_string('abcdefg', 4, 3, 2)  # Writes 3 bytes from position 2 of 'abcdefg' to position 4 of the buffer
b.get_string  #=> "\0\0\0\0cde\0\0\0"

Setting a numeric value - set_value(type, offset, value)

Writes the numeric value to the buffer at offset in the type format.

b = IO::Buffer.new(10)
b.set_value(:u32, 2, 0x12345678)
b.get_string  #=> "\0\0\x78\x56\x34\x12\0\0\0\0"

Setting multiple numeric values - set_values(buffer_types, offset, values)

Writes an array of values values to the buffer at offset, corresponding to the formats in buffer_types.

b = IO::Buffer.new(10)
b.set_values([:U8, :U16], 3, [1, 0x203])
b.get_string  #=> "\0\0\0\x01\x02\x03\0\0\0\0"

IO

Reading from IO to buffer - read(io, length=nil, offset=0)

Reads data into the buffer using the read method of the IO object. length here doesn't mean reading only the specified size, but reading until at least that size is reached. If length is nil, it reads until the end of the IO or buffer. If 0 is specified, a single read call is performed.

File.write('/tmp/x', '0123456789')
b = IO::Buffer.new(10)
f = File.open('/tmp/x')
b.read(f, nil, 3)
b.get_string  #=> "\0\0\00123456"

Reading from a specific position in IO to buffer - pread(io, from, length=nil, offset=0)

Reads data into the buffer using the pread method of the IO object, specifying the position in the IO with from.

File.write('/tmp/x', '0123456789')
b = IO::Buffer.new(10)
f = File.open('/tmp/x')
b.pread(f, 2, nil, 3)
b.get_string  #=> "\0\0\02345678"

Writing from buffer to IO - write(io, length=nil, offset=0)

Writes data from the buffer to the IO object io.

f = File.open('/tmp/x', 'w')
b = IO::Buffer.for('abcdefg')
b.write(f, nil, 2)
File.read('/tmp/x')  #=> "cdefg"

Writing from buffer to a specific position in IO - pwrite(io, from, length=nil, offset=0)

Writes buffer data to the IO object io using its pwrite method.

f = File.open('/tmp/x', 'w')
b = IO::Buffer.for('abcdefg')
b.pwrite(f, 3, nil, 2)
File.read('/tmp/x')  #=> "\0\0\0cdefg"

Iterators

Iterating by specifying data format - each(buffer_type=:U8, offset=0, [count]) {|offset, byte| ...}

Extracts data in buffer_type format from the buffer starting at offset and repeats the block count times. If no block is given, returns an enumerator.

b = IO::Buffer.for("\x00\x01\x02\x03\x04\x05\x06\x07")
b.each{|o, x| pp [o, x]}
#=> [0, 0]
#=> [1, 1]
#=> [2, 2]
#=> [3, 3]
#=> [4, 4]
#=> [5, 5]
#=> [6, 6]
#=> [7, 7]

b.each(:U16, 2, 3){|o, x| pp [o, x]}
#=> [2, 515]
#=> [4, 1029]
#=> [6, 1543]

Iterating by byte - each_byte(offset=0, [count]) {|byte| ...}

Extracts byte data from the buffer starting at offset and repeats the block count times.

b = IO::Buffer.for('abcdefg')
b.each_byte{|x| pp x}
#=> 97
#=> 98
#=> 99
#=> 100
#=> 101
#=> 102
#=> 103

b.each_byte(nil, 2, 3){|x| pp x}
#=> 99
#=> 100
#=> 101

State

empty?

Returns true if the buffer size is 0, otherwise false.

internal?

True if the buffer references internal data (?).

external?

True if the buffer references external data (?).

Sometimes both external? and internal? can be false, which I don't fully understand.

locked?

True if locked.

mapped?

True if the buffer was created with mmap(2).

null?

True if initialized with size 0 or freed.

private?

True if created with the IO::Buffer::PRIVATE flag.

shared?

True if created with the IO::Buffer::SHARED flag.

readonly?

True if read-only.

valid?

True if the buffer is accessible.

Bitwise Operations

Logical AND - &

Returns an IO::Buffer object resulting from the logical AND of the left-hand buffer with the right-hand buffer. If the right-hand side is shorter than the left, it is applied repeatedly.

a = IO::Buffer.for('abcdefg')
b = IO::Buffer.for("\xff\x5f")
c = a & b
c.get_string  #=> "aBcDeFg"

Logical AND (destructive) - and!

Same as &, except that self is modified.

a = IO::Buffer.for('abcdefg').dup
b = IO::Buffer.for("\xff\x5f")
a.and!(b)
a.get_string  #=> "aBcDeFg"

Logical OR - |

Returns an IO::Buffer object resulting from the logical OR of the left-hand buffer with the right-hand buffer. If the right-hand side is shorter than the left, it is applied repeatedly.

a = IO::Buffer.for('ABCDEFG')
b = IO::Buffer.for("\x00\x20")
c = a | b
c.get_string  #=> "AbCdEfG"

Logical OR (destructive) - or!

Same as |, except that self is modified.

a = IO::Buffer.for('ABCDEFG').dup
b = IO::Buffer.for("\x00\x20")
a.or!(b)
a.get_string  #=> "AbCdEfG"

Exclusive OR - ^

Returns an IO::Buffer object resulting from the exclusive OR of the left-hand buffer with the right-hand buffer. If the right-hand side is shorter than the left, it is applied repeatedly.

a = IO::Buffer.for("\x01\x02\x03\x04\x05")
b = IO::Buffer.for("\x00\xff")
c = a ^ b
c.get_string  #=> "\x01\xFD\x03\xFB\x05"

Exclusive OR (destructive) - xor!

Same as ^, except that self is modified.

a = IO::Buffer.for("\x01\x02\x03\x04\x05").dup
b = IO::Buffer.for("\x00\xff")
a.xor!(b)
a.get_string  #=> "\x01\xFD\x03\xFB\x05"

Negation - ~

Returns an IO::Buffer object resulting from the logical negation of the buffer.

a = IO::Buffer.for("\x01\x02\x03\x04\x05")
b = ~a
b.get_string  #=> "\xFE\xFD\xFC\xFB\xFA"

Negation (destructive) - not!

Same as ~, except that self is modified.

b = IO::Buffer.for("\x01\x02\x03\x04\x05").dup
b.not!
b.get_string  #=> "\xFE\xFD\xFC\xFB\xFA"

Other

Comparison - <=>

Compares the left-hand side and right-hand side byte by byte; returns -1 if the left is smaller, 0 if equal, and 1 if the right is smaller.

a = IO::Buffer.for('0123')
b = IO::Buffer.for('0246')
a <=> b  #=> -1

Clear - clear(value=0, offset=0, length=nil)

Replaces length bytes of data from offset with value.

b = IO::Buffer.for('abcdefg').dup
b.clear
b.get_string  #=> "\x00\x00\x00\x00\x00\x00\x00"
b.clear(1)
b.get_string  #=> "\x01\x01\x01\x01\x01\x01\x01"
b.clear(9, 2)
b.get_string  #=> "\x01\x01\x09\x09\x09\x09\x09"
b.clear(5, 3, 2)
b.get_string  #=> "\x01\x01\x09\x05\x05\x09\x09"

Copy - copy(source, offset=0, length=nil, source_offset=0)

Copies length bytes of data from source to offset.

s = IO::Buffer.for('abcdefg')
d = IO::Buffer.for('0123456789').dup
d.copy(s)
d.get_string  #=> "abcdefg789"

d = IO::Buffer.for('0123456789').dup
d.copy(s, 3, 2)
d.get_string  #=> "012ab56789"

Free - free

Frees the buffer.

b = IO::Buffer.for('abcdefg')
b.size  #=> 7
b.free
b.size  #=> 0
b.null?  #=> true

Hex Dump - hexdump(offset=0, length=nil, width=16)

Outputs length bytes of data from offset in hex dump format as a string.

b = IO::Buffer.for('abcdfeg')
b.hexdump
#=> "0x00000000  61 62 63 64 65 66 67                            abcdefg"

Duplicate - dup / clone

Duplicates the object. The internal buffer is also copied, breaking the connection with the external object.

Inspect - inspect

Returns a string for inspection, including a hex dump of the first 256 bytes.

Lock - locked {...}

Locks the buffer and executes the block.

Locking is not thread safe. It is designed as a safety net around non-blocking system calls. You can only share a buffer between threads with appropriate synchronisation techniques.

As it says it is not thread-safe, use caution.

Resize - resize(new_size)

Resizes the buffer to new_size. Buffers mapped as readonly or shared cannot be resized.

Size - size

Returns the buffer size.

Slice - slice(offset=0, length=nil)

Slices length bytes from offset and returns a new IO::Buffer object.
The buffer of the new object is shared with the original object.

String conversion - to_s

Returns buffer information as a string. Same as inspect but without the hex dump.

Transfer - transfer

Returns a new IO::Buffer object that has taken ownership of the buffer. The original buffer becomes empty.

b = IO::Buffer.for('abcdefg')
t = b.transfer
b.get_string  #=> ""
t.get_string  #=> "abcdefg"

IO::Buffer is experimental, so it seems there are still some rough edges, but I enjoy libraries at this layer, so I plan to use it.

Discussion