Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add IO::Buffer.string for efficient string creation. #7364

Merged
merged 1 commit into from Feb 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 30 additions & 0 deletions io_buffer.c
Expand Up @@ -407,6 +407,35 @@ rb_io_buffer_type_for(VALUE klass, VALUE string)
}
}

/*
* call-seq:
* IO::Buffer.string(length) {|io_buffer| ... read/write io_buffer ...} -> string
*
* Creates a new string of the given length and yields a IO::Buffer instance
* to the block which uses the string as a source. The block is expected to
* write to the buffer and the string will be returned.
*
* IO::Buffer.string(4) do |buffer|
* buffer.set_string("Ruby")
* end
* # => "Ruby"
*/
VALUE
rb_io_buffer_type_string(VALUE klass, VALUE length)
{
VALUE string = rb_str_new(NULL, NUM2SIZET(length));

struct io_buffer_for_yield_instance_arguments arguments = {
.klass = klass,
.string = string,
.instance = Qnil,
};

rb_ensure(io_buffer_for_yield_instance, (VALUE)&arguments, io_buffer_for_yield_instance_ensure, (VALUE)&arguments);

return string;
}

VALUE
rb_io_buffer_new(void *base, size_t size, enum rb_io_buffer_flags flags)
{
Expand Down Expand Up @@ -3246,6 +3275,7 @@ Init_IO_Buffer(void)

rb_define_alloc_func(rb_cIOBuffer, rb_io_buffer_type_allocate);
rb_define_singleton_method(rb_cIOBuffer, "for", rb_io_buffer_type_for, 1);
rb_define_singleton_method(rb_cIOBuffer, "string", rb_io_buffer_type_string, 1);

#ifdef _WIN32
SYSTEM_INFO info;
Expand Down
14 changes: 14 additions & 0 deletions test/ruby/test_io_buffer.rb
Expand Up @@ -124,6 +124,20 @@ def test_non_string
end
end

def test_string
result = IO::Buffer.string(12) do |buffer|
buffer.set_string("Hello World!")
end

assert_equal "Hello World!", result
end

def test_string_negative
assert_raise ArgumentError do
IO::Buffer.string(-1)
end
end

def test_resize_mapped
buffer = IO::Buffer.new

Expand Down