Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
IO::Buffer#slice
static VALUE
io_buffer_slice(int argc, VALUE *argv, VALUE self)
{
rb_check_arity(argc, 0, 2);
size_t offset, length;
struct rb_io_buffer_view *buffer = io_buffer_extract_offset_length(self, argc, argv, &offset, &length);
return rb_io_buffer_slice(buffer, self, offset, length);
}
Produce another IO::Buffer which is a slice (or view into) the current one starting at offset bytes and going for length bytes.
Slicing does not copy memory. The slice retains self as its source and tracks a logical offset and length within that view. Nested slices retain their immediate parent rather than being flattened.
A slice becomes invalid if its source is freed, transferred, resized so that the slice is outside its bounds, or otherwise invalidated. It becomes valid again if the source becomes valid and the range fits within it. Reallocating the underlying storage does not invalidate the slice.
If the offset is not given, it will be zero. If the offset is negative, it will raise an ArgumentError.
If the length is not given, the slice will be as long as the original buffer minus the specified offset. If the length is negative, it will raise an ArgumentError.
Raises RuntimeError if the offset+length is out of the current buffer’s bounds.
string = 'test' buffer = IO::Buffer.for(string).dup slice = buffer.slice # => # #<IO::Buffer 0x0000000108338e68+4 SLICE> # 0x00000000 74 65 73 74 test buffer.slice(2) # => # #<IO::Buffer 0x0000000108338e6a+2 SLICE> # 0x00000000 73 74 st slice = buffer.slice(1, 2) # => # #<IO::Buffer 0x00007fc3d34ebc49+2 SLICE> # 0x00000000 65 73 es # Put "o" into 0s position of the slice slice.set_string('o', 0) slice # => # #<IO::Buffer 0x00007fc3d34ebc49+2 SLICE> # 0x00000000 6f 73 os # it is also visible at position 1 of the original buffer buffer # => # #<IO::Buffer 0x00007fc3d31e2d80+4 INTERNAL> # 0x00000000 74 6f 73 74 tost