From e257c08f2ec27e2d66cdfa7e2415deb492522e22 Mon Sep 17 00:00:00 2001 From: Jean Boussier Date: Thu, 12 Mar 2020 13:55:20 +0100 Subject: [PATCH] [ruby/stringio] StringIO#initialize default to the source string encoding [Bug #16497] https://github.com/ruby/stringio/commit/4958a5ccab --- ext/stringio/stringio.c | 10 ++++++---- spec/ruby/library/stringio/initialize_spec.rb | 3 +++ test/stringio/test_stringio.rb | 12 ++++++++++++ 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/ext/stringio/stringio.c b/ext/stringio/stringio.c index c8057eefb5..b31e801b2a 100644 --- a/ext/stringio/stringio.c +++ b/ext/stringio/stringio.c @@ -363,7 +363,12 @@ strio_init(int argc, VALUE *argv, struct StringIO *ptr, VALUE self) rb_str_resize(string, 0); } ptr->string = string; - ptr->enc = convconfig.enc; + if (argc == 1) { + ptr->enc = rb_enc_get(string); + } + else { + ptr->enc = convconfig.enc; + } ptr->pos = 0; ptr->lineno = 0; if (ptr->flags & FMODE_SETENC_BY_BOM) set_encoding_by_bom(ptr); @@ -1759,9 +1764,6 @@ strio_set_encoding_by_bom(VALUE self) { struct StringIO *ptr = StringIO(self); - if (ptr->enc) { - rb_raise(rb_eArgError, "encoding conversion is set"); - } if (!set_encoding_by_bom(ptr)) return Qnil; return rb_enc_from_encoding(ptr->enc); } diff --git a/spec/ruby/library/stringio/initialize_spec.rb b/spec/ruby/library/stringio/initialize_spec.rb index cc4f4c9254..8aae47dacb 100644 --- a/spec/ruby/library/stringio/initialize_spec.rb +++ b/spec/ruby/library/stringio/initialize_spec.rb @@ -187,11 +187,14 @@ end describe "StringIO#initialize sets the encoding to" do before :each do @external = Encoding.default_external + @internal = Encoding.default_internal Encoding.default_external = Encoding::ISO_8859_2 + Encoding.default_internal = Encoding::ISO_8859_2 end after :each do Encoding.default_external = @external + Encoding.default_internal = @internal end it "Encoding.default_external when passed no arguments" do diff --git a/test/stringio/test_stringio.rb b/test/stringio/test_stringio.rb index 663a33be27..a99ccf4302 100644 --- a/test/stringio/test_stringio.rb +++ b/test/stringio/test_stringio.rb @@ -797,6 +797,18 @@ class TestStringIO < Test::Unit::TestCase end end + def test_binary_encoding_read_and_default_internal + verbose, $VERBOSE = $VERBOSE, nil + default_internal = Encoding.default_internal + Encoding.default_internal = Encoding::UTF_8 + $VERBOSE = verbose + assert_equal Encoding::BINARY, StringIO.new("Hello".b).read.encoding + ensure + $VERBOSE = nil + Encoding.default_internal = default_internal + $VERBOSE = verbose + end + def assert_string(content, encoding, str, mesg = nil) assert_equal([content, encoding], [str, str.encoding], mesg) end