nstack/annotation/
cardinality.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4//
5// Copyright (c) DUSK NETWORK. All rights reserved.
6
7use crate::NStack;
8
9use core::ops::Deref;
10
11use ranno::Annotation;
12
13/// The cardinality of the NStack.
14#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
15pub struct Cardinality(u64);
16
17impl From<u64> for Cardinality {
18    fn from(c: u64) -> Self {
19        Self(c)
20    }
21}
22
23impl Deref for Cardinality {
24    type Target = u64;
25
26    fn deref(&self) -> &Self::Target {
27        &self.0
28    }
29}
30
31impl PartialEq<u64> for Cardinality {
32    fn eq(&self, other: &u64) -> bool {
33        self.0.eq(other)
34    }
35}
36
37impl<T> Annotation<NStack<T, Cardinality>> for Cardinality {
38    fn from_child(stack: &NStack<T, Cardinality>) -> Self {
39        let mut cardinality = 0;
40
41        match stack {
42            NStack::Leaf(leaf) => {
43                for _ in leaf.iter().flatten() {
44                    cardinality += 1;
45                }
46            }
47            NStack::Node(node) => {
48                for a in node.iter().flatten() {
49                    let anno = a.anno();
50                    let c = &*anno;
51                    cardinality += c.0;
52                }
53            }
54        }
55
56        cardinality.into()
57    }
58}