Skip to content

Commit e97301b

Browse files
committed
Add string optimizations
1 parent d237ca6 commit e97301b

File tree

2 files changed

+108
-22
lines changed

2 files changed

+108
-22
lines changed

QRCoder/QRCodeGenerator.cs

Lines changed: 64 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -745,14 +745,21 @@ bool IsUtf8()
745745
}
746746
}
747747

748+
private static readonly Encoding _iso88591ExceptionFallback = Encoding.GetEncoding("ISO-8859-1", new EncoderExceptionFallback(), new DecoderExceptionFallback());
748749
/// <summary>
749750
/// Checks if the given string can be accurately represented and retrieved in ISO-8859-1 encoding.
750751
/// </summary>
751752
private static bool IsValidISO(string input)
752753
{
753-
var bytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(input);
754-
var result = Encoding.GetEncoding("ISO-8859-1").GetString(bytes);
755-
return String.Equals(input, result);
754+
try
755+
{
756+
_ = _iso88591ExceptionFallback.GetByteCount(input);
757+
return true;
758+
}
759+
catch (EncoderFallbackException)
760+
{
761+
return false;
762+
}
756763
}
757764

758765
/// <summary>
@@ -866,18 +873,13 @@ private static BitArray PlainTextToBinaryAlphanumeric(string plainText)
866873
return codeText;
867874
}
868875

869-
/// <summary>
870-
/// Returns a string that contains the original string, with characters that cannot be encoded by a
871-
/// specified encoding (default of ISO-8859-2) with a replacement character.
872-
/// </summary>
873-
private static string ConvertToIso8859(string value, string Iso = "ISO-8859-2")
874-
{
875-
Encoding iso = Encoding.GetEncoding(Iso);
876-
Encoding utf8 = Encoding.UTF8;
877-
byte[] utfBytes = utf8.GetBytes(value);
878-
byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes);
879-
return iso.GetString(isoBytes);
880-
}
876+
private static readonly Encoding _iso8859_1 =
877+
#if NET5_0_OR_GREATER
878+
Encoding.Latin1;
879+
#else
880+
Encoding.GetEncoding("ISO-8859-1");
881+
#endif
882+
private static Encoding _iso8859_2;
881883

882884
/// <summary>
883885
/// Converts plain text into a binary format using byte mode encoding, which supports various character encodings through ECI (Extended Channel Interpretations).
@@ -894,35 +896,69 @@ private static string ConvertToIso8859(string value, string Iso = "ISO-8859-2")
894896
/// </remarks>
895897
private static BitArray PlainTextToBinaryByte(string plainText, EciMode eciMode, bool utf8BOM, bool forceUtf8)
896898
{
897-
byte[] codeBytes;
899+
Encoding targetEncoding;
898900

899901
// Check if the text is valid ISO-8859-1 and UTF-8 is not forced, then encode using ISO-8859-1.
900902
if (IsValidISO(plainText) && !forceUtf8)
901-
codeBytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(plainText);
903+
{
904+
targetEncoding = _iso8859_1;
905+
utf8BOM = false;
906+
}
902907
else
903908
{
904909
// Determine the encoding based on the specified ECI mode.
905910
switch (eciMode)
906911
{
907912
case EciMode.Iso8859_1:
908913
// Convert text to ISO-8859-1 and encode.
909-
codeBytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(ConvertToIso8859(plainText, "ISO-8859-1"));
914+
targetEncoding = _iso8859_1;
915+
utf8BOM = false;
910916
break;
911917
case EciMode.Iso8859_2:
918+
// Note: ISO-8859-2 is not natively supported on .NET Core
919+
//
920+
// Users must install the System.Text.Encoding.CodePages package and call Encoding.RegisterProvider(CodePagesEncodingProvider.Instance)
921+
// before using this encoding mode.
922+
if (_iso8859_2 == null)
923+
_iso8859_2 = Encoding.GetEncoding("ISO-8859-2");
912924
// Convert text to ISO-8859-2 and encode.
913-
codeBytes = Encoding.GetEncoding("ISO-8859-2").GetBytes(ConvertToIso8859(plainText, "ISO-8859-2"));
925+
targetEncoding = _iso8859_2;
926+
utf8BOM = false;
914927
break;
915928
case EciMode.Default:
916929
case EciMode.Utf8:
917930
default:
918931
// Handle UTF-8 encoding, optionally adding a BOM if specified.
919-
codeBytes = utf8BOM ? Encoding.UTF8.GetPreamble().Concat(Encoding.UTF8.GetBytes(plainText)).ToArray() : Encoding.UTF8.GetBytes(plainText);
932+
targetEncoding = Encoding.UTF8;
920933
break;
921934
}
922935
}
923936

937+
#if NET5_0_OR_GREATER
938+
// In .NET 5.0 and later, we can use stackalloc for small arrays to prevent heap allocations
939+
int count = targetEncoding.GetByteCount(plainText);
940+
Span<byte> codeBytes = count < 2000 ? stackalloc byte[count] : new byte[count];
941+
targetEncoding.GetBytes(plainText, codeBytes);
942+
#else
943+
byte[] codeBytes;
944+
codeBytes = targetEncoding.GetBytes(plainText);
945+
#endif
946+
924947
// Convert the array of bytes into a BitArray.
925-
return ToBitArray(codeBytes);
948+
if (utf8BOM)
949+
{
950+
// convert to bit array, leaving 24 bits for the UTF-8 preamble
951+
var bitArray = ToBitArray(codeBytes, 24);
952+
// write UTF8 preamble (EF BB BF) to the BitArray
953+
DecToBin(0xEF, 8, bitArray, 0);
954+
DecToBin(0xBB, 8, bitArray, 8);
955+
DecToBin(0xBF, 8, bitArray, 16);
956+
return bitArray;
957+
}
958+
else
959+
{
960+
return ToBitArray(codeBytes);
961+
}
926962
}
927963

928964
/// <summary>
@@ -932,7 +968,13 @@ private static BitArray PlainTextToBinaryByte(string plainText, EciMode eciMode,
932968
/// <param name="byteArray">The byte array to convert into a BitArray.</param>
933969
/// <param name="prefixZeros">The number of leading zeros to prepend to the resulting BitArray.</param>
934970
/// <returns>A BitArray representing the bits of the input byteArray, with optional leading zeros.</returns>
935-
private static BitArray ToBitArray(byte[] byteArray, int prefixZeros = 0)
971+
private static BitArray ToBitArray(
972+
#if NET5_0_OR_GREATER
973+
ReadOnlySpan<byte> byteArray,
974+
#else
975+
byte[] byteArray,
976+
#endif
977+
int prefixZeros = 0)
936978
{
937979
// Calculate the total number of bits in the resulting BitArray including the prefix zeros.
938980
var bitArray = new BitArray((int)((uint)byteArray.Length * 8) + prefixZeros);

QRCoderTests/QRGeneratorTests.cs

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,26 @@ public void can_encode_byte()
160160
result.ShouldBe("0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111001011011111110000000010000010011100100000100000000101110101101101011101000000001011101001010010111010000000010111010001010101110100000000100000100000101000001000000001111111010101011111110000000000000000110110000000000000000111011111111011000100000000001001110001100010000010000000010011110001010001001000000000110011010000001000110000000001110001111001010110110000000000000000111101010011100000000111111101111011100110000000001000001010011101110010000000010111010110101110010100000000101110100110001000110000000001011101011001000100010000000010000010100000100011000000000111111101110101010111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
161161
}
162162

163+
[Fact]
164+
[Category("QRGenerator/TextEncoding")]
165+
public void can_encode_utf8()
166+
{
167+
var gen = new QRCodeGenerator();
168+
var qrData = gen.CreateQrCode("https://en.wikipedia.org/wiki/🍕", QRCodeGenerator.ECCLevel.L, true, false, QRCodeGenerator.EciMode.Utf8);
169+
var result = string.Join("", qrData.ModuleMatrix.Select(x => x.ToBitString()).ToArray());
170+
result.ShouldBe("0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011111110101011010011101111111000000001000001001111100001110100000100000000101110101110000011000010111010000000010111010111010111100101011101000000001011101010011010111010101110100000000100000100011010001110010000010000000011111110101010101010101111111000000000000000000101000011100000000000000000111100101011110101011100111010000000001011000101011111010011101010000000001010011101111101001111011101000000000111011011110000010001100000100000000000000010011010101100000000000000000001100110101011011111001101110000000000000011100001010101010110101000000000000111001011100110111111110011000000001110101011001011001000100011000000000000101010100001010111111000000000000010111010101001111100000001110000000000010110100010111111100100010100000000011101111010011101111111101010000000000000000110000001000100010010000000001111111001100011001010101101000000000100000100111111111011000111000000000010111010010100011010111110111000000001011101010110100011100101011000000000101110101100101111100101111010000000010000010111011001111000001101000000001111111011110000100000110101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
171+
}
172+
173+
[Fact]
174+
[Category("QRGenerator/TextEncoding")]
175+
public void can_encode_utf8_bom()
176+
{
177+
var gen = new QRCodeGenerator();
178+
var qrData = gen.CreateQrCode("https://en.wikipedia.org/wiki/🍕", QRCodeGenerator.ECCLevel.L, true, true, QRCodeGenerator.EciMode.Utf8);
179+
var result = string.Join("", qrData.ModuleMatrix.Select(x => x.ToBitString()).ToArray());
180+
result.ShouldBe("0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011111110010001101010101111111000000001000001011011000110000100000100000000101110100111010101111010111010000000010111010110100100010101011101000000001011101000101111000010101110100000000100000101010000111000010000010000000011111110101010101010101111111000000000000000000001010101110000000000000000111110111110101010100101010100000000000100000110000101000001100101000000000001001001011000011010000111100000000100010001111000001111110111010000000010110111010100011100100101111000000000001010001101101001000010100100000000100001101110011001010000001010000000001011001100011001111111010111000000000010001010101011110010100000100000000100100010000000000010110010000000000010110110010110000101010101100000000001001100100010010100111101101100000000101010110011000111101111100100000000000000000111011110011100011010000000001111111011100110010010101110000000000100000100100110010101000110110000000010111010110010111101111110011000000001011101010100000100010110100000000000101110101001100111110110111100000000010000010111100101111100100001000000001111111011110001110100111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
181+
}
182+
163183
[Fact]
164184
[Category("QRGenerator/TextEncoding")]
165185
public void can_generate_from_bytes()
@@ -170,6 +190,30 @@ public void can_generate_from_bytes()
170190
var result = string.Join("", qrData.ModuleMatrix.Select(x => x.ToBitString()).ToArray());
171191
result.ShouldBe("0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111011001011111110000000010000010010010100000100000000101110101010101011101000000001011101010010010111010000000010111010111000101110100000000100000100000001000001000000001111111010101011111110000000000000000011000000000000000000111100101010010011101000000001011100001001001001110000000010101011111011111110100000000000101000000110000000000000001011001001010100110000000000000000000110001000101000000000111111100110011011110000000001000001001111110111010000000010111010011100100101100000000101110101110010010010000000001011101011010100011000000000010000010110110101000100000000111111101011100010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
172192
}
193+
194+
[Fact]
195+
[Category("QRGenerator/TextEncoding")]
196+
public void isValidIso_works()
197+
{
198+
Encoding _iso88591ExceptionFallback = Encoding.GetEncoding("ISO-8859-1", new EncoderExceptionFallback(), new DecoderExceptionFallback());
199+
200+
IsValidISO("abc").ShouldBeTrue();
201+
IsValidISO("äöü").ShouldBeTrue();
202+
IsValidISO("🍕").ShouldBeFalse();
203+
204+
bool IsValidISO(string input)
205+
{
206+
try
207+
{
208+
_ = _iso88591ExceptionFallback.GetByteCount(input);
209+
return true;
210+
}
211+
catch (EncoderFallbackException)
212+
{
213+
return false;
214+
}
215+
}
216+
}
173217
}
174218

175219
public static class ExtensionMethods

0 commit comments

Comments
 (0)