Skip to content

Commit

Permalink
[Bug #20292] Truncate embedded string to new capacity
Browse files Browse the repository at this point in the history
  • Loading branch information
nobu committed Feb 22, 2024
1 parent 5f7f229 commit e041461
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
12 changes: 4 additions & 8 deletions string.c
Expand Up @@ -1877,17 +1877,13 @@ rb_str_init(int argc, VALUE *argv, VALUE str)
if (orig == str) n = 0;
}
str_modifiable(str);
if (STR_EMBED_P(str)) { /* make noembed always */
char *new_ptr = ALLOC_N(char, (size_t)capa + termlen);
RUBY_ASSERT(RSTRING_LEN(str) + 1 <= str_embed_capa(str));
memcpy(new_ptr, RSTRING(str)->as.embed.ary, RSTRING_LEN(str) + 1);
RSTRING(str)->as.heap.ptr = new_ptr;
}
else if (FL_TEST(str, STR_SHARED|STR_NOFREE)) {
if (STR_EMBED_P(str) || FL_TEST(str, STR_SHARED|STR_NOFREE)) {
/* make noembed always */
const size_t size = (size_t)capa + termlen;
const char *const old_ptr = RSTRING_PTR(str);
const size_t osize = RSTRING_LEN(str) + TERM_LEN(str);
char *new_ptr = ALLOC_N(char, (size_t)capa + termlen);
char *new_ptr = ALLOC_N(char, size);
if (STR_EMBED_P(str)) RUBY_ASSERT(osize <= str_embed_capa(str));
memcpy(new_ptr, old_ptr, osize < size ? osize : size);
FL_UNSET_RAW(str, STR_SHARED|STR_NOFREE);
RSTRING(str)->as.heap.ptr = new_ptr;
Expand Down
7 changes: 7 additions & 0 deletions test/ruby/test_string.rb
Expand Up @@ -80,6 +80,13 @@ def test_initialize
assert_equal("mystring", str.__send__(:initialize, "mystring", capacity: 1000))
str = S("mystring")
assert_equal("mystring", str.__send__(:initialize, str, capacity: 1000))

if @cls == String
100.times {
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".
__send__(:initialize, capacity: -1)
}
end
end

def test_initialize_shared
Expand Down

0 comments on commit e041461

Please sign in to comment.