Skip to main content

malachite_base/options/
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::strings::typst::ToTypst;
10use core::fmt::{Formatter, Result};
11
12impl<T: ToTypst> ToTypst for Option<T> {
13    /// Writes an [`Option`] as a Typst math-mode fragment.
14    ///
15    /// [`None`] becomes `bot`, and [`Some`] wraps its value in square brackets. The brackets are
16    /// not decoration: without them `Some(None)` and [`None`] would both be `bot`, and distinct
17    /// values would have the same fragment.
18    ///
19    /// Typst grows a matched pair of delimiters to fit what is between them, so the brackets fit a
20    /// value that is taller than one line, such as a fraction or a nested [`Option`], without being
21    /// asked to.
22    ///
23    /// # Worst-case complexity
24    /// Same as the time and additional memory complexity of `fmt_typst` for `T`.
25    ///
26    /// # Examples
27    /// ```
28    /// use malachite_base::strings::typst::ToTypst;
29    ///
30    /// assert_eq!(None::<u8>.to_typst_string(), "bot");
31    /// assert_eq!(Some(5u8).to_typst_string(), "[5]");
32    /// assert_eq!(Some("hi").to_typst_string(), r#"["hi"]"#);
33    ///
34    /// // The brackets keep nested `Option`s apart.
35    /// assert_eq!(Some(None::<u8>).to_typst_string(), "[bot]");
36    /// assert_eq!(Some(Some(5u8)).to_typst_string(), "[[5]]");
37    /// ```
38    ///
39    /// | value              | fragment  |
40    /// |--------------------|-----------|
41    /// | `None::<u8>`       | `bot`     |
42    /// | `Some(5u8)`        | `[5]`     |
43    /// | `Some("hi")`       | `["hi"]`  |
44    /// | `Some(None::<u8>)` | `[bot]`   |
45    /// | `Some(Some(5u8))`  | `[[5]]`   |
46    #[inline]
47    fn fmt_typst(&self, f: &mut Formatter) -> Result {
48        match self {
49            None => f.write_str("bot"),
50            Some(x) => {
51                f.write_str("[")?;
52                x.fmt_typst(f)?;
53                f.write_str("]")
54            }
55        }
56    }
57}