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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
use ahash::HashMap;
use std::borrow::Cow;

use crate::error::Error;
use crate::name::NameId;
use crate::namespace::NamespaceId;
use crate::prefix::PrefixId;
use crate::xmlvalue::Prefixes;
use crate::xotdata::Xot;

type ToPrefixes = HashMap<NamespaceId, Vec<PrefixId>>;

fn inverse_prefixes(prefixes: &Prefixes) -> ToPrefixes {
    let mut to_prefixes = HashMap::default();
    for (prefix, namespace) in prefixes.iter() {
        to_prefixes
            .entry(*namespace)
            .or_insert_with(Vec::new)
            .push(*prefix);
    }
    to_prefixes
}

pub(crate) struct FullnameSerializer<'a> {
    xot: &'a Xot,
    prefix_stack: Vec<(Prefixes, ToPrefixes)>,
}

enum NameInfo<'a> {
    // the name is in the default namespace
    NoNamespace {
        name: &'a str,
    },
    // Prefixes are known for the namespace
    Prefixes {
        name: &'a str,
        namespace_id: NamespaceId,
        prefixes: &'a [PrefixId],
    },
    // the name is in a namespace, but the prefix is not known
    MissingPrefix {
        namespace_id: NamespaceId,
    },
}

pub(crate) enum Fullname<'a> {
    Name(Cow<'a, str>),
    MissingPrefix(NamespaceId),
}

impl<'a> FullnameSerializer<'a> {
    pub(crate) fn new(xot: &'a Xot) -> Self {
        Self::with_prefixes(Prefixes::new(), xot)
    }

    pub(crate) fn with_prefixes(prefixes: Prefixes, xot: &'a Xot) -> Self {
        let to_prefixes = inverse_prefixes(&prefixes);
        let prefix_stack = vec![(prefixes, to_prefixes)];
        Self { xot, prefix_stack }
    }

    pub(crate) fn push(&mut self, prefixes: &Prefixes) {
        if prefixes.is_empty() {
            return;
        }
        let mut entry = self.top_prefixes().clone();
        // add in the new declarations. This may shadow existing prefixes
        entry.extend(prefixes);
        // construct the inverse from this
        let to_prefixes = inverse_prefixes(&entry);
        self.prefix_stack.push((entry, to_prefixes));
    }

    pub(crate) fn pop(&mut self, prefixes: &Prefixes) {
        if prefixes.is_empty() {
            return;
        }
        self.prefix_stack.pop();
    }

    #[inline]
    pub(crate) fn top(&self) -> &(Prefixes, ToPrefixes) {
        &self.prefix_stack[self.prefix_stack.len() - 1]
    }

    #[inline]
    pub(crate) fn top_prefixes(&self) -> &Prefixes {
        &self.top().0
    }

    #[inline]
    pub(crate) fn top_to_prefixes(&self) -> &ToPrefixes {
        &self.top().1
    }

    fn name_info(&self, name_id: NameId) -> NameInfo {
        let name = self.xot.name_lookup.get_value(name_id);
        if name.namespace_id == self.xot.no_namespace_id {
            return NameInfo::NoNamespace { name: &name.name };
        } else if name.namespace_id == self.xot.xml_namespace_id {
            return NameInfo::Prefixes {
                name: name.name.as_ref(),
                namespace_id: name.namespace_id,
                prefixes: &self.xot.xml_prefixes,
            };
        }
        // there should always be at least 1 entry in the stack
        let prefix_ids = self.top_to_prefixes().get(&name.namespace_id);
        if let Some(prefix_ids) = prefix_ids {
            NameInfo::Prefixes {
                name: &name.name,
                namespace_id: name.namespace_id,
                prefixes: prefix_ids,
            }
        } else {
            NameInfo::MissingPrefix {
                namespace_id: name.namespace_id,
            }
        }
    }

    pub(crate) fn fullname(&'a self, name_id: NameId) -> Fullname<'a> {
        match self.name_info(name_id) {
            NameInfo::NoNamespace { name } => Fullname::Name(name.into()),
            NameInfo::Prefixes { name, prefixes, .. } => {
                // if any of the prefixes is the empty prefix, prefer that
                if prefixes.iter().any(|p| *p == self.xot.empty_prefix_id) {
                    Fullname::Name(name.into())
                } else {
                    // otherwise, use the first prefix
                    let prefix = self.xot.prefix_lookup.get_value(prefixes[0]);
                    Fullname::Name(format!("{}:{}", prefix, name).into())
                }
            }
            NameInfo::MissingPrefix { namespace_id } => Fullname::MissingPrefix(namespace_id),
        }
    }

    pub(crate) fn fullname_attr(&'a self, name_id: NameId) -> Fullname<'a> {
        match self.name_info(name_id) {
            NameInfo::NoNamespace { name } => Fullname::Name(name.into()),
            NameInfo::Prefixes {
                name,
                namespace_id,
                prefixes,
            } => {
                // first filter out the empty prefix, as we can't use that for attributes,
                // because attributes without a prefix have no namespace.
                // use the first non-empty prefix, if it exists
                let prefix = prefixes.iter().find(|p| **p != self.xot.empty_prefix_id);
                if let Some(prefix_id) = prefix {
                    let prefix = self.xot.prefix_lookup.get_value(*prefix_id);
                    Fullname::Name(format!("{}:{}", prefix, name).into())
                } else {
                    // otherwise, we can't express the namespace id for the empty prefix
                    Fullname::MissingPrefix(namespace_id)
                }
            }
            NameInfo::MissingPrefix { namespace_id } => Fullname::MissingPrefix(namespace_id),
        }
    }

    pub(crate) fn fullname_or_err(&'a self, name_id: NameId) -> Result<Cow<'a, str>, Error> {
        match self.fullname(name_id) {
            Fullname::Name(name) => Ok(name),
            Fullname::MissingPrefix(namespace_id) => Err(Error::MissingPrefix(namespace_id)),
        }
    }

    pub(crate) fn fullname_attr_or_err(&'a self, name_id: NameId) -> Result<Cow<'a, str>, Error> {
        match self.fullname_attr(name_id) {
            Fullname::Name(name) => Ok(name),
            Fullname::MissingPrefix(namespace_id) => Err(Error::MissingPrefix(namespace_id)),
        }
    }

    pub(crate) fn is_namespace_known(&self, namespace_id: NamespaceId) -> bool {
        self.top_to_prefixes().contains_key(&namespace_id)
    }
}