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
93
94
95
96
use std::borrow::{Borrow, Cow};
use std::io;

use bytehash::ByteHash;

pub use cardinality::{Cardinality, Count, Counter, GetNth, Nth};
pub use max_key::{MaxKey, MaxKeyType};

use crate::{Content, Sink, Source};

mod annotation_macro;
mod cardinality;

mod max_key;

/// Helper group-trait for annotations
pub trait Annotation<L, H>:
    'static + Combine<Self> + for<'l> From<&'l L> + Content<H>
where
    H: ByteHash,
{
}

impl<A, L, H> Annotation<L, H> for A
where
    A: 'static + Combine<Self> + for<'any> From<&'any L> + Content<H>,
    H: ByteHash,
{
}

/// Wrapper trait for hiding generics when working on select functions
pub trait ErasedAnnotation<A: Clone>: Clone {
    /// Returns the annotation of &self, if any.
    fn annotation(&self) -> Option<Cow<A>>;
}

/// Defines the associative operation for the annotation type
pub trait Associative {
    /// Perform the associative operation on self
    fn op(&mut self, b: &Self);
}

/// Defines how annotation types are combined. Prefer using `Associative` when possible.
pub trait Combine<A>: Sized + Clone {
    /// Combines n annotation elements into one
    fn combine<E>(elements: &[E]) -> Option<Self>
    where
        A: Borrow<Self> + Clone,
        E: ErasedAnnotation<A>;
}

impl<A, T> Combine<A> for T
where
    Self: Associative + Clone,
{
    fn combine<E>(elements: &[E]) -> Option<T>
    where
        A: Borrow<Self> + Clone,
        E: ErasedAnnotation<A>,
    {
        let mut iter = elements.iter().filter_map(ErasedAnnotation::annotation);

        iter.next().map(|first| {
            let t: &T = (*first).borrow().borrow();
            let mut s: T = t.clone();
            for next in iter {
                let a: &A = next.borrow();
                s.op(a.borrow())
            }
            s
        })
    }
}

/// Empty annotation
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct VoidAnnotation;

impl<T> From<&T> for VoidAnnotation {
    fn from(_: &T) -> Self {
        VoidAnnotation
    }
}

impl Associative for VoidAnnotation {
    fn op(&mut self, _: &Self) {}
}

impl<H: ByteHash> Content<H> for VoidAnnotation {
    fn persist(&mut self, _: &mut Sink<H>) -> io::Result<()> {
        Ok(())
    }
    fn restore(_: &mut Source<H>) -> io::Result<Self> {
        Ok(VoidAnnotation)
    }
}