From 795464cec3a3ae96e0f929aa6226d03722108ce9 Mon Sep 17 00:00:00 2001 From: Lars Kanis Date: Wed, 4 Jan 2023 17:16:19 +0100 Subject: [PATCH] Fix writing to an IO with no external_encoding A file-IO has no external_encoding by default, so that rb_to_encoding() fails with a TypeError. This regression was introduces in commit 2e260f53e6b84b8f9c1b115b0ded85eebc8155d7. Fixes #2752 Co-authored-by: Mike Dalessio --- ext/nokogiri/nokogiri.c | 3 ++- test/xml/test_node.rb | 8 ++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/ext/nokogiri/nokogiri.c b/ext/nokogiri/nokogiri.c index f2e39ab014..3844c856a0 100644 --- a/ext/nokogiri/nokogiri.c +++ b/ext/nokogiri/nokogiri.c @@ -112,7 +112,8 @@ noko_io_write(void *io, char *c_buffer, int c_buffer_len) { VALUE rb_args[2], rb_n_bytes_written; VALUE rb_io = (VALUE)io; - rb_encoding *io_encoding = rb_to_encoding(rb_funcall(rb_io, id_external_encoding, 0)); + VALUE rb_enc = rb_funcall(rb_io, id_external_encoding, 0); + rb_encoding *io_encoding = RB_NIL_P(rb_enc) ? rb_ascii8bit_encoding() : rb_to_encoding(rb_enc); rb_args[0] = rb_io; rb_args[1] = rb_enc_str_new(c_buffer, (long)c_buffer_len, io_encoding); diff --git a/test/xml/test_node.rb b/test/xml/test_node.rb index 5c76305242..80fb66d37b 100644 --- a/test/xml/test_node.rb +++ b/test/xml/test_node.rb @@ -679,6 +679,14 @@ def test_write_to_with_block end end + def test_write_to_file_without_encoding + Tempfile.create do |io| + xml.write_to(io) + io.rewind + assert_equal(xml.to_xml, io.read) + end + end + def test_serialize_with_block called = false conf = nil