Actions
Bug #19342
closedString#encode does not always throw exceptions for invalid source encodings
Status:
Closed
Assignee:
-
Target version:
-
ruby -v:
ruby 3.0.5p211 (2022-11-24 revision ba5cf0f7c5) [amd64-freebsd13]
Description
Documentation says that String#encode throws Encoding::InvalidByteSequenceError when the string isn't valid in the source encoding, but it does not always do so:
"\x99".encode('UTF-8', 'UTF-8')
"\x99".force_encoding('UTF-8').encode('UTF-8')
In both cases, it returns a string with invalid encoding.
But those do throw an exception:
"\x99".encode('ISO8859-1', 'UTF-8')
"\x99".force_encoding('UTF-8').encode('ISO8859-1')
I suppose it's debatable if it could be considered a bug or not. It's a weird case to ask to convert to/from the same encoding, but it happened to me with a loop that tried to interpret a binary string with multiple encodings:
input_string = "\x99".force_encoding('US-ASCII')
want_encoding = 'UTF-8'
%w{ISO8859-1 UTF-8}.each do |try_encoding|
s = begin
input_string.encode(want_encoding, try_encoding)
rescue EncodingError
next
end
process_string s
end
I expected to get a Encoding::InvalidByteSequenceError exception during the conversion, but instead I got exceptions later on while trying to work on an invalid string that #encode returned.
Actions
Like0
Like0Like0Like0