binn_ir/cmp.rs
1/*
2==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--
3
4Binn-IR
5
6Copyright (C) 2018-2023 Anonymous
7
8There are several releases over multiple years,
9they are listed as ranges, such as: "2018-2023".
10
11This program is free software: you can redistribute it and/or modify
12it under the terms of the GNU Lesser General Public License as published by
13the Free Software Foundation, either version 3 of the License, or
14(at your option) any later version.
15
16This program is distributed in the hope that it will be useful,
17but WITHOUT ANY WARRANTY; without even the implied warranty of
18MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19GNU Lesser General Public License for more details.
20
21You should have received a copy of the GNU Lesser General Public License
22along with this program. If not, see <https://www.gnu.org/licenses/>.
23
24::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--
25*/
26
27//! # Helper for comparing things
28
29use core::{
30 cmp::Ordering,
31 mem,
32};
33
34/// # Helps compare 2 things
35pub (crate) trait CmpTo<T: Ord>: Ord {
36
37 /// # Comapres to target
38 fn cmp_to(&self, target: &T) -> Ordering;
39
40}
41
42impl CmpTo<u32> for i32 {
43
44 fn cmp_to(&self, target: &u32) -> Ordering {
45 if self < &0 {
46 Ordering::Less
47 } else {
48 (*self as u32).cmp(target)
49 }
50 }
51
52}
53
54macro_rules! impl_cmp_to_for_same_sign {
55 ($($src: ty, $target: ty, $test_fn_name: tt,)+) => {
56 $(
57 #[test]
58 #[allow(unused_comparisons)]
59 fn $test_fn_name() {
60 let min_src = <$src>::min_value();
61 let min_target = <$target>::min_value();
62 assert!((min_src < 0 && min_target < 0) || (min_src >= 0 && min_target >= 0));
63 }
64
65 impl CmpTo<$target> for $src {
66
67 fn cmp_to(&self, target: &$target) -> Ordering {
68 if mem::size_of::<Self>() >= mem::size_of::<$target>() {
69 self.cmp(&(*target as Self))
70 } else {
71 (*self as $target).cmp(target)
72 }
73 }
74
75 }
76 )+
77 }
78}
79
80impl_cmp_to_for_same_sign!(
81 usize, u32, test_impl_of_usize_u32,
82 u32, usize, test_impl_of_u32_usize,
83);
84
85macro_rules! impl_cmp_to_for_one_type {
86 ($($ty: ty,)+) => {
87 $(
88 impl CmpTo<$ty> for $ty {
89
90 fn cmp_to(&self, target: &$ty) -> Ordering {
91 self.cmp(target)
92 }
93
94 }
95 )+
96 }
97}
98
99impl_cmp_to_for_one_type!(usize, u32,);