malachite_q/rational_vector/conversion/string/typst.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::rational_vector::RationalVector;
10use core::fmt::{Formatter, Result};
11use malachite_base::strings::typst::ToTypst;
12
13impl ToTypst for RationalVector {
14 /// Writes a [`RationalVector`] as a Typst math-mode fragment.
15 ///
16 /// The elements' fragments are separated by commas and enclosed in parentheses, as a vector's
17 /// coordinates are written by hand; Typst grows the parentheses to fit their contents. The
18 /// 0-dimensional vector is `()`.
19 ///
20 /// # Worst-case complexity
21 /// $T(n) = O(n (\log n)^2 \log\log n)$
22 ///
23 /// $M(n) = O(n \log n)$
24 ///
25 /// where $T$ is time, $M$ is additional memory, and $n$ is the sum of the bits of the elements.
26 ///
27 /// # Examples
28 /// ```
29 /// use core::str::FromStr;
30 /// use malachite_base::strings::typst::ToTypst;
31 /// use malachite_q::Rational;
32 /// use malachite_q::rational_vector::RationalVector;
33 ///
34 /// let v = RationalVector {
35 /// elements: vec![Rational::from(1u32), Rational::from(2u32), Rational::from(3u32)],
36 /// };
37 /// assert_eq!(v.to_typst_string(), "(1, 2, 3)");
38 /// assert_eq!(
39 /// RationalVector::from_str("(1/2)").unwrap().to_typst_string(),
40 /// "(frac(1, 2))"
41 /// );
42 /// assert_eq!(
43 /// RationalVector {
44 /// elements: vec![Rational::from(5u32)]
45 /// }
46 /// .to_typst_string(),
47 /// "(5)"
48 /// );
49 /// assert_eq!(
50 /// RationalVector {
51 /// elements: Vec::new()
52 /// }
53 /// .to_typst_string(),
54 /// "()"
55 /// );
56 /// ```
57 ///
58 /// The value column holds each vector as [`Display`](core::fmt::Display) writes it.
59 ///
60 /// | value | fragment |
61 /// |-------------|----------------|
62 /// | `(1/2)` | `(frac(1, 2))` |
63 /// | `(1, 2, 3)` | `(1, 2, 3)` |
64 /// | `(5)` | `(5)` |
65 /// | `()` | `()` |
66 fn fmt_typst(&self, f: &mut Formatter) -> Result {
67 f.write_str("(")?;
68 for (i, x) in self.elements.iter().enumerate() {
69 if i != 0 {
70 f.write_str(", ")?;
71 }
72 x.fmt_typst(f)?;
73 }
74 f.write_str(")")
75 }
76}