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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
use alloc::vec::Vec;
use arbitrary::Arbitrary;
use canonical::{Canon, CanonError, EncodeToVec, Id, Source};
use canonical_derive::Canon;
use crate::link::Link;
use crate::{Annotation, Compound};
const TAG_EMPTY: u8 = 0;
const TAG_LEAF: u8 = 1;
const TAG_LINK: u8 = 2;
#[derive(Clone, Canon, Debug, PartialEq, Arbitrary)]
pub struct GenericAnnotation(Vec<u8>);
#[derive(Clone, Canon, Debug, PartialEq, Arbitrary)]
pub struct GenericLeaf(Vec<u8>);
impl GenericLeaf {
pub(crate) fn new<C: Canon>(c: &C) -> Self {
GenericLeaf(c.encode_to_vec())
}
pub fn cast<T: Canon>(&self) -> Result<T, CanonError> {
T::decode(&mut Source::new(&self.0))
}
}
impl GenericAnnotation {
pub(crate) fn new<A: Canon>(a: &A) -> Self {
GenericAnnotation(a.encode_to_vec())
}
pub fn cast<A: Canon>(&self) -> Result<A, CanonError> {
A::decode(&mut Source::new(&self.0))
}
}
#[derive(Clone, Debug, PartialEq, Arbitrary)]
pub enum GenericChild {
Empty,
Leaf(GenericLeaf),
Link(Id, GenericAnnotation),
}
impl Canon for GenericChild {
fn encode(&self, sink: &mut canonical::Sink) {
match self {
Self::Empty => TAG_EMPTY.encode(sink),
Self::Leaf(leaf) => {
TAG_LEAF.encode(sink);
leaf.encode(sink)
}
Self::Link(id, annotation) => {
TAG_LINK.encode(sink);
id.encode(sink);
annotation.encode(sink);
}
}
}
fn decode(source: &mut canonical::Source) -> Result<Self, CanonError> {
match u8::decode(source)? {
TAG_EMPTY => Ok(GenericChild::Empty),
TAG_LEAF => Ok(GenericChild::Leaf(GenericLeaf::decode(source)?)),
TAG_LINK => {
let id = Id::decode(source)?;
let anno = GenericAnnotation::decode(source)?;
Ok(GenericChild::Link(id, anno))
}
_ => Err(CanonError::InvalidEncoding),
}
}
fn encoded_len(&self) -> usize {
const TAG_LEN: usize = 1;
match self {
Self::Empty => TAG_LEN,
Self::Leaf(leaf) => TAG_LEN + leaf.encoded_len(),
Self::Link(id, anno) => {
TAG_LEN + id.encoded_len() + anno.encoded_len()
}
}
}
}
#[derive(Default, Clone, Canon, Debug, PartialEq, Arbitrary)]
pub struct GenericTree(Vec<GenericChild>);
impl GenericTree {
pub(crate) fn new() -> Self {
GenericTree(vec![])
}
pub(crate) fn push_empty(&mut self) {
self.0.push(GenericChild::Empty)
}
pub(crate) fn push_leaf<L: Canon>(&mut self, leaf: &L) {
self.0.push(GenericChild::Leaf(GenericLeaf::new(leaf)))
}
pub(crate) fn push_link<C, A>(&mut self, link: &Link<C, A>)
where
C: Compound<A>,
C::Leaf: Canon,
A: Annotation<C::Leaf>,
{
let id = link.id();
let anno = GenericAnnotation::new(&*link.annotation());
self.0.push(GenericChild::Link(id, anno));
}
pub fn children(&self) -> &[GenericChild] {
&self.0
}
}