Skip to main content

trumly_core/
model.rs

1//! The in-memory shape of a model: nodes, links, and the graph that holds them.
2//! Mirrors spec/FORMAT.md section 2. Nothing here reads files; that is the parser's job.
3
4use std::collections::BTreeMap;
5
6// serde_json::Value is "any JSON value": null, bool, number, string, list or map.
7// Node fields are free-form, so we need a type that can hold any of those.
8use serde_json::Value;
9
10/// Free-form key/value data. BTreeMap (not HashMap) keeps keys sorted,
11/// which makes our output deterministic, and the fixtures compare output exactly.
12pub type Fields = BTreeMap<String, Value>;
13
14/// A typed, directed edge. It is stored on the node it starts from; the target is only an id.
15/// Holding an id (a String) instead of a reference to the target Node avoids
16/// self-referential structs, which Rust's ownership rules make painful.
17#[derive(Debug, Clone, PartialEq)]
18pub struct Link {
19    /// The link type. The spec calls this `type`, which is a reserved word in Rust.
20    pub kind: String,        // the spec calls this `type`; that is a reserved word in Rust
21    /// Id of the target node.
22    pub to: String,          // id of the target node
23    /// An optional key the file gave this link.
24    pub key: Option<String>, // Option = "may be absent"; Rust has no null
25    /// Extra data carried on the link.
26    pub fields: Fields,
27}
28
29#[derive(Debug, Clone, PartialEq)]
30/// One file of the model: a node with its front matter, links and markdown body.
31pub struct Node {
32    /// The node's id; it matches the file name without `.md`.
33    pub id: String,
34    /// The node's `type`. `None` if the file had none, which is a structure finding, not a load error.
35    pub kind: Option<String>, // None means the file had no `type`; that is a finding, not a load error
36    /// Display title; the id when the file gives none.
37    pub title: String,        // defaults to the id when the file has none
38    /// Id of the parent node, if any.
39    pub parent: Option<String>,
40    /// Id of the plane the node sits in, if any.
41    pub plane: Option<String>,
42    /// The other front matter fields.
43    pub fields: Fields,
44    /// Links from this node to other nodes.
45    pub links: Vec<Link>,
46    /// The markdown body.
47    pub body: String,
48}
49
50/// The whole model: every node, looked up by id. BTreeMap again, so iteration is in id order,
51/// which is exactly the order the spec requires for output.
52#[derive(Debug, Default)]
53pub struct Graph {
54    nodes: BTreeMap<String, Node>,
55}
56
57impl Graph {
58    /// An empty graph.
59    pub fn new() -> Self {
60        Self::default()
61    }
62
63    /// Add a node. If the id is already taken the existing node is kept ("first wins", the
64    /// spec's duplicate rule) and the rejected node is handed back in `Err`.
65    pub fn insert(&mut self, node: Node) -> Result<(), Node> {
66        if self.nodes.contains_key(&node.id) {
67            return Err(node);
68        }
69        self.nodes.insert(node.id.clone(), node);
70        Ok(())
71    }
72
73    /// Look a node up. Returns a borrowed reference, not a copy: `Option<&Node>`.
74    pub fn get(&self, id: &str) -> Option<&Node> {
75        self.nodes.get(id)
76    }
77
78    /// The scratch plane a node sits in, if it is in one: its `plane` names a `plane` node with `fields.scratch: true`.
79    /// A scratch is a sandbox: rules skip its nodes and nothing outside it may link to or parent them.
80    pub fn scratch_of<'a>(&'a self, node: &'a Node) -> Option<&'a str> {
81        let p = node.plane.as_deref()?;
82        let plane = self.get(p)?;
83        (plane.kind.as_deref() == Some("plane") && plane.fields.get("scratch") == Some(&serde_json::Value::Bool(true))).then_some(p)
84    }
85
86    /// The number of nodes.
87    pub fn len(&self) -> usize {
88        self.nodes.len()
89    }
90
91    /// True when the graph has no nodes.
92    pub fn is_empty(&self) -> bool {
93        self.nodes.is_empty()
94    }
95
96    /// Every node in id order. `impl Iterator` means "something you can loop over".
97    pub fn nodes(&self) -> impl Iterator<Item = &Node> {
98        self.nodes.values()
99    }
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105
106    fn node(id: &str, parent: Option<&str>) -> Node {
107        Node {
108            id: id.to_string(),
109            kind: Some("thing".to_string()),
110            title: id.to_string(),
111            parent: parent.map(|p| p.to_string()),
112            plane: None,
113            fields: Fields::new(),
114            links: vec![],
115            body: String::new(),
116        }
117    }
118
119    #[test]
120    fn insert_and_get() {
121        let mut g = Graph::new();
122        assert!(g.insert(node("a", None)).is_ok());
123        assert_eq!(g.len(), 1);
124        assert_eq!(g.get("a").unwrap().title, "a");
125        assert!(g.get("missing").is_none());
126    }
127
128    #[test]
129    fn first_duplicate_wins() {
130        let mut g = Graph::new();
131        let mut first = node("a", None);
132        first.title = "first".into();
133        let mut second = node("a", None);
134        second.title = "second".into();
135        assert!(g.insert(first).is_ok());
136        assert!(g.insert(second).is_err());
137        assert_eq!(g.get("a").unwrap().title, "first");
138    }
139
140    #[test]
141    fn iterates_in_id_order() {
142        let mut g = Graph::new();
143        for id in ["c", "a", "b"] {
144            g.insert(node(id, None)).unwrap();
145        }
146        let ids: Vec<&str> = g.nodes().map(|n| n.id.as_str()).collect();
147        assert_eq!(ids, ["a", "b", "c"]);
148    }
149
150    #[test]
151    fn links_are_stored_on_the_source() {
152        let mut n = node("a", None);
153        n.links.push(Link { kind: "uses".into(), to: "b".into(), key: None, fields: Fields::new() });
154        assert_eq!(n.links.len(), 1);
155        assert_eq!(n.links[0].to, "b");
156    }
157}