malachite_base/rounding_modes/
from_str.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::rounding_modes::RoundingMode::{self, *};
10use alloc::string::String;
11use alloc::string::ToString;
12use core::str::FromStr;
13
14impl FromStr for RoundingMode {
15    type Err = String;
16
17    /// Converts a string to a [`RoundingMode`].
18    ///
19    /// If the string does not represent a valid [`RoundingMode`], an `Err` is returned with the
20    /// unparseable string.
21    ///
22    /// # Worst-case complexity
23    /// $T(n) = O(n)$
24    ///
25    /// $M(n) = O(n)$
26    ///
27    /// where $T$ is time, $M$ is additional memory, and $n$ = `src.len()`.
28    ///
29    /// The worst case occurs when the input string is invalid and must be copied into an `Err`.
30    ///
31    /// # Examples
32    /// ```
33    /// use malachite_base::rounding_modes::RoundingMode::{self, *};
34    /// use std::str::FromStr;
35    ///
36    /// assert_eq!(RoundingMode::from_str("Down"), Ok(Down));
37    /// assert_eq!(RoundingMode::from_str("Up"), Ok(Up));
38    /// assert_eq!(RoundingMode::from_str("Floor"), Ok(Floor));
39    /// assert_eq!(RoundingMode::from_str("Ceiling"), Ok(Ceiling));
40    /// assert_eq!(RoundingMode::from_str("Nearest"), Ok(Nearest));
41    /// assert_eq!(RoundingMode::from_str("Exact"), Ok(Exact));
42    /// assert_eq!(RoundingMode::from_str("abc"), Err("abc".to_string()));
43    /// ```
44    #[inline]
45    fn from_str(src: &str) -> Result<RoundingMode, String> {
46        match src {
47            "Down" => Ok(Down),
48            "Up" => Ok(Up),
49            "Floor" => Ok(Floor),
50            "Ceiling" => Ok(Ceiling),
51            "Nearest" => Ok(Nearest),
52            "Exact" => Ok(Exact),
53            _ => Err(src.to_string()),
54        }
55    }
56}