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