commit 26d0198df0ae874a25d18e65b6c855c3eeeebef0
parent 551d3a0f1040ee9eed1039302dfd29c806f10db3
Author: Nikola <nikola@radojevic.rs>
Date: Thu, 5 May 2022 10:00:01 +0200
sort::search now returns an index to the element instead of a pointer
Fixes: https://todo.sr.ht/~sircmpwn/hare/678
Diffstat:
3 files changed, 13 insertions(+), 18 deletions(-)
diff --git a/fnmatch/fnmatch.ha b/fnmatch/fnmatch.ha
@@ -347,10 +347,10 @@ fn ctype_name_to_func(name: str) nullable *fn(c: rune) bool = {
("upper", &ascii::isupper), ("xdigit",&ascii::isxdigit),
];
match (sort::search(map, size(funcmap), &name, &cmp)) {
- case null =>
+ case void =>
return null: nullable *fn(c: rune) bool;
- case let p: *const void =>
- return (p: *const funcmap).1;
+ case let ind: size =>
+ return map[ind].1;
};
};
diff --git a/sort/+test.ha b/sort/+test.ha
@@ -40,11 +40,11 @@
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (let i = 0z; i < len(nums); i += 1) {
const key = nums[i];
- const p = search(nums, size(int), &key, &icmp) as *const int;
- assert(p == &nums[i] && *p == nums[i]);
+ const p = search(nums, size(int), &key, &icmp) as size;
+ assert(p == i);
};
const key = 1337;
- assert(search(nums, size(int), &key, &icmp) is null);
+ assert(search(nums, size(int), &key, &icmp) is void);
};
@test fn sort() void = {
diff --git a/sort/search.ha b/sort/search.ha
@@ -1,14 +1,14 @@
// License: MPL-2.0
// (c) 2021 Drew DeVault <sir@cmpwn.com>
-// Performs a binary search over a sorted slice. If the key is found, a pointer
-// to the matching item in the slice is returned. Otherwise, null is returned.
+// Performs a binary search over a sorted slice. If the key is found, index of
+// the matching item in the slice is returned. Otherwise, void is returned.
export fn search(
in: []const void,
sz: size,
key: const *void,
cmp: *cmpfunc,
-) nullable *const void = {
+) (size | void) = {
let ba = in: *[*]u8;
for (let nmemb = len(in); nmemb > 0) {
let v = &ba[nmemb / 2 * sz];
@@ -19,21 +19,16 @@ export fn search(
ba = (v: uintptr + sz: uintptr): *[*]u8;
nmemb -= nmemb / 2 + 1;
} else {
- return v;
+ const offs = (v: uintptr - in: *[*]const void: uintptr);
+ return (offs / sz: uintptr): size;
};
};
- return null;
+ return void;
};
// Performs a binary search over a sorted slice of strings. Sorting is done with
// respect to Unicode codepoints; see [[strings::compare]]. The index of the
// matching item in the slice is returned if found, otherwise void is returned.
export fn searchstrings(in: []const str, key: str) (size | void) = {
- match (search(in, size(str), &key, &scmp)) {
- case null =>
- return void;
- case let v: *const void =>
- const offs = (v: uintptr - in: *[*]const str: uintptr);
- return (offs / size(str): uintptr): size;
- };
+ return search(in, size(str), &key, &scmp);
};