commit 38a5c85d8d45c3ef7836990dd6e704305d7285f6
parent c256d7067888ccea3a747dee26ae5e9c9beb709c
Author: Bor Grošelj Simić <bgs@turminal.net>
Date: Thu, 10 Nov 2022 21:43:26 +0100
fix sort::icmp
the old version produced incorrect results in some edge cases involving
INT_MIN.
Signed-off-by: Bor Grošelj Simić <bgs@turminal.net>
Diffstat:
4 files changed, 16 insertions(+), 5 deletions(-)
diff --git a/scripts/gen-stdlib b/scripts/gen-stdlib
@@ -1218,7 +1218,7 @@ sort() {
gensrcs_sort \
+test.ha
fi
- gen_ssa sort strings
+ gen_ssa sort strings types
}
strconv() {
diff --git a/sort/+test.ha b/sort/+test.ha
@@ -1,6 +1,7 @@
// License: MPL-2.0
// (c) 2021 Drew DeVault <sir@cmpwn.com>
// (c) 2021 Eyal Sawady <ecs@d2evs.net>
+use types;
@test fn lbisect() void = {
const nums = [1, 3, 4, 4, 5, 7, 9, 11, 11, 11];
@@ -71,3 +72,11 @@
assert(sorted(nums, size(int), &icmp));
assert(sorted(nums[..0], size(int), &icmp));
};
+
+@test fn icmp() void = {
+ assert(icmp(&5, &0) == 1);
+ assert(icmp(&0, &5) == -1);
+ assert(icmp(&0, &0) == 0);
+ assert(icmp(&0, &types::INT_MIN) == 1);
+ assert(icmp(&types::INT_MIN, &0) == -1);
+};
diff --git a/sort/types.ha b/sort/types.ha
@@ -14,6 +14,8 @@ fn scmp(a: const *void, b: const *void) int = {
};
fn icmp(a: const *void, b: const *void) int = {
- const a = a: const *int, b = b: const *int;
- return *a - *b;
+ const a = *(a: const *int), b = *(b: const *int);
+ return if (a < b) -1
+ else if (a > b) 1
+ else 0;
};
diff --git a/stdlib.mk b/stdlib.mk
@@ -1853,7 +1853,7 @@ stdlib_sort_any_srcs = \
$(STDLIB)/sort/sort.ha \
$(STDLIB)/sort/types.ha
-$(HARECACHE)/sort/sort-any.ssa: $(stdlib_sort_any_srcs) $(stdlib_rt) $(stdlib_strings_$(PLATFORM))
+$(HARECACHE)/sort/sort-any.ssa: $(stdlib_sort_any_srcs) $(stdlib_rt) $(stdlib_strings_$(PLATFORM)) $(stdlib_types_$(PLATFORM))
@printf 'HAREC \t$@\n'
@mkdir -p $(HARECACHE)/sort
@HARECACHE=$(HARECACHE) $(HAREC) $(HAREFLAGS) -o $@ -Nsort \
@@ -4086,7 +4086,7 @@ testlib_sort_any_srcs = \
$(STDLIB)/sort/types.ha \
$(STDLIB)/sort/+test.ha
-$(TESTCACHE)/sort/sort-any.ssa: $(testlib_sort_any_srcs) $(testlib_rt) $(testlib_strings_$(PLATFORM))
+$(TESTCACHE)/sort/sort-any.ssa: $(testlib_sort_any_srcs) $(testlib_rt) $(testlib_strings_$(PLATFORM)) $(testlib_types_$(PLATFORM))
@printf 'HAREC \t$@\n'
@mkdir -p $(TESTCACHE)/sort
@HARECACHE=$(TESTCACHE) $(HAREC) $(TESTHAREFLAGS) -o $@ -Nsort \