SpanHelpers.BinarySearch.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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.Collections.Generic;
  5. using System.Runtime.CompilerServices;
  6. using System.Runtime.InteropServices;
  7. using Internal.Runtime.CompilerServices;
  8. namespace System
  9. {
  10. internal static partial class SpanHelpers
  11. {
  12. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  13. public static int BinarySearch<T, TComparable>(
  14. this ReadOnlySpan<T> span, TComparable comparable)
  15. where TComparable : IComparable<T>
  16. {
  17. if (comparable == null)
  18. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparable);
  19. return BinarySearch(ref MemoryMarshal.GetReference(span), span.Length, comparable);
  20. }
  21. public static int BinarySearch<T, TComparable>(
  22. ref T spanStart, int length, TComparable comparable)
  23. where TComparable : IComparable<T>
  24. {
  25. int lo = 0;
  26. int hi = length - 1;
  27. // If length == 0, hi == -1, and loop will not be entered
  28. while (lo <= hi)
  29. {
  30. // PERF: `lo` or `hi` will never be negative inside the loop,
  31. // so computing median using uints is safe since we know
  32. // `length <= int.MaxValue`, and indices are >= 0
  33. // and thus cannot overflow an uint.
  34. // Saves one subtraction per loop compared to
  35. // `int i = lo + ((hi - lo) >> 1);`
  36. int i = (int)(((uint)hi + (uint)lo) >> 1);
  37. int c = comparable.CompareTo(Unsafe.Add(ref spanStart, i));
  38. if (c == 0)
  39. {
  40. return i;
  41. }
  42. else if (c > 0)
  43. {
  44. lo = i + 1;
  45. }
  46. else
  47. {
  48. hi = i - 1;
  49. }
  50. }
  51. // If none found, then a negative number that is the bitwise complement
  52. // of the index of the next element that is larger than or, if there is
  53. // no larger element, the bitwise complement of `length`, which
  54. // is `lo` at this point.
  55. return ~lo;
  56. }
  57. // Helper to allow sharing all code via IComparable<T> inlineable
  58. internal readonly struct ComparerComparable<T, TComparer> : IComparable<T>
  59. where TComparer : IComparer<T>
  60. {
  61. private readonly T _value;
  62. private readonly TComparer _comparer;
  63. public ComparerComparable(T value, TComparer comparer)
  64. {
  65. _value = value;
  66. _comparer = comparer;
  67. }
  68. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  69. public int CompareTo(T other) => _comparer.Compare(_value, other);
  70. }
  71. }
  72. }