End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
IO::Buffer#copy
copy(source, [offset, [length, [source_offset]]]) → size
io_buffer.c
View on GitHub ↗
static VALUE
io_buffer_copy(int argc, VALUE *argv, VALUE self)
{
rb_check_arity(argc, 1, 4);
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
VALUE source = argv[0];
const void *source_base;
size_t source_size;
rb_io_buffer_get_bytes_for_reading(source, &source_base, &source_size);
return io_buffer_copy_from(data, source_base, source_size, argc-1, argv+1);
}
Efficiently copy data from a source IO::Buffer into the buffer, at offset using memcpy. For copying String instances, see set_string.
Example
buffer = IO::Buffer.new(32) # => # #<IO::Buffer 0x0000555f5ca22520+32 INTERNAL> # 0x00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ # 0x00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ * buffer.copy(IO::Buffer.for("test"), 8) # => 4 -- size of data copied buffer # => # #<IO::Buffer 0x0000555f5cf8fe40+32 INTERNAL> # 0x00000000 00 00 00 00 00 00 00 00 74 65 73 74 00 00 00 00 ........test.... # 0x00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ *
copy can be used to put data into strings associated with buffer:
Example
string= "data: " # => "data: " buffer = IO::Buffer.for(string) buffer.copy(IO::Buffer.for("test"), 5) # => 4 string # => "data:test"
Attempt to copy into a read-only buffer will fail:
Example
File.write('test.txt', 'test') buffer = IO::Buffer.map(File.open('test.txt'), nil, 0, IO::Buffer::READONLY) buffer.copy(IO::Buffer.for("test"), 8) # in `copy': Buffer is not writable! (IO::Buffer::AccessError)
See ::map for details of creation of mutable file mappings, this will work:
Example
buffer = IO::Buffer.map(File.open('test.txt', 'r+')) buffer.copy(IO::Buffer.for("boom"), 0) # => 4 File.read('test.txt') # => "boom"
Attempt to copy the data which will need place outside of buffer’s bounds will fail:
Example
buffer = IO::Buffer.new(2) buffer.copy(IO::Buffer.for('test'), 0) # in `copy': Specified offset+length exceeds source size! (ArgumentError)