8000 String.new(capacity:) don't substract termlen · ruby/ruby@83f57ca · GitHub
[go: up one dir, main page]

Skip to content

Commit 83f57ca

Browse files
committed
String.new(capacity:) don't substract termlen
[Bug #20585] This was changed in 36a06ef because `String.new(1024)` would end up allocating `1025` bytes, but the problem with this change is that the caller may be trying to right size a String. So instead, we should just better document the behavior of `capacity:`.
1 parent 321ed86 commit 83f57ca

File tree

3 files changed

+6
-7
lines changed

3 files changed

+6
-7
lines changed

doc/string/new.rdoc

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,10 @@ which may in turn affect performance:
4646
String.new(capacity: 1)
4747
String.new('foo', capacity: 4096)
4848

49+
Note that Ruby strings are null-terminated internally, so the internal
50+
buffer size will be one or more bytes larger than the requested capacity
51+
depending on the encoding.
52+
4953
The +string+, +encoding+, and +capacity+ arguments may all be used together:
5054

5155
String.new('hello', encoding: 'UTF-8', capacity: 25)

string.c

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2055,12 +2055,7 @@ rb_str_s_new(int argc, VALUE *argv, VALUE klass)
20552055
}
20562056
}
20572057

2058-
long fake_len = capa - termlen;
2059-
if (fake_len < 0) {
2060-
fake_len = 0;
2061-
}
2062-
2063-
VALUE str = str_new0(klass, NULL, fake_len, termlen);
2058+
VALUE str = str_new0(klass, NULL, capa, termlen);
20642059
STR_SET_LEN(str, 0);
20652060
TERM_FILL(RSTRING_PTR(str), termlen);
20662061

test/-ext-/string/test_capacity.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ def test_capacity_normal
2323
def test_s_new_capacity
2424
assert_equal("", String.new(capacity: 1000))
2525
assert_equal(String, String.new(capacity: 1000).class)
26-
assert_equal(10_000 - 1, capa(String.new(capacity: 10_000))) # Real capa doesn't account for termlen
26+
assert_equal(10_000, capa(String.new(capacity: 10_000)))
2727

2828
assert_equal("", String.new(capacity: -1000))
2929
assert_equal(capa(String.new(capacity: -10000)), capa(String.new(capacity: -1000)))

0 commit comments

Comments
 (0)
0