diff --git a/ext/stringio/stringio.c b/ext/stringio/stringio.c index 89c1ff7..3190561 100644 --- a/ext/stringio/stringio.c +++ b/ext/stringio/stringio.c @@ -20,6 +20,7 @@ STRINGIO_VERSION = "3.1.6"; #include "ruby.h" #include "ruby/io.h" #include "ruby/encoding.h" +#include "ruby/version.h" #if defined(HAVE_FCNTL_H) || defined(_WIN32) #include #elif defined(HAVE_SYS_FCNTL_H) @@ -1859,7 +1860,12 @@ strio_set_encoding(int argc, VALUE *argv, VALUE self) } } ptr->enc = enc; - if (!NIL_P(ptr->string) && WRITABLE(self)) { + if (!NIL_P(ptr->string) && WRITABLE(self) +#if (RUBY_API_VERSION_MAJOR == 3 && RUBY_API_VERSION_MINOR >= 4) || RUBY_API_VERSION_MAJOR >= 4 + // Do not attempt to modify chilled strings on Ruby 3.4+ + && !FL_TEST_RAW(ptr->string, RUBY_FL_USER2 | RUBY_FL_USER3) +#endif + ) { rb_enc_associate(ptr->string, enc); } diff --git a/test/stringio/test_stringio.rb b/test/stringio/test_stringio.rb index 570b3d7..002b946 100644 --- a/test/stringio/test_stringio.rb +++ b/test/stringio/test_stringio.rb @@ -1057,6 +1057,13 @@ def test_chilled_string_string_set assert_equal("test", io.string) assert_same(chilled_string, io.string) end + + def test_chilled_string_set_enocoding + chilled_string = eval(%{""}) + io = StringIO.new(chilled_string) + assert_warning("") { io.set_encoding(Encoding::BINARY) } + assert_same(chilled_string, io.string) + end end private