1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
use std::{convert::TryFrom, iter::FromIterator};
use crate::Polynomial;

#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Default, Debug)]
pub struct Node(String);

impl From<String> for Node {
    fn from(id: String) -> Self {
        Node(id)
    }
}

impl AsRef<str> for Node {
    fn as_ref(&self) -> &str {
        self.0.as_str()
    }
}

pub trait ToNode {
    fn to_node(&self) -> Node;
}

impl<S: AsRef<str>> ToNode for S {
    fn to_node(&self) -> Node {
        self.as_ref().to_string().into()
    }
}

/// An alphabetically ordered and deduplicated list of [`Node`]s.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Default, Debug)]
pub struct NodeList {
    pub(crate) nodes: Vec<Node>,
}

impl NodeList {
    pub fn with_more(mut self, nodes: Vec<Node>) -> Self {
        self.nodes.extend(nodes.into_iter());
        self.nodes.sort();
        let len = self.nodes.partition_dedup().0.len();
        self.nodes.truncate(len);
        self
    }

    pub(crate) fn add_assign(&mut self, other: &mut Self) {
        self.nodes.append(&mut other.nodes);
        self.nodes.sort();
        let len = self.nodes.partition_dedup().0.len();
        self.nodes.truncate(len);
    }
}

impl From<Node> for NodeList {
    fn from(node: Node) -> Self {
        NodeList { nodes: vec![node] }
    }
}

impl<T: ToNode> From<Vec<T>> for NodeList {
    fn from(nodes: Vec<T>) -> Self {
        let mut nodes: Vec<Node> = nodes.into_iter().map(|n| n.to_node()).collect();
        nodes.sort();
        let len = nodes.partition_dedup().0.len();
        nodes.truncate(len);
        NodeList { nodes }
    }
}

impl TryFrom<Polynomial> for NodeList {
    type Error = &'static str;

    fn try_from(poly: Polynomial) -> Result<Self, Self::Error> {
        if poly.is_flat {
            let mut monomials = poly.monomials.into_iter();

            if let Some(monomial) = monomials.next() {
                let nodes = Vec::from_iter(monomial.into_iter());
                // no need for sorting, unless `monomial` breaks the
                // invariants: 'is-ordered' and 'no-duplicates'...

                if monomials.next().is_none() {
                    Ok(NodeList { nodes })
                } else {
                    Err("Not a node list")
                }
            } else {
                Ok(Default::default())
            }
        } else {
            Err("Not a node list")
        }
    }
}