Skip to content

Commit 28d9967

Browse files
authored
Reduce per-lookup overhead from key validation in HybridCache (#6441)
* Reduce per-lookup overhead from key validation in HybridCache * Might as well be static
1 parent 53093ea commit 28d9967

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

src/Libraries/Microsoft.Extensions.Caching.Hybrid/Internal/DefaultHybridCache.cs

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,6 @@ internal sealed partial class DefaultHybridCache : HybridCache
2626
{
2727
internal const int DefaultExpirationMinutes = 5;
2828

29-
// reserve non-printable characters from keys, to prevent potential L2 abuse
30-
private static readonly char[] _keyReservedCharacters = Enumerable.Range(0, 32).Select(i => (char)i).ToArray();
31-
3229
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0032:Use auto property", Justification = "Keep usage explicit")]
3330
private readonly IDistributedCache? _backendCache;
3431
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0032:Use auto property", Justification = "Keep usage explicit")]
@@ -255,6 +252,26 @@ private static ValueTask<T> RunWithoutCacheAsync<TState, T>(HybridCacheEntryFlag
255252
return null;
256253
}
257254

255+
// reserve non-printable characters from keys, to prevent potential L2 abuse
256+
private static bool ContainsReservedCharacters(ReadOnlySpan<char> key)
257+
{
258+
const char MaxControlChar = (char)31;
259+
260+
#if NET8_0_OR_GREATER
261+
return key.IndexOfAnyInRange((char)0, MaxControlChar) >= 0;
262+
#else
263+
foreach (char c in key)
264+
{
265+
if (c <= MaxControlChar)
266+
{
267+
return true;
268+
}
269+
}
270+
271+
return false;
272+
#endif
273+
}
274+
258275
private bool ValidateKey(string key)
259276
{
260277
if (string.IsNullOrWhiteSpace(key))
@@ -269,7 +286,7 @@ private bool ValidateKey(string key)
269286
return false;
270287
}
271288

272-
if (key.IndexOfAny(_keyReservedCharacters) >= 0)
289+
if (ContainsReservedCharacters(key.AsSpan()))
273290
{
274291
_logger.KeyInvalidContent();
275292
return false;

0 commit comments

Comments
 (0)