Skip to content
This repository has been archived by the owner on Mar 21, 2024. It is now read-only.

Fix binary search middle calculation to avoid overflows #1306

Merged
merged 1 commit into from
Oct 14, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions thrust/system/detail/generic/scalar/binary_search.inl
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ RandomAccessIterator lower_bound_n(RandomAccessIterator first,
Size start = 0, i;
while(start < n)
{
i = (start + n) / 2;
i = start + (n - start) / 2; // Overflow-safe variant of (a+b)/2
if(wrapped_comp(first[i], val))
{
start = i + 1;
Expand All @@ -62,7 +62,7 @@ RandomAccessIterator lower_bound_n(RandomAccessIterator first,
n = i;
}
} // end while

return first + start;
}

Expand Down Expand Up @@ -94,7 +94,7 @@ RandomAccessIterator upper_bound_n(RandomAccessIterator first,
Size start = 0, i;
while(start < n)
{
i = (start + n) / 2;
i = start + (n - start) / 2; // Overflow-safe variant of (a+b)/2
if(wrapped_comp(val, first[i]))
{
n = i;
Expand All @@ -104,7 +104,7 @@ RandomAccessIterator upper_bound_n(RandomAccessIterator first,
start = i + 1;
}
} // end while

return first + start;
}

Expand Down Expand Up @@ -156,4 +156,3 @@ bool binary_search(RandomAccessIterator first, RandomAccessIterator last, const
} // end thrust

#include <thrust/system/detail/generic/scalar/binary_search.inl>