Utilities.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Diagnostics;
  5. using System.Runtime.CompilerServices;
  6. using System.Runtime.Intrinsics.X86;
  7. namespace System.Buffers
  8. {
  9. internal static class Utilities
  10. {
  11. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  12. internal static int SelectBucketIndex(int bufferSize)
  13. {
  14. Debug.Assert(bufferSize >= 0);
  15. if (Lzcnt.IsSupported)
  16. {
  17. uint bits = ((uint)bufferSize - 1) >> 4;
  18. return 32 - (int)Lzcnt.LeadingZeroCount(bits);
  19. }
  20. // bufferSize of 0 will underflow here, causing a huge
  21. // index which the caller will discard because it is not
  22. // within the bounds of the bucket array.
  23. uint bitsRemaining = ((uint)bufferSize - 1) >> 4;
  24. int poolIndex = 0;
  25. if (bitsRemaining > 0xFFFF) { bitsRemaining >>= 16; poolIndex = 16; }
  26. if (bitsRemaining > 0xFF) { bitsRemaining >>= 8; poolIndex += 8; }
  27. if (bitsRemaining > 0xF) { bitsRemaining >>= 4; poolIndex += 4; }
  28. if (bitsRemaining > 0x3) { bitsRemaining >>= 2; poolIndex += 2; }
  29. if (bitsRemaining > 0x1) { bitsRemaining >>= 1; poolIndex += 1; }
  30. return poolIndex + (int)bitsRemaining;
  31. }
  32. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  33. internal static int GetMaxSizeForBucket(int binIndex)
  34. {
  35. int maxSize = 16 << binIndex;
  36. Debug.Assert(maxSize >= 0);
  37. return maxSize;
  38. }
  39. }
  40. }