Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Commit 42c5dec

Browse files
committed
compute median without subtract
1 parent 41ebc1c commit 42c5dec

File tree

2 files changed

+4
-4
lines changed

2 files changed

+4
-4
lines changed

src/System.Memory/src/System/SpanHelpers.BinarySearch.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,9 @@ internal static int BinarySearch<T, TComparable>(
3434
// TODO: Test/investigate if below is faster (if it gives better asm), perhaps via Unsafe.As to avoid unnecessary conversions
3535
// This is safe since we know span.Length < int.MaxValue, and indeces are >= 0
3636
// and thus cannot overflow an uint. Saves on subtraction per loop.
37-
// int i = (int)(((uint)hi + (uint)lo) >> 1)
38-
int i = lo + ((hi - lo) >> 1);
37+
int i = (int)(((uint)hi + (uint)lo) >> 1);
38+
// Below was intended to avoid overflows, but this cannot happen if we do the computation in uint
39+
//int i = lo + ((hi - lo) >> 1);
3940

4041
// TODO: We probably need to add `ref readonly`/`in` overloads or `AddReadOnly`to unsafe,
4142
// if this will be available in language

src/System.Memory/tests/ReadOnlySpan/BinarySearch.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,8 +74,7 @@ public unsafe static void BinarySearch_MaxLength_NoOverflow()
7474
{
7575
// Allocate max size span memory
7676
var length = int.MaxValue;
77-
IntPtr memory;
78-
if (!AllocationHelper.TryAllocNative(new IntPtr(length), out memory))
77+
if (!AllocationHelper.TryAllocNative(new IntPtr(length), out IntPtr memory))
7978
{
8079
Console.WriteLine($"Span.BinarySearch test {nameof(BinarySearch_MaxLength_NoOverflow)} skipped (could not alloc memory).");
8180
return;

0 commit comments

Comments
 (0)