End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
IO::Buffer#slice
slice(offset, length) → io_buffer
io_buffer.c
View on GitHub ↗
VALUE
rb_io_buffer_slice(VALUE self, VALUE _offset, VALUE _length)
{
// TODO fail on negative offets/lengths.
size_t offset = NUM2SIZET(_offset);
size_t length = NUM2SIZET(_length);
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
io_buffer_validate_range(data, offset, length);
VALUE instance = rb_io_buffer_type_allocate(rb_class_of(self));
struct rb_io_buffer *slice = NULL;
TypedData_Get_Struct(instance, struct rb_io_buffer, &rb_io_buffer_type, slice);
slice->base = (char*)data->base + offset;
slice->size = length;
// The source should be the root buffer:
if (data->source != Qnil)
slice->source = data->source;
else
slice->source = self;
return instance;
}
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.
Raises RuntimeError if the <tt>offset+length<tt> is out of the current buffer’s bounds.
Example
string = 'test' buffer = IO::Buffer.for(string) 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