malachite_q/conversion/string/
from_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::str::FromStr;
11use malachite_base::num::basic::traits::One;
12use malachite_nz::natural::Natural;
13
14impl FromStr for Rational {
15    type Err = ();
16
17    /// Converts an string to a [`Rational`].
18    ///
19    /// If the string does not represent a valid [`Rational`], an `Err` is returned. The numerator
20    /// and denominator do not need to be in lowest terms, but the denominator must be nonzero. A
21    /// negative sign is only allowed at the 0th position of the string.
22    ///
23    /// # Worst-case complexity
24    /// $T(n) = O(n (\log n)^2 \log\log n)$
25    ///
26    /// $M(n) = O(n \log n)$
27    ///
28    /// where $T$ is time, $M$ is additional memory, and $n$ is `s.len()`.
29    ///
30    /// # Examples
31    /// ```
32    /// use malachite_q::Rational;
33    /// use std::str::FromStr;
34    ///
35    /// assert_eq!(Rational::from_str("123456").unwrap(), 123456);
36    /// assert_eq!(Rational::from_str("00123456").unwrap(), 123456);
37    /// assert_eq!(Rational::from_str("0").unwrap(), 0);
38    /// assert_eq!(Rational::from_str("-123456").unwrap(), -123456);
39    /// assert_eq!(Rational::from_str("-00123456").unwrap(), -123456);
40    /// assert_eq!(Rational::from_str("-0").unwrap(), 0);
41    /// assert_eq!(Rational::from_str("22/7").unwrap().to_string(), "22/7");
42    /// assert_eq!(Rational::from_str("01/02").unwrap().to_string(), "1/2");
43    /// assert_eq!(Rational::from_str("3/21").unwrap().to_string(), "1/7");
44    /// assert_eq!(Rational::from_str("-22/7").unwrap().to_string(), "-22/7");
45    /// assert_eq!(Rational::from_str("-01/02").unwrap().to_string(), "-1/2");
46    /// assert_eq!(Rational::from_str("-3/21").unwrap().to_string(), "-1/7");
47    ///
48    /// assert!(Rational::from_str("").is_err());
49    /// assert!(Rational::from_str("a").is_err());
50    /// assert!(Rational::from_str("1/0").is_err());
51    /// assert!(Rational::from_str("/1").is_err());
52    /// assert!(Rational::from_str("1/").is_err());
53    /// assert!(Rational::from_str("--1").is_err());
54    /// assert!(Rational::from_str("1/-2").is_err());
55    /// ```
56    #[inline]
57    fn from_str(s: &str) -> Result<Self, ()> {
58        let (abs_string, sign) = if let Some(abs_string) = s.strip_prefix('-') {
59            if abs_string.starts_with('+') {
60                return Err(());
61            }
62            (abs_string, false)
63        } else {
64            (s, true)
65        };
66        let numerator;
67        let denominator;
68        if let Some(slash_index) = abs_string.find('/') {
69            numerator = Natural::from_str(&abs_string[..slash_index])?;
70            denominator = Natural::from_str(&abs_string[slash_index + 1..])?;
71            if denominator == 0u32 {
72                return Err(());
73            }
74        } else {
75            numerator = Natural::from_str(abs_string)?;
76            denominator = Natural::ONE;
77        }
78        Ok(Self::from_sign_and_naturals(sign, numerator, denominator))
79    }
80}