Skip to content

Commit

Permalink
Replace a few stackallocs with collection expressions (#105143)
Browse files Browse the repository at this point in the history
* Replace a few stackallocs with collection expressions

* Update src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/OptimizedInboxTextEncoder.Ascii.cs
  • Loading branch information
stephentoub committed Jul 20, 2024
1 parent f26dbf0 commit ef56648
Show file tree
Hide file tree
Showing 12 changed files with 29 additions and 30 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,15 @@ internal static string DebuggerToString(string name, ILogger logger)

internal static LogLevel? CalculateEnabledLogLevel(ILogger logger)
{
ReadOnlySpan<LogLevel> logLevels = stackalloc LogLevel[]
{
ReadOnlySpan<LogLevel> logLevels =
[
LogLevel.Critical,
LogLevel.Error,
LogLevel.Warning,
LogLevel.Information,
LogLevel.Debug,
LogLevel.Trace,
};
];

LogLevel? minimumLevel = null;

Expand Down
5 changes: 3 additions & 2 deletions src/libraries/Common/src/System/Net/Security/MD4.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,10 @@ internal static void HashData(ReadOnlySpan<byte> source, Span<byte> destination)

Span<byte> buffer = stackalloc byte[64];
buffer.Clear();

// Initialize the context
Span<uint> state = stackalloc uint[4] { 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476 };
Span<uint> count = stackalloc uint[2] { 0, 0 };
Span<uint> state = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476];
Span<uint> count = [0, 0];

HashCore(source, state, count, buffer);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ internal unsafe SP800108HmacCounterKdfImplementationCng(ReadOnlySpan<byte> key,
else
{
// CNG requires a non-null pointer even when the length is zero.
symmetricKeyMaterial = stackalloc byte[] { 0 };
symmetricKeyMaterial = [0];
symmetricKeyMaterialLength = 0;
}

Expand Down Expand Up @@ -82,7 +82,7 @@ internal unsafe SP800108HmacCounterKdfImplementationCng(byte[] key, HashAlgorith
else
{
// CNG requires a non-null pointer even when the length is zero.
symmetricKeyMaterial = stackalloc byte[] { 0 };
symmetricKeyMaterial = [0];
symmetricKeyMaterialLength = 0;
}

Expand Down
6 changes: 3 additions & 3 deletions src/libraries/Microsoft.Extensions.Logging/src/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -238,15 +238,15 @@ private sealed class LoggerProviderDebugView(string providerName, MessageLogger?
return null;
}

ReadOnlySpan<LogLevel> logLevels = stackalloc LogLevel[]
{
ReadOnlySpan<LogLevel> logLevels =
[
LogLevel.Critical,
LogLevel.Error,
LogLevel.Warning,
LogLevel.Information,
LogLevel.Debug,
LogLevel.Trace,
};
];

LogLevel? minimumLevel = null;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,13 +85,13 @@ private static unsafe void CallStartupHook(char* pStartupHookPart)

private static void ParseStartupHook(ref StartupHookNameOrPath startupHook, string startupHookPart)
{
ReadOnlySpan<char> disallowedSimpleAssemblyNameChars = stackalloc char[4]
{
ReadOnlySpan<char> disallowedSimpleAssemblyNameChars =
[
Path.DirectorySeparatorChar,
Path.AltDirectorySeparatorChar,
' ',
','
};
];

if (string.IsNullOrEmpty(startupHookPart))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -396,13 +396,13 @@ public decimal ReadDecimal()
{
byte[] buffer = GetBuffer(ValueHandleLength.Decimal, out int offset);
ReadOnlySpan<byte> bytes = buffer.AsSpan(offset, sizeof(decimal));
ReadOnlySpan<int> span = stackalloc int[4]
{
ReadOnlySpan<int> span =
[
BinaryPrimitives.ReadInt32LittleEndian(bytes.Slice(8, 4)),
BinaryPrimitives.ReadInt32LittleEndian(bytes.Slice(12, 4)),
BinaryPrimitives.ReadInt32LittleEndian(bytes.Slice(4, 4)),
BinaryPrimitives.ReadInt32LittleEndian(bytes.Slice(0, 4))
};
];

Advance(ValueHandleLength.Decimal);
return new decimal(span);
Expand Down Expand Up @@ -975,13 +975,13 @@ public decimal GetDecimal(int offset)
else
{
ReadOnlySpan<byte> bytes = _buffer.AsSpan(offset, sizeof(decimal));
ReadOnlySpan<int> span = stackalloc int[4]
{
ReadOnlySpan<int> span =
[
BinaryPrimitives.ReadInt32LittleEndian(bytes.Slice(8, 4)),
BinaryPrimitives.ReadInt32LittleEndian(bytes.Slice(12, 4)),
BinaryPrimitives.ReadInt32LittleEndian(bytes.Slice(4, 4)),
BinaryPrimitives.ReadInt32LittleEndian(bytes.Slice(0, 4))
};
];

return new decimal(span);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,12 @@ internal static void WriteByteStringLength(IncrementalHash hasher, ulong value)
if (value < (byte)CborAdditionalInfo.Additional8BitData)
{
initialByte = new CborInitialByte(MajorType, (CborAdditionalInfo)value);
hasher.AppendData(stackalloc byte[] { initialByte.InitialByte });
hasher.AppendData([initialByte.InitialByte]);
}
else if (value <= byte.MaxValue)
{
initialByte = new CborInitialByte(MajorType, CborAdditionalInfo.Additional8BitData);
hasher.AppendData(stackalloc byte[] { initialByte.InitialByte, (byte)value });
hasher.AppendData([initialByte.InitialByte, (byte)value]);
}
else if (value <= ushort.MaxValue)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,9 +186,7 @@ protected override RSASignaturePadding GetSignaturePadding(
return RSASignaturePadding.Pkcs1;
}

Span<byte> expectedParameters = stackalloc byte[2];
expectedParameters[0] = 0x05;
expectedParameters[1] = 0x00;
ReadOnlySpan<byte> expectedParameters = [0x05, 0x00];

if (expectedParameters.SequenceEqual(signatureParameters.Value.Span))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ private static unsafe void FillKeyDerivation(
if (password.IsEmpty)
{
// CNG won't accept a null pointer for the password.
symmetricKeyMaterial = stackalloc byte[1];
symmetricKeyMaterial = [0];
symmetricKeyMaterialLength = 0;
clearSpan = default;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ private DefaultJavaScriptEncoder(TextEncoderSettings settings, bool allowMinimal

_innerEncoder = allowMinimalJsonEscaping
? new OptimizedInboxTextEncoder(EscaperImplementation.SingletonMinimallyEscaped, settings.GetAllowedCodePointsBitmap(), forbidHtmlSensitiveCharacters: false,
extraCharactersToEscape: stackalloc char[] { '\"', '\\' })
extraCharactersToEscape: ['\"', '\\'])
: new OptimizedInboxTextEncoder(EscaperImplementation.Singleton, settings.GetAllowedCodePointsBitmap(), forbidHtmlSensitiveCharacters: true,
extraCharactersToEscape: stackalloc char[] { '\\', '`' });
extraCharactersToEscape: ['\\', '`']);
}

public override int MaxOutputCharactersPerInputCharacter => 6; // "\uXXXX" for a single char ("\uXXXX\uYYYY" [12 chars] for supplementary scalar value)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ internal DefaultUrlEncoder(TextEncoderSettings settings)
// Basic Latin set is:
// ALPHA / DIGIT / "-" / "." / "_" / "~" / "!" / "$" / "(" / ")" / "*" / "," / ";" / "@"

_innerEncoder = new OptimizedInboxTextEncoder(EscaperImplementation.Singleton, settings.GetAllowedCodePointsBitmap(), extraCharactersToEscape: stackalloc char[] {
_innerEncoder = new OptimizedInboxTextEncoder(EscaperImplementation.Singleton, settings.GetAllowedCodePointsBitmap(), extraCharactersToEscape: [
' ', // chars from Basic Latin which aren't already disallowed by the base encoder
'#',
'%',
Expand Down Expand Up @@ -96,7 +96,7 @@ internal DefaultUrlEncoder(TextEncoderSettings settings)
'\uFFFD',
'\uFFFE',
'\uFFFF',
});
]);
}

public override int MaxOutputCharactersPerInputCharacter => 9; // "%XX%YY%ZZ" for a single char ("%XX%YY%ZZ%WW" [12 chars] for supplementary scalar value)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1541,7 +1541,7 @@ private static RegexCharClass ParseRecursive(string charClass, int start)
/// <param name="c">The character for which to create the set.</param>
/// <returns>The create set string.</returns>
public static string OneToStringClass(char c)
=> CharsToStringClass(stackalloc char[1] { c });
=> CharsToStringClass([c]);

internal static unsafe string CharsToStringClass(ReadOnlySpan<char> chars)
{
Expand Down

0 comments on commit ef56648

Please sign in to comment.