|
3 | 3 | use pyo3::prelude::*; |
4 | 4 | use pyo3::wrap_pyfunction; |
5 | 5 | use pyo3::types::{PyDict, PyInt, PyList, PyString}; |
| 6 | +use std::collections::HashMap; |
| 7 | +use pyo3::prelude::*; |
| 8 | +use std::hash::Hash; |
| 9 | + |
| 10 | + |
| 11 | +use lasso::{Rodeo, Spur}; |
| 12 | +use std::num::NonZero; |
| 13 | +use std::ops; |
| 14 | + |
| 15 | +mod serialisation; |
| 16 | +mod python_interface; |
| 17 | +mod formatters; |
| 18 | + |
| 19 | +// This data structure uses the Newtype Index Pattern |
| 20 | +// See https://matklad.github.io/2018/06/04/newtype-index-pattern.html |
| 21 | +// See also https://github.com/nrc/r4cppp/blob/master/graphs/README.md#rcrefcellnode for a discussion of other approaches to trees and graphs in rust. |
| 22 | +// https://smallcultfollowing.com/babysteps/blog/2015/04/06/modeling-graphs-in-rust-using-vector-indices/ |
| 23 | + |
| 24 | +// Index types use struct Id(NonZero<usize>) |
| 25 | +// This reserves 0 as a special value which allows Option<Id(NonZero<usize>)> to be the same size as usize. |
| 26 | + |
| 27 | +#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash)] |
| 28 | +pub(crate) struct NodeId(NonZero<usize>); |
| 29 | + |
| 30 | +// Allow node indices to index directly into Qubes: |
| 31 | +impl ops::Index<NodeId> for Qube { |
| 32 | + type Output = Node; |
| 33 | + |
| 34 | + fn index(&self, index: NodeId) -> &Node { |
| 35 | + &self.nodes[index.0.get() - 1] |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +impl ops::IndexMut<NodeId> for Qube { |
| 40 | + fn index_mut(&mut self, index: NodeId) -> &mut Node { |
| 41 | + &mut self.nodes[index.0.get() - 1] |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +impl ops::Index<StringId> for Qube { |
| 46 | + type Output = str; |
| 47 | + |
| 48 | + fn index(&self, index: StringId) -> &str { |
| 49 | + &self.strings[index] |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +impl NodeId { |
| 54 | + pub fn new_infallible(value: NonZero<usize>) -> NodeId { |
| 55 | + NodeId(value) |
| 56 | + } |
| 57 | + pub fn new(value: usize) -> Option<NodeId> { |
| 58 | + NonZero::new(value).map(NodeId) |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash)] |
| 63 | +struct StringId(lasso::Spur); |
| 64 | + |
| 65 | +impl ops::Index<StringId> for lasso::Rodeo { |
| 66 | + type Output = str; |
| 67 | + |
| 68 | + fn index(&self, index: StringId) -> &str { |
| 69 | + &self[index.0] |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +#[derive(Debug)] |
| 74 | +pub(crate) struct Node { |
| 75 | + pub key: StringId, |
| 76 | + pub metadata: HashMap<StringId, Vec<String>>, |
| 77 | + pub parent: Option<NodeId>, // If not present, it's the root node |
| 78 | + pub values: Vec<StringId>, |
| 79 | + pub children: HashMap<StringId, Vec<NodeId>>, |
| 80 | +} |
| 81 | + |
| 82 | +impl Node { |
| 83 | + fn new_root(q: &mut Qube) -> Node { |
| 84 | + Node { |
| 85 | + key: q.get_or_intern("root"), |
| 86 | + metadata: HashMap::new(), |
| 87 | + parent: None, |
| 88 | + values: vec![], |
| 89 | + children: HashMap::new(), |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + fn children(&self) -> impl Iterator<Item = &NodeId> { |
| 94 | + self.children.values().flatten() |
| 95 | + } |
| 96 | + |
| 97 | + fn is_root(&self) -> bool { |
| 98 | + self.parent.is_none() |
| 99 | + } |
| 100 | + |
| 101 | + /// Because children are stored grouped by key |
| 102 | + /// determining the number of children quickly takes a little effort. |
| 103 | + /// This is a fast method for the special case of checking if a Node has exactly one child. |
| 104 | + /// Returns Ok(NodeId) if there is one child else None |
| 105 | + fn has_exactly_one_child(&self) -> Option<NodeId> { |
| 106 | + if self.children.len() != 1 {return None} |
| 107 | + let Some(value_group) = self.children.values().next() else {return None}; |
| 108 | + let [node_id] = &value_group.as_slice() else {return None}; |
| 109 | + Some(*node_id) |
| 110 | + } |
| 111 | + |
| 112 | + fn n_children(&self) -> usize { |
| 113 | + self.children |
| 114 | + .values() |
| 115 | + .map(|v| v.len()) |
| 116 | + .sum() |
| 117 | + } |
| 118 | +} |
| 119 | + |
| 120 | +#[derive(Debug)] |
| 121 | +#[pyclass(subclass, dict)] |
| 122 | +pub struct Qube { |
| 123 | + pub root: NodeId, |
| 124 | + nodes: Vec<Node>, |
| 125 | + strings: Rodeo, |
| 126 | +} |
| 127 | + |
| 128 | +impl Qube { |
| 129 | + pub fn new() -> Self { |
| 130 | + let mut q = Self { |
| 131 | + root: NodeId::new(1).unwrap(), |
| 132 | + nodes: Vec::new(), |
| 133 | + strings: Rodeo::default(), |
| 134 | + }; |
| 135 | + |
| 136 | + let root = Node::new_root(&mut q); |
| 137 | + q.nodes.push(root); |
| 138 | + q |
| 139 | + } |
| 140 | + |
| 141 | + fn get_or_intern(&mut self, val: &str) -> StringId { |
| 142 | + StringId(self.strings.get_or_intern(val)) |
| 143 | + } |
| 144 | + |
| 145 | + pub fn add_node(&mut self, parent: NodeId, key: &str, values: &[&str]) -> NodeId { |
| 146 | + let key_id = self.get_or_intern(key); |
| 147 | + let values = values.iter().map(|val| self.get_or_intern(val)).collect(); |
6 | 148 |
|
7 | | -mod qube; |
8 | | -mod json; |
| 149 | + // Create the node object |
| 150 | + let node = Node { |
| 151 | + key: key_id, |
| 152 | + metadata: HashMap::new(), |
| 153 | + values: values, |
| 154 | + parent: Some(parent), |
| 155 | + children: HashMap::new(), |
| 156 | + }; |
| 157 | + |
| 158 | + // Insert it into the Qube arena and determine its id |
| 159 | + self.nodes.push(node); |
| 160 | + let node_id = NodeId::new(self.nodes.len()).unwrap(); |
| 161 | + |
| 162 | + // Add a reference to this node's id to the parents list of children. |
| 163 | + let parent_node = &mut self[parent]; |
| 164 | + let key_group = parent_node.children.entry(key_id).or_insert(Vec::new()); |
| 165 | + key_group.push(node_id); |
| 166 | + |
| 167 | + node_id |
| 168 | + } |
| 169 | + |
| 170 | + fn print(&self, node_id: Option<NodeId>) -> String { |
| 171 | + let node_id: NodeId = node_id.unwrap_or(self.root); |
| 172 | + let node = &self[node_id]; |
| 173 | + node.summary(&self) |
| 174 | + } |
| 175 | +} |
9 | 176 |
|
10 | 177 |
|
11 | 178 | #[pymodule] |
12 | 179 | fn rust(m: &Bound<'_, PyModule>) -> PyResult<()> { |
13 | | - m.add_class::<qube::Qube>()?; |
14 | | - m.add_function(wrap_pyfunction!(json::parse_qube, m)?); |
| 180 | + m.add_class::<Qube>()?; |
15 | 181 | Ok(()) |
16 | 182 | } |
0 commit comments