Skip to content
Merged
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
17 changes: 8 additions & 9 deletions QRCoder/QRCodeGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -995,22 +995,21 @@ private static int GetDataLength(EncodingMode encoding, string plainText, BitArr
bool IsUtf8() => (encoding == EncodingMode.Byte && (forceUtf8 || !IsValidISO(plainText)));
}

private static readonly Encoding _iso88591ExceptionFallback = Encoding.GetEncoding(28591, new EncoderExceptionFallback(), new DecoderExceptionFallback()); // ISO-8859-1
/// <summary>
/// Checks if the given string can be accurately represented and retrieved in ISO-8859-1 encoding.
/// </summary>
private static bool IsValidISO(string input)
{
// No heap allocations if the string is ISO-8859-1
try
// ISO-8859-1 contains the same characters as UTF-16 for the range 0x00-0xFF.
// 0x00-0x7F: ASCII (0-127)
// 0x80-0x9F: C1 control characters (128-159)
// 0xA0-0xFF: Extended Latin (160-255)
foreach (char c in input)
{
_ = _iso88591ExceptionFallback.GetByteCount(input);
return true;
}
catch (EncoderFallbackException) // The exception is a heap allocation and not ideal
{
return false;
if (c > 0xFF)
return false;
}
return true;
}

/// <summary>
Expand Down