Skip to content

Commit 740eddb

Browse files
committed
Fix StringIO#initialize and preserve initial string's encoding when mode is w so the initial string is truncated
* close #3599
1 parent 954bfcf commit 740eddb

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ Compatibility:
3333
* Fix `Enumerable#reduce` to handle non-Symbol method name parameter (#2931, @andrykonchin).
3434
* Fix `RangeError` message to match CRuby for `Integer#chr` called with invalid codepoint argument (#2795, @andrykonchin).
3535
* Joni has been updated from 2.1.44 to 2.2.1 (@andrykonchin).
36+
* Fix `StringIO#initialize` and preserve initial string's encoding when mode is `w` so the initial string is truncated (#3599, @andrykonchin).
3637

3738
Performance:
3839

lib/truffle/stringio.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -691,7 +691,7 @@ def yaml_initialize(type, val)
691691

692692
d = @__data__ # no sync, only called from initialize
693693
raise Errno::EACCES, 'Permission denied' if @writable && d.string.frozen?
694-
d.string.replace('') if truncate
694+
d.string.replace(''.force_encoding(d.string.encoding)) if truncate
695695
end
696696

697697
private def mode_from_integer(mode)
@@ -708,7 +708,7 @@ def yaml_initialize(type, val)
708708
end
709709

710710
@append = true if (mode & IO::APPEND) != 0
711-
d.string.replace('') if (mode & IO::TRUNC) != 0
711+
d.string.replace(''.force_encoding(d.string.encoding)) if (mode & IO::TRUNC) != 0
712712
end
713713

714714
private def getline(arg_error, sep, limit, chomp = false)

spec/ruby/library/stringio/initialize_spec.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,26 @@
130130
-> { @io.send(:initialize, str, "w") }.should raise_error(Errno::EACCES)
131131
-> { @io.send(:initialize, str, "a") }.should raise_error(Errno::EACCES)
132132
end
133+
134+
it "truncates all the content if passed w mode" do
135+
io = StringIO.allocate
136+
source = +"example".encode(Encoding::ISO_8859_1);
137+
138+
io.send(:initialize, source, "w")
139+
140+
io.string.should.empty?
141+
io.string.encoding.should == Encoding::ISO_8859_1
142+
end
143+
144+
it "truncates all the content if passed IO::TRUNC mode" do
145+
io = StringIO.allocate
146+
source = +"example".encode(Encoding::ISO_8859_1);
147+
148+
io.send(:initialize, source, IO::TRUNC)
149+
150+
io.string.should.empty?
151+
io.string.encoding.should == Encoding::ISO_8859_1
152+
end
133153
end
134154

135155
describe "StringIO#initialize when passed [Object]" do

0 commit comments

Comments
 (0)