Skip to content

Commit

Permalink
[fix] potential string sharing as each_line returns shared buffer
Browse files Browse the repository at this point in the history
... later modification to StringIO#string might affect the line

resolves GH-5203
  • Loading branch information
kares committed Jun 12, 2018
1 parent 6b7d821 commit e485ef3
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
3 changes: 2 additions & 1 deletion core/src/main/java/org/jruby/ext/stringio/StringIO.java
Expand Up @@ -508,6 +508,7 @@ private RubyString strioSubstr(Ruby runtime, int pos, int len) {
if (len < 0) len = 0;

if (len == 0) return RubyString.newEmptyString(runtime);
string.setByteListShared(); // we only share the byte[] buffer but its easier this way
return RubyString.newStringShared(runtime, stringBytes, stringByteList.getBegin() + pos, len, enc);
}
}
Expand Down Expand Up @@ -657,7 +658,7 @@ private IRubyObject getline(ThreadContext context, final IRubyObject rs, int lim
if (limit > 0 && s + limit < e) {
e = ptr.enc.rightAdjustCharHead(stringBytes, s, s + limit, e);
}
if (rs.isNil()) {
if (rs == context.nil) {
if (chomp) {
w = chompNewlineWidth(stringBytes, s, e);
}
Expand Down
11 changes: 11 additions & 0 deletions test/jruby/test_string.rb
Expand Up @@ -96,6 +96,17 @@ def test_count
assert_equal(2, "abc\u{3042 3044 3046}".count("^\u3042", "^\u3044", "^\u3046", "^c"))
end

# GH-5203
def test_string_buffer_sharing_in_stringio; require 'stringio'
zero = 0
strio = StringIO.new "123\nabcdefghijklmnopqrstuvxyz\n#{zero}\n"
ary = []; strio.each_line { |line| ary << line }
strio.rewind
strio.write('456')
assert_equal ["123\n", "abcdefghijklmnopqrstuvxyz\n", "0\n"], ary
assert_equal "456\nabcdefghijklmnopqrstuvxyz\n0\n", strio.string
end

private

def do_sub buf, e1, e2, e3
Expand Down

0 comments on commit e485ef3

Please sign in to comment.