Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Flush shift state for String#encode #11993

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions spec/std/string_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -2615,6 +2615,13 @@ describe "String" do
bytes.to_a.should eq([72, 0, 101, 0, 108, 0, 108, 0, 111, 0])
end

{% unless flag?(:musl) %}
it "flushes the shift state (#11992)" do
"\u{00CA}".encode("BIG5-HKSCS").should eq(Bytes[0x88, 0x66])
"\u{00CA}\u{0304}".encode("BIG5-HKSCS").should eq(Bytes[0x88, 0x62])
end
{% end %}

it "raises if wrong encoding" do
expect_raises ArgumentError, "Invalid encoding: FOO" do
"Hello".encode("FOO")
Expand Down Expand Up @@ -2652,6 +2659,11 @@ describe "String" do
String.new(bytes, "UTF-16LE").should eq("Hello")
end

it "decodes with shift state" do
String.new(Bytes[0x88, 0x66], "BIG5-HKSCS").should eq("\u{00CA}")
String.new(Bytes[0x88, 0x62], "BIG5-HKSCS").should eq("\u{00CA}\u{0304}")
end

it "decodes with skip" do
bytes = Bytes[186, 195, 255, 202, 199]
String.new(bytes, "EUC-JP", invalid: :skip).should eq("挫頁")
Expand Down
8 changes: 8 additions & 0 deletions src/string.cr
Original file line number Diff line number Diff line change
Expand Up @@ -1672,6 +1672,14 @@ class String
end
io.write(outbuf.to_slice[0, outbuf.size - outbytesleft])
end

outbuf_ptr = outbuf.to_unsafe
outbytesleft = LibC::SizeT.new(outbuf.size)
err = iconv.convert(Pointer(UInt8*).null, Pointer(LibC::SizeT).null, pointerof(outbuf_ptr), pointerof(outbytesleft))
if err == Crystal::Iconv::ERROR
iconv.handle_invalid(pointerof(inbuf_ptr), pointerof(inbytesleft))
end
io.write(outbuf.to_slice[0, outbuf.size - outbytesleft])
end
end

Expand Down