diff --git a/ext/stringio/stringio.c b/ext/stringio/stringio.c index ba6512366a..d6833976af 100644 --- a/ext/stringio/stringio.c +++ b/ext/stringio/stringio.c @@ -767,12 +767,14 @@ strio_ungetc(VALUE self, VALUE c) check_modifiable(ptr); if (NIL_P(c)) return Qnil; if (FIXNUM_P(c)) { - int cc = FIX2INT(c); + int len, cc = FIX2INT(c); char buf[16]; enc = rb_enc_get(ptr->string); + len = rb_enc_codelen(cc, enc); + if (len <= 0) rb_enc_uint_chr(cc, enc); rb_enc_mbcput(cc, buf, enc); - return strio_unget_bytes(ptr, buf, rb_enc_codelen(cc, enc)); + return strio_unget_bytes(ptr, buf, len); } else { SafeStringValue(c); diff --git a/test/stringio/test_stringio.rb b/test/stringio/test_stringio.rb index d4df7b2617..30370f5ca6 100644 --- a/test/stringio/test_stringio.rb +++ b/test/stringio/test_stringio.rb @@ -453,6 +453,8 @@ class TestStringIO < Test::Unit::TestCase f.ungetc("y".ord) assert_equal("y", f.getc) assert_equal("2", f.getc) + + assert_raise(RangeError) {f.ungetc(0x1ffffff)} ensure f.close unless f.closed? end