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
use alloc::{borrow::Cow, vec, vec::Vec};

use crate::types::{Tag, TagTree};

#[derive(Debug, Clone)]
pub struct Variants {
    fields: Vec<Tag>,
}

impl Variants {
    pub fn new(fields: Cow<'static, [TagTree]>) -> Self {
        let fields = (*fields)
            .iter()
            .flat_map(|tree| {
                fn flatten_tree(tree: &TagTree) -> Vec<Tag> {
                    match tree {
                        TagTree::Leaf(tag) => vec![*tag],
                        TagTree::Choice(tree) => tree.iter().flat_map(flatten_tree).collect(),
                    }
                }

                flatten_tree(tree)
            })
            .collect();

        Self { fields }
    }

    pub const fn empty() -> Self {
        Self { fields: Vec::new() }
    }

    pub fn from_static(fields: &'static [TagTree]) -> Self {
        Self::new(Cow::Borrowed(fields))
    }
}

impl From<Cow<'static, [TagTree]>> for Variants {
    fn from(fields: Cow<'static, [TagTree]>) -> Self {
        Self::new(fields)
    }
}

impl core::ops::Deref for Variants {
    type Target = [Tag];

    fn deref(&self) -> &Self::Target {
        &self.fields
    }
}