dcc_lsystem/
token.rs

1use crate::arena::{Arena, ArenaId};
2
3/// A token for use in an L-system.  In general, the `LSystem` owns the token,
4/// while the user can refer to the token via an `ArenaId`.  This means
5/// we don't have to deal with any tricky ownership issues.
6#[derive(Debug, Clone, Eq, PartialEq)]
7pub struct Token {
8    name: String,
9}
10
11impl Token {
12    /// Create a new token with the given name.
13    ///
14    /// # Panics
15    /// This function will panic if `name` contains any spaces
16    pub fn new<T: Into<String>>(name: T) -> Self {
17        let name = name.into();
18
19        if name.contains(' ') {
20            panic!("Token name may not contain whitespace");
21        }
22
23        Self { name }
24    }
25
26    /// Get the name of this token
27    pub fn name(&self) -> &String {
28        &self.name
29    }
30}
31
32impl std::fmt::Display for Token {
33    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
34        write!(f, "{}", self.name())
35    }
36}
37
38impl Arena<Token> {
39    /// Returns a string representation of the given slice of ArenaId's in terms
40    /// of the contents of this arena.
41    pub fn render(&self, tokens: &[ArenaId]) -> String {
42        assert!(self.is_valid_slice(tokens));
43
44        let mut st = String::new();
45
46        for token in tokens {
47            st.push_str(&format!("{}", self.get(*token).unwrap()));
48        }
49
50        st
51    }
52}