Skip to content

Commit

Permalink
Improve behavioural consistency of unallocated (zero length) `IO::Buf…
Browse files Browse the repository at this point in the history
…fer`. (ruby#9532)

This makes the behaviour of IO::Buffer.new(0) and IO::Buffer.new.slice(0, 0) consistent.

Fixes https://bugs.ruby-lang.org/issues/19542 and https://bugs.ruby-lang.org/issues/18805.
  • Loading branch information
ioquatix authored Jan 14, 2024
1 parent 5c823aa commit c5cf4d4
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 8 deletions.
14 changes: 6 additions & 8 deletions io_buffer.c
Original file line number Diff line number Diff line change
Expand Up @@ -854,11 +854,10 @@ io_buffer_get_bytes_for_writing(struct rb_io_buffer *buffer, void **base, size_t
if (buffer->base) {
*base = buffer->base;
*size = buffer->size;

return;
} else {
*base = NULL;
*size = 0;
}

rb_raise(rb_eIOBufferAllocationError, "The buffer is not allocated!");
}

void
Expand All @@ -880,11 +879,10 @@ io_buffer_get_bytes_for_reading(struct rb_io_buffer *buffer, const void **base,
if (buffer->base) {
*base = buffer->base;
*size = buffer->size;

return;
} else {
*base = NULL;
*size = 0;
}

rb_raise(rb_eIOBufferAllocationError, "The buffer is not allocated!");
}

void
Expand Down
35 changes: 35 additions & 0 deletions test/ruby/test_io_buffer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,14 @@ def test_compare_different_size
assert_positive buffer2 <=> buffer1
end

def test_compare_zero_length
buffer1 = IO::Buffer.new(0)
buffer2 = IO::Buffer.new(1)

assert_negative buffer1 <=> buffer2
assert_positive buffer2 <=> buffer1
end

def test_slice
buffer = IO::Buffer.new(128)
slice = buffer.slice(8, 32)
Expand Down Expand Up @@ -270,6 +278,14 @@ def test_get_string
end
end

def test_zero_length_get_string
buffer = IO::Buffer.new.slice(0, 0)
assert_equal "", buffer.get_string

buffer = IO::Buffer.new(0)
assert_equal "", buffer.get_string
end

# We check that values are correctly round tripped.
RANGES = {
:U8 => [0, 2**8-1],
Expand Down Expand Up @@ -316,6 +332,13 @@ def test_get_set_values
end
end

def test_zero_length_get_set_values
buffer = IO::Buffer.new(0)

assert_equal [], buffer.get_values([], 0)
assert_equal 0, buffer.set_values([], 0, [])
end

def test_values
buffer = IO::Buffer.new(128)

Expand All @@ -340,13 +363,25 @@ def test_each
end
end

def test_zero_length_each
buffer = IO::Buffer.new(0)

assert_equal [], buffer.each(:U8).to_a
end

def test_each_byte
string = "The quick brown fox jumped over the lazy dog."
buffer = IO::Buffer.for(string)

assert_equal string.bytes, buffer.each_byte.to_a
end

def test_zero_length_each_byte
buffer = IO::Buffer.new(0)

assert_equal [], buffer.each_byte.to_a
end

def test_clear
buffer = IO::Buffer.new(16)
buffer.set_string("Hello World!")
Expand Down

0 comments on commit c5cf4d4

Please sign in to comment.