From 559ed0b1dd538b816fcaabe53dcecd3d11b3235d Mon Sep 17 00:00:00 2001 From: Peter Dettman Date: Thu, 6 Oct 2022 10:45:18 +0700 Subject: Refactor stackalloc usage --- crypto/src/math/raw/Mod.cs | 27 ++++++++++----------------- 1 file changed, 10 insertions(+), 17 deletions(-) diff --git a/crypto/src/math/raw/Mod.cs b/crypto/src/math/raw/Mod.cs index 8d08e144d..a46a7cdfa 100644 --- a/crypto/src/math/raw/Mod.cs +++ b/crypto/src/math/raw/Mod.cs @@ -125,15 +125,10 @@ namespace Org.BouncyCastle.Math.Raw int bits = (len32 << 5) - Integers.NumberOfLeadingZeros((int)m[len32 - 1]); int len30 = (bits + 29) / 30; - if (len30 <= 50) - return ImplModOddInverse(m, x, z, bits, len30, stackalloc int[len30 * 5]); + Span alloc = len30 <= 50 + ? stackalloc int[len30 * 5] + : new int[len30 * 5]; - return ImplModOddInverse(m, x, z, bits, len30, new int[len30 * 5]); - } - - private static uint ImplModOddInverse(ReadOnlySpan m, ReadOnlySpan x, Span z, int bits, - int len30, Span alloc) - { Span t = stackalloc int[4]; Span D = alloc[..len30]; alloc = alloc[len30..]; Span E = alloc[..len30]; alloc = alloc[len30..]; @@ -278,15 +273,10 @@ namespace Org.BouncyCastle.Math.Raw int bits = (len32 << 5) - Integers.NumberOfLeadingZeros((int)m[len32 - 1]); int len30 = (bits + 29) / 30; - if (len30 <= 50) - return ImplModOddInverseVar(m, x, z, bits, len30, stackalloc int[len30 * 5]); + Span alloc = len30 <= 50 + ? stackalloc int[len30 * 5] + : new int[len30 * 5]; - return ImplModOddInverseVar(m, x, z, bits, len30, new int[len30 * 5]); - } - - private static bool ImplModOddInverseVar(ReadOnlySpan m, ReadOnlySpan x, Span z, int bits, - int len30, Span alloc) - { Span t = stackalloc int[4]; Span D = alloc[..len30]; alloc = alloc[len30..]; Span E = alloc[..len30]; alloc = alloc[len30..]; @@ -407,7 +397,10 @@ namespace Org.BouncyCastle.Math.Raw m |= m >> 8; m |= m >> 16; - Span bytes = stackalloc byte[len << 2]; + Span bytes = len <= 256 + ? stackalloc byte[len << 2] + : new byte[len << 2]; + do { RandomSource.NextBytes(bytes); -- cgit 1.4.1