Skip to main content

malachite_nz/integer_vector/conversion/string/
from_string.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::integer::Integer;
10use crate::integer_vector::IntegerVector;
11use alloc::vec::Vec;
12use core::str::FromStr;
13
14impl FromStr for IntegerVector {
15    type Err = ();
16
17    /// Converts a string to an [`IntegerVector`].
18    ///
19    /// This reads back what [`Display`](core::fmt::Display) writes: the elements in order,
20    /// separated by `", "` and enclosed in parentheses, with `()` for the 0-dimensional vector.
21    /// Each element is read the way [`Integer::from_str`] reads one, so it may have leading zeros
22    /// and a single leading `'-'` or `'+'`. Any other spacing, such as `(1,2)` or `( 1, 2 )`, is
23    /// rejected, as is an empty element.
24    ///
25    /// If the string does not represent an [`IntegerVector`], an `Err` is returned.
26    ///
27    /// # Worst-case complexity
28    /// $T(n) = O(n (\log n)^2 \log\log n)$
29    ///
30    /// $M(n) = O(n \log n)$
31    ///
32    /// where $T$ is time, $M$ is additional memory, and $n$ is `s.len()`.
33    ///
34    /// # Examples
35    /// ```
36    /// use core::str::FromStr;
37    /// use malachite_base::vector::Vector;
38    /// use malachite_nz::integer_vector::IntegerVector;
39    ///
40    /// assert_eq!(
41    ///     IntegerVector::from_str("(1, 2, 3)").unwrap().to_string(),
42    ///     "(1, 2, 3)"
43    /// );
44    /// assert_eq!(IntegerVector::from_str("(5)").unwrap().to_string(), "(5)");
45    /// assert_eq!(IntegerVector::from_str("()").unwrap().dimension(), 0);
46    ///
47    /// // An element may be written as `Integer::from_str` accepts it.
48    /// assert_eq!(
49    ///     IntegerVector::from_str("(-1, -0, +2)").unwrap().to_string(),
50    ///     "(-1, 0, 2)"
51    /// );
52    /// assert_eq!(
53    ///     IntegerVector::from_str("(007, +8)").unwrap().to_string(),
54    ///     "(7, 8)"
55    /// );
56    ///
57    /// assert!(IntegerVector::from_str("").is_err());
58    /// assert!(IntegerVector::from_str("1, 2").is_err());
59    /// assert!(IntegerVector::from_str("(1,2)").is_err());
60    /// assert!(IntegerVector::from_str("( 1, 2 )").is_err());
61    /// assert!(IntegerVector::from_str("(1, )").is_err());
62    /// assert!(IntegerVector::from_str("(--1)").is_err());
63    /// ```
64    fn from_str(s: &str) -> Result<Self, ()> {
65        let inner = s
66            .strip_prefix('(')
67            .and_then(|s| s.strip_suffix(')'))
68            .ok_or(())?;
69        if inner.is_empty() {
70            return Ok(Self {
71                elements: Vec::new(),
72            });
73        }
74        Ok(Self {
75            elements: inner
76                .split(", ")
77                .map(Integer::from_str)
78                .collect::<Result<_, _>>()?,
79        })
80    }
81}