malachite_q/conversion/string/
to_string.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::fmt::{Debug, Display, Formatter, Result, Write};
11
12impl Display for Rational {
13    /// Converts a [`Rational`] to a [`String`].
14    ///
15    /// # Worst-case complexity
16    /// $T(n) = O(n (\log n)^2 \log\log n)$
17    ///
18    /// $M(n) = O(n \log n)$
19    ///
20    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
21    ///
22    /// # Examples
23    /// ```
24    /// use malachite_base::num::basic::traits::Zero;
25    /// use malachite_q::Rational;
26    /// use std::str::FromStr;
27    ///
28    /// assert_eq!(Rational::ZERO.to_string(), "0");
29    /// assert_eq!(Rational::from(123).to_string(), "123");
30    /// assert_eq!(Rational::from_str("22/7").unwrap().to_string(), "22/7");
31    /// ```
32    fn fmt(&self, f: &mut Formatter) -> Result {
33        if !self.sign {
34            f.write_char('-')?;
35        }
36        let result = Display::fmt(&self.numerator, f);
37        if self.denominator == 1 {
38            result
39        } else {
40            f.write_char('/')?;
41            Display::fmt(&self.denominator, f)
42        }
43    }
44}
45
46impl Debug for Rational {
47    /// Converts a [`Rational`] to a [`String`].
48    ///
49    /// This is the same implementation as for [`Display`].
50    ///
51    /// # Worst-case complexity
52    /// $T(n) = O(n (\log n)^2 \log\log n)$
53    ///
54    /// $M(n) = O(n \log n)$
55    ///
56    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
57    ///
58    /// # Examples
59    /// ```
60    /// use malachite_base::num::basic::traits::Zero;
61    /// use malachite_base::strings::ToDebugString;
62    /// use malachite_q::Rational;
63    ///
64    /// assert_eq!(Rational::ZERO.to_debug_string(), "0");
65    /// assert_eq!(Rational::from(123).to_debug_string(), "123");
66    /// assert_eq!(Rational::from_signeds(22, 7).to_debug_string(), "22/7");
67    /// ```
68    #[inline]
69    fn fmt(&self, f: &mut Formatter) -> Result {
70        Display::fmt(self, f)
71    }
72}