|
1 | 1 | using System;
|
| 2 | +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1 |
| 3 | +using System.Buffers; |
| 4 | +#endif |
2 | 5 | using System.Collections;
|
3 | 6 | using System.Collections.Generic;
|
4 | 7 | using System.Globalization;
|
@@ -937,29 +940,41 @@ private static BitArray PlainTextToBinaryByte(string plainText, EciMode eciMode,
|
937 | 940 |
|
938 | 941 | #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1
|
939 | 942 | // 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 | + |
941 | 945 | 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); |
943 | 951 | targetEncoding.GetBytes(plainText, codeBytes);
|
944 | 952 | #else
|
945 | 953 | byte[] codeBytes = targetEncoding.GetBytes(plainText);
|
946 | 954 | #endif
|
947 | 955 |
|
948 | 956 | // Convert the array of bytes into a BitArray.
|
| 957 | + BitArray bitArray; |
949 | 958 | if (utf8BOM)
|
950 | 959 | {
|
951 | 960 | // convert to bit array, leaving 24 bits for the UTF-8 preamble
|
952 |
| - var bitArray = ToBitArray(codeBytes, 24); |
| 961 | + bitArray = ToBitArray(codeBytes, 24); |
953 | 962 | // write UTF8 preamble (EF BB BF) to the BitArray
|
954 | 963 | DecToBin(0xEF, 8, bitArray, 0);
|
955 | 964 | DecToBin(0xBB, 8, bitArray, 8);
|
956 | 965 | DecToBin(0xBF, 8, bitArray, 16);
|
957 |
| - return bitArray; |
958 | 966 | }
|
959 | 967 | else
|
960 | 968 | {
|
961 |
| - return ToBitArray(codeBytes); |
| 969 | + bitArray = ToBitArray(codeBytes); |
962 | 970 | }
|
| 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; |
963 | 978 | }
|
964 | 979 |
|
965 | 980 | /// <summary>
|
|
0 commit comments