Skip to content

Commit 5037a5a

Browse files
committed
Utilize suggestions
1 parent cb5a497 commit 5037a5a

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

QRCoder/QRCodeGenerator.cs

+20-5
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
using System;
2+
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1
3+
using System.Buffers;
4+
#endif
25
using System.Collections;
36
using System.Collections.Generic;
47
using System.Globalization;
@@ -937,29 +940,41 @@ private static BitArray PlainTextToBinaryByte(string plainText, EciMode eciMode,
937940

938941
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1
939942
// We can use stackalloc for small arrays to prevent heap allocations
940-
// Note that all QR codes should fit within 3000 bytes, so this code should never trigger a heap allocation unless an exception will be thrown anyway.
943+
const int MAX_STACK_SIZE_IN_BYTES = 512;
944+
941945
int count = targetEncoding.GetByteCount(plainText);
942-
Span<byte> codeBytes = count < 3000 ? stackalloc byte[count] : new byte[count];
946+
byte[] bufferFromPool = null;
947+
Span<byte> codeBytes = (count <= MAX_STACK_SIZE_IN_BYTES)
948+
? (stackalloc byte[MAX_STACK_SIZE_IN_BYTES])
949+
: (bufferFromPool = ArrayPool<byte>.Shared.Rent(count));
950+
codeBytes = codeBytes.Slice(0, count);
943951
targetEncoding.GetBytes(plainText, codeBytes);
944952
#else
945953
byte[] codeBytes = targetEncoding.GetBytes(plainText);
946954
#endif
947955

948956
// Convert the array of bytes into a BitArray.
957+
BitArray bitArray;
949958
if (utf8BOM)
950959
{
951960
// convert to bit array, leaving 24 bits for the UTF-8 preamble
952-
var bitArray = ToBitArray(codeBytes, 24);
961+
bitArray = ToBitArray(codeBytes, 24);
953962
// write UTF8 preamble (EF BB BF) to the BitArray
954963
DecToBin(0xEF, 8, bitArray, 0);
955964
DecToBin(0xBB, 8, bitArray, 8);
956965
DecToBin(0xBF, 8, bitArray, 16);
957-
return bitArray;
958966
}
959967
else
960968
{
961-
return ToBitArray(codeBytes);
969+
bitArray = ToBitArray(codeBytes);
962970
}
971+
972+
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1
973+
if (bufferFromPool != null)
974+
ArrayPool<byte>.Shared.Return(bufferFromPool);
975+
#endif
976+
977+
return bitArray;
963978
}
964979

965980
/// <summary>

0 commit comments

Comments
 (0)