End of Life Ruby 3.2 has reached end of life and gets no more fixes. 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);
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
size_t offset = 0, length = 0;
if (argc > 0) {
if (rb_int_negative_p(argv[0])) {
rb_raise(rb_eArgError, "Offset can't be negative!");
}
offset = NUM2SIZET(argv[0]);
}
if (argc > 1) {
if (rb_int_negative_p(argv[1])) {
rb_raise(rb_eArgError, "Length can't be negative!");
}
length = NUM2SIZET(argv[1]);
} else {
length = data->size - offset;
}
return rb_io_buffer_slice(data, 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.
The slicing happens without copying of memory, and the slice keeps being associated with the original buffer’s source (string, or file), if any.
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.
Example:
string = 'test' buffer = IO::Buffer.for(string) 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 SLICE> # 0x00000000 74 6f 73 74 tost # ...and original string string # => tost