std: Restore conventional compareFn behavior for binarySearch

PR #20927 made some improvements to the `binarySearch` API, but one
change I found surprising was the relationship between the left-hand and
right-hand parameters of `compareFn` was inverted. This is different
from how comparison functions typically behave, both in other parts of
Zig (e.g. `std.math.order`) and in other languages (e.g. C's `bsearch`).
Unless a strong reason can be identified and documented for doing
otherwise, I think it'll be better to stick with convention.

While writing this patch and changing things back to the way they were,
the predicates of `lowerBound` and `upperBound` seemed to be the only
areas that benefited from the inversion. I don't think that benefit is
worth the cost, personally. Calling `Order.invert()` in the predicates
accomplishes the same goal.
This commit is contained in:
Jay Petacat
2024-09-09 22:23:18 -06:00
committed by Andrew Kelley
parent 7caa3d9da7
commit 812557bfde
5 changed files with 30 additions and 32 deletions

View File

@@ -182,7 +182,7 @@ pub const CompileUnit = struct {
pub fn findSource(slc: *const SrcLocCache, address: u64) !LineEntry {
const index = std.sort.upperBound(u64, slc.line_table.keys(), address, struct {
fn order(context: u64, item: u64) std.math.Order {
return std.math.order(item, context);
return std.math.order(context, item);
}
}.order);
if (index == 0) return missing();