Skip to content

Commit 2921abd

Browse files
committed
reduced extra allocations on array reverse operations
1 parent c7a683e commit 2921abd

File tree

3 files changed

+16
-6
lines changed

3 files changed

+16
-6
lines changed

Asn1Parser/Universal/Asn1Enumerated.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
using System;
22
using System.IO;
3-
using System.Linq;
43
using System.Numerics;
54
using SysadminsLV.Asn1Parser.Utils.CLRExtensions;
65

@@ -55,7 +54,9 @@ void m_decode(Asn1Reader asn) {
5554
var value = new BigInteger(payload, isUnsigned: true, isBigEndian: true);
5655
#else
5756
// Fallback for .NET Framework: reverse to little-endian
58-
var value = new BigInteger(payload.ToArray().Cast<Byte>().Reverse().ToArray());
57+
Byte[] bytes = payload.ToArray();
58+
Array.Reverse(bytes);
59+
var value = new BigInteger(bytes);
5960
#endif
6061
if (value > UInt64.MaxValue) {
6162
throw new InvalidDataException(String.Format(InvalidType, TYPE.ToString()));

Asn1Parser/Universal/Asn1Integer.cs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
using System;
2-
using System.Linq;
32
using System.Numerics;
43
using SysadminsLV.Asn1Parser.Utils.CLRExtensions;
54

@@ -48,6 +47,15 @@ void m_encode(BigInteger inputInteger) {
4847
Initialize(Asn1Utils.EncodeAsReader(inputInteger.GetAsnBytes(), TYPE));
4948
}
5049
void m_decode(Asn1Reader asn) {
51-
Value = new BigInteger(asn.GetPayload().Cast<Byte>().Reverse().ToArray());
50+
ReadOnlySpan<Byte> payload = asn.GetPayloadAsMemory().Span;
51+
#if NET8_0_OR_GREATER
52+
// BigInteger constructor with isBigEndian parameter (available in .NET 5+)
53+
Value = new BigInteger(payload, isUnsigned: false, isBigEndian: true);
54+
#else
55+
// Fallback for .NET Framework: reverse to little-endian
56+
Byte[] bytes = payload.ToArray();
57+
Array.Reverse(bytes);
58+
Value = new BigInteger(bytes);
59+
#endif
5260
}
5361
}

Asn1Parser/Utils/CLRExtensions/BigIntegerExtensions.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
using System;
2-
using System.Linq;
32
using System.Numerics;
43

54
namespace SysadminsLV.Asn1Parser.Utils.CLRExtensions;
@@ -14,6 +13,8 @@ internal static class BigIntegerExtensions {
1413
/// <param name="bigInteger">An <see cref="BigInteger"/> class instance.</param>
1514
/// <returns>Byte array in a big-endian order.</returns>
1615
public static ReadOnlySpan<Byte> GetAsnBytes(this BigInteger bigInteger) {
17-
return bigInteger.ToByteArray().Cast<Byte>().Reverse().ToArray();
16+
Byte[] bytes = bigInteger.ToByteArray();
17+
Array.Reverse(bytes); // In-place reverse, single allocation
18+
return bytes;
1819
}
1920
}

0 commit comments

Comments
 (0)