malachite_base/num/arithmetic/sign.rs
1// Copyright © 2025 Mikhail Hogrefe
2//
3// This file is part of Malachite.
4//
5// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
6// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
7// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
8
9use crate::num::arithmetic::traits::Sign;
10use core::cmp::Ordering::{self, *};
11
12macro_rules! impl_sign_primitive_int {
13 ($t:ident) => {
14 impl Sign for $t {
15 /// Compares a number to zero.
16 ///
17 /// Returns `Greater`, `Equal`, or `Less`, depending on whether the number is positive,
18 /// zero, or negative, respectively.
19 ///
20 /// # Worst-case complexity
21 /// Constant time and additional memory.
22 ///
23 /// # Examples
24 /// See [here](super::sign#sign).
25 #[inline]
26 fn sign(&self) -> Ordering {
27 self.cmp(&0)
28 }
29 }
30 };
31}
32apply_to_primitive_ints!(impl_sign_primitive_int);
33
34macro_rules! impl_sign_primitive_float {
35 ($t:ident) => {
36 impl Sign for $t {
37 /// Compares a number to zero.
38 ///
39 /// - Positive finite numbers, positive zero, and positive infinity have sign `Greater`.
40 /// - Negative finite numbers, negative zero, and negative infinity have sign `Less`.
41 /// - `NaN` has sign `Equal`.
42 ///
43 /// # Worst-case complexity
44 /// Constant time and additional memory.
45 ///
46 /// # Examples
47 /// See [here](super::sign#sign).
48 #[inline]
49 fn sign(&self) -> Ordering {
50 if self.is_nan() {
51 Equal
52 } else if self.is_sign_positive() {
53 Greater
54 } else {
55 Less
56 }
57 }
58 }
59 };
60}
61apply_to_primitive_floats!(impl_sign_primitive_float);