malachite_q/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::Rational;
10use core::cmp::Ordering::{self, *};
11use malachite_base::num::arithmetic::traits::Sign;
12
13impl Sign for Rational {
14    /// Compares a [`Rational`] to zero.
15    ///
16    /// Returns `Greater`, `Equal`, or `Less`, depending on whether the [`Rational`] is positive,
17    /// zero, or negative, respectively.
18    ///
19    /// # Worst-case complexity
20    /// Constant time and additional memory.
21    ///
22    /// # Examples
23    /// ```
24    /// use malachite_base::num::arithmetic::traits::Sign;
25    /// use malachite_base::num::basic::traits::Zero;
26    /// use malachite_q::Rational;
27    /// use std::cmp::Ordering::*;
28    ///
29    /// assert_eq!(Rational::ZERO.sign(), Equal);
30    /// assert_eq!(Rational::from_signeds(22, 7).sign(), Greater);
31    /// assert_eq!(Rational::from_signeds(-22, 7).sign(), Less);
32    /// ```
33    fn sign(&self) -> Ordering {
34        if self.sign {
35            if self.numerator == 0 { Equal } else { Greater }
36        } else {
37            Less
38        }
39    }
40}