graphity_dot/attributes.rs
1//! The attributes that the attribute hooks of [`DotWriter`](crate::DotWriter) put - the
2//! `Map<String, String>` of Java's `AttributeHook`.
3
4use std::borrow::Cow;
5use std::iter::FusedIterator;
6use std::slice;
7
8/// The attributes of one node or edge, name to value, in the order they were put: the map that the
9/// hooks of [`DotWriter::node_attributes`](crate::DotWriter::node_attributes) and
10/// [`DotWriter::edge_attributes`](crate::DotWriter::edge_attributes) fill.
11///
12/// The attributes, such as `color` or `shape`, are those of DOT (the language of Graphviz). Java's
13/// `AttributeHook` is a closure `Fn(u32, &mut Attributes<'a>)` here, called with the node ID or edge
14/// index and this map. The writer passes it holding the label from
15/// [`node_label`](crate::DotWriter::node_label) or [`edge_label`](crate::DotWriter::edge_label) as the
16/// attribute `label`, if there is one, and nothing else; the hook can add attributes, and replace or
17/// remove the label. The writer writes the attributes in the order they were put and escapes their
18/// values; a name that is not an identifier or is a DOT keyword makes
19/// [`write`](crate::DotWriter::write) panic with an `invalid argument` message. The writer reuses the
20/// map for every node and edge, so a hook cannot keep it: the borrow ends with the call.
21///
22/// ```
23/// use graphity_core::GraphBuilder;
24/// use graphity_dot::DotWriter;
25///
26/// let mut b = GraphBuilder::new();
27/// b.add_nodes(2);
28/// b.add_edge(0, 1);
29/// let graph = b.build();
30///
31/// let dot = DotWriter::of(&graph)
32/// .node_label(|node| Some(format!("v{node}").into()))
33/// .node_attributes(|node, attributes| {
34/// if node == 0 {
35/// attributes.insert("shape", "box");
36/// attributes.insert("label", "entry"); // replaces the label, keeps its place
37/// }
38/// })
39/// .write_to_string();
40/// assert!(dot.contains(" 0 [label=\"entry\", shape=\"box\"];\n"));
41/// ```
42///
43/// Names and values are [`Cow`]s: a string literal or a `&str` into the caller's data, which lives
44/// for the writer's lifetime `'a`, is kept without a copy, and a computed `String` is moved in.
45///
46/// Putting a name that is present replaces its value in place, as Java's `LinkedHashMap.put` does;
47/// removing an entry keeps the order of the others. Lookups search the entries linearly: an element
48/// carries a handful of attributes, for which a vector of pairs is faster than hashing.
49#[derive(Debug, Clone, Default, PartialEq, Eq)]
50pub struct Attributes<'a> {
51 entries: Vec<(Cow<'a, str>, Cow<'a, str>)>,
52}
53
54impl<'a> Attributes<'a> {
55 /// Returns an empty map.
56 ///
57 /// **Time:** O(1).
58 pub fn new() -> Self {
59 Self::default()
60 }
61
62 /// Sets the value of `name` and returns the previous one - Java's `Map.put`. A new name is appended;
63 /// a present one keeps its place.
64 ///
65 /// **Time:** O(len).
66 pub fn insert(
67 &mut self,
68 name: impl Into<Cow<'a, str>>,
69 value: impl Into<Cow<'a, str>>,
70 ) -> Option<Cow<'a, str>> {
71 let name = name.into();
72 let value = value.into();
73 match self.position(&name) {
74 Some(i) => Some(std::mem::replace(&mut self.entries[i].1, value)),
75 None => {
76 self.entries.push((name, value));
77 None
78 }
79 }
80 }
81
82 /// Returns the value of `name`, or `None` if it is absent.
83 ///
84 /// **Time:** O(len).
85 pub fn get(&self, name: &str) -> Option<&str> {
86 self.position(name).map(|i| &*self.entries[i].1)
87 }
88
89 /// Returns whether `name` is present.
90 ///
91 /// **Time:** O(len).
92 pub fn contains_key(&self, name: &str) -> bool {
93 self.position(name).is_some()
94 }
95
96 /// Removes `name` and returns its value, or `None` if it is absent; the other entries keep their
97 /// order.
98 ///
99 /// **Time:** O(len).
100 pub fn remove(&mut self, name: &str) -> Option<Cow<'a, str>> {
101 self.position(name).map(|i| self.entries.remove(i).1)
102 }
103
104 /// Returns the number of entries.
105 ///
106 /// **Time:** O(1).
107 pub fn len(&self) -> usize {
108 self.entries.len()
109 }
110
111 /// Returns whether the map has no entries.
112 ///
113 /// **Time:** O(1).
114 pub fn is_empty(&self) -> bool {
115 self.entries.is_empty()
116 }
117
118 /// Removes every entry.
119 ///
120 /// **Time:** O(len).
121 pub fn clear(&mut self) {
122 self.entries.clear();
123 }
124
125 /// Returns the entries as `(name, value)`, in the order they were put.
126 ///
127 /// **Time:** O(1) to create the iterator.
128 pub fn iter(&self) -> Iter<'_> {
129 Iter {
130 entries: self.entries.iter(),
131 }
132 }
133
134 fn position(&self, name: &str) -> Option<usize> {
135 self.entries.iter().position(|(key, _)| key == name)
136 }
137}
138
139impl<'b> IntoIterator for &'b Attributes<'_> {
140 type Item = (&'b str, &'b str);
141 type IntoIter = Iter<'b>;
142
143 fn into_iter(self) -> Iter<'b> {
144 self.iter()
145 }
146}
147
148/// The entries of an [`Attributes`] map, in the order they were put, as
149/// [`Attributes::iter`] returns them.
150#[derive(Debug, Clone)]
151pub struct Iter<'b> {
152 entries: slice::Iter<'b, (Cow<'b, str>, Cow<'b, str>)>,
153}
154
155impl<'b> Iterator for Iter<'b> {
156 type Item = (&'b str, &'b str);
157
158 fn next(&mut self) -> Option<(&'b str, &'b str)> {
159 self.entries.next().map(|(name, value)| (&**name, &**value))
160 }
161
162 fn size_hint(&self) -> (usize, Option<usize>) {
163 self.entries.size_hint()
164 }
165}
166
167impl ExactSizeIterator for Iter<'_> {}
168
169impl FusedIterator for Iter<'_> {}
170
171#[cfg(test)]
172mod tests {
173 use super::*;
174
175 fn entries<'b>(attributes: &'b Attributes<'_>) -> Vec<(&'b str, &'b str)> {
176 attributes.iter().collect()
177 }
178
179 #[test]
180 fn keeps_insertion_order() {
181 let mut attributes = Attributes::new();
182 assert!(attributes.is_empty());
183 assert_eq!(attributes.insert("label", "a"), None);
184 assert_eq!(attributes.insert("shape", "box"), None);
185 assert_eq!(attributes.insert("color", String::from("red")), None);
186 assert_eq!(attributes.len(), 3);
187 assert_eq!(
188 entries(&attributes),
189 [("label", "a"), ("shape", "box"), ("color", "red")]
190 );
191 assert_eq!(attributes.iter().len(), 3);
192 }
193
194 #[test]
195 fn insert_replaces_in_place_and_returns_the_previous_value() {
196 let mut attributes = Attributes::new();
197 attributes.insert("label", "a");
198 attributes.insert("shape", "box");
199 assert_eq!(attributes.insert("label", "b"), Some("a".into()));
200 assert_eq!(entries(&attributes), [("label", "b"), ("shape", "box")]);
201 assert_eq!(attributes.get("label"), Some("b"));
202 assert_eq!(attributes.get("Label"), None);
203 assert!(attributes.contains_key("shape") && !attributes.contains_key("color"));
204 }
205
206 #[test]
207 fn remove_keeps_the_order_of_the_rest_and_a_new_insert_goes_last() {
208 let mut attributes = Attributes::new();
209 for (name, value) in [("a", "1"), ("b", "2"), ("c", "3")] {
210 attributes.insert(name, value);
211 }
212 assert_eq!(attributes.remove("b"), Some("2".into()));
213 assert_eq!(attributes.remove("b"), None);
214 assert_eq!(entries(&attributes), [("a", "1"), ("c", "3")]);
215 attributes.insert("b", "4");
216 assert_eq!(entries(&attributes), [("a", "1"), ("c", "3"), ("b", "4")]);
217 let names: Vec<&str> = (&attributes).into_iter().map(|(name, _)| name).collect();
218 assert_eq!(names, ["a", "c", "b"]);
219 attributes.clear();
220 assert!(attributes.is_empty());
221 assert_eq!(attributes, Attributes::default());
222 }
223}