1
use std::{collections::BTreeMap, fmt::Debug};
2

            
3
use arc_bytes::serde::Bytes;
4
use serde::{Deserialize, Serialize};
5

            
6
use crate::{
7
    document::{DocumentId, Header, OwnedDocument},
8
    schema::view::{self, Key, SerializedView, View},
9
};
10

            
11
/// A document's entry in a View's mappings.
12
12
#[derive(PartialEq, Debug)]
13
pub struct Map<K: for<'a> Key<'a> = (), V = ()> {
14
    /// The header of the document that emitted this entry.
15
    pub source: Header,
16

            
17
    /// The key used to index the View.
18
    pub key: K,
19

            
20
    /// An associated value stored in the view.
21
    pub value: V,
22
}
23

            
24
impl<K: for<'a> Key<'a>, V> Map<K, V> {
25
    /// Serializes this map.
26
49435
    pub(crate) fn serialized<View: SerializedView<Value = V>>(
27
49435
        &self,
28
49435
    ) -> Result<Serialized, view::Error> {
29
49435
        Ok(Serialized {
30
49435
            source: self.source.clone(),
31
49435
            key: Bytes::from(
32
49435
                self.key
33
49435
                    .as_ord_bytes()
34
49435
                    .map_err(view::Error::key_serialization)?
35
49435
                    .to_vec(),
36
49435
            ),
37
49435
            value: Bytes::from(View::serialize(&self.value)?),
38
        })
39
49435
    }
40
}
41

            
42
impl<K: for<'a> Key<'a>, V> Map<K, V> {
43
    /// Creates a new Map entry for the document with id `source`.
44
106741
    pub fn new(source: Header, key: K, value: V) -> Self {
45
106741
        Self { source, key, value }
46
106741
    }
47
}
48

            
49
/// A collection of [`Map`]s.
50
5
#[derive(Debug, PartialEq)]
51
#[must_use]
52
pub enum Mappings<K: for<'a> Key<'a> = (), V = ()> {
53
    /// Zero or one mappings.
54
    Simple(Option<Map<K, V>>),
55
    /// More than one mapping.
56
    List(Vec<Map<K, V>>),
57
}
58

            
59
impl<K: for<'a> Key<'a>, V> Default for Mappings<K, V> {
60
    fn default() -> Self {
61
        Self::none()
62
    }
63
}
64

            
65
impl<K: for<'a> Key<'a>, V> Mappings<K, V> {
66
    /// Returns an empty collection of mappings.
67
806
    pub fn none() -> Self {
68
806
        Self::Simple(None)
69
806
    }
70

            
71
    /// Appends `mapping` to the end of this collection.
72
755
    pub fn push(&mut self, mapping: Map<K, V>) {
73
755
        match self {
74
748
            Self::Simple(existing_mapping) => {
75
748
                *self = if let Some(existing_mapping) = existing_mapping.take() {
76
748
                    Self::List(vec![existing_mapping, mapping])
77
                } else {
78
                    Self::Simple(Some(mapping))
79
                };
80
            }
81
7
            Self::List(vec) => vec.push(mapping),
82
        }
83
755
    }
84

            
85
    /// Appends `mappings` to the end of this collection and returns self.
86
1
    pub fn and(mut self, mappings: Self) -> Self {
87
1
        self.extend(mappings);
88
1
        self
89
1
    }
90
}
91

            
92
impl<K: for<'a> Key<'a>, V> Extend<Map<K, V>> for Mappings<K, V> {
93
755
    fn extend<T: IntoIterator<Item = Map<K, V>>>(&mut self, iter: T) {
94
755
        let iter = iter.into_iter();
95
1510
        for map in iter {
96
755
            self.push(map);
97
755
        }
98
755
    }
99
}
100

            
101
impl<K: for<'a> Key<'a>, V> FromIterator<Map<K, V>> for Mappings<K, V> {
102
    fn from_iter<T: IntoIterator<Item = Map<K, V>>>(iter: T) -> Self {
103
        let mut mappings = Self::none();
104
        mappings.extend(iter);
105
        mappings
106
    }
107
}
108

            
109
impl<K: for<'a> Key<'a>, V> FromIterator<Self> for Mappings<K, V> {
110
1606
    fn from_iter<T: IntoIterator<Item = Self>>(iter: T) -> Self {
111
1606
        let mut iter = iter.into_iter();
112
1606
        if let Some(mut collected) = iter.next() {
113
2081
            for mappings in iter {
114
754
                collected.extend(mappings);
115
754
            }
116
1327
            collected
117
        } else {
118
279
            Self::none()
119
        }
120
1606
    }
121
}
122

            
123
impl<K: for<'a> Key<'a>, V> IntoIterator for Mappings<K, V> {
124
    type Item = Map<K, V>;
125

            
126
    type IntoIter = MappingsIter<K, V>;
127

            
128
107536
    fn into_iter(self) -> Self::IntoIter {
129
107536
        match self {
130
106789
            Mappings::Simple(option) => MappingsIter::Inline(option),
131
747
            Mappings::List(list) => MappingsIter::Vec(list.into_iter()),
132
        }
133
107536
    }
134
}
135

            
136
/// An iterator over [`Mappings`].
137
pub enum MappingsIter<K: for<'a> Key<'a> = (), V = ()> {
138
    /// An iterator over a [`Mappings::Simple`] value.
139
    Inline(Option<Map<K, V>>),
140
    /// An iterator over a [`Mappings::List`] value.
141
    Vec(std::vec::IntoIter<Map<K, V>>),
142
}
143

            
144
impl<K: for<'a> Key<'a>, V> Iterator for MappingsIter<K, V> {
145
    type Item = Map<K, V>;
146

            
147
215020
    fn next(&mut self) -> Option<Self::Item> {
148
215020
        match self {
149
212772
            MappingsIter::Inline(opt) => opt.take(),
150
2248
            MappingsIter::Vec(iter) => iter.next(),
151
        }
152
215020
    }
153
}
154

            
155
/// A collection of mappings and the associated documents.
156
#[derive(Debug)]
157
pub struct MappedDocuments<D, V: View> {
158
    /// The collection of mappings.
159
    pub mappings: Vec<Map<V::Key, V::Value>>,
160
    /// All associated documents by ID.
161
    ///
162
    /// Documents can appear in a mapping query multiple times. As a result, they are stored separately to avoid duplication.
163
    pub documents: BTreeMap<DocumentId, D>,
164
}
165

            
166
impl<D, V: View> MappedDocuments<D, V> {
167
    /// The number of mappings contained in this collection.
168
    #[must_use]
169
47
    pub fn len(&self) -> usize {
170
47
        self.mappings.len()
171
47
    }
172

            
173
    /// Returns true if there are no mappings in this collection.
174
    #[must_use]
175
    pub fn is_empty(&self) -> bool {
176
        self.len() == 0
177
    }
178

            
179
    /// Returns the mapped document at`index`, or `None` if `index >=
180
    /// self.len()`.
181
    #[must_use]
182
31
    pub fn get(&self, index: usize) -> Option<MappedDocument<'_, D, V::Key, V::Value>> {
183
31
        if index < self.len() {
184
26
            let mapping = &self.mappings[index];
185
26
            let document = self
186
26
                .documents
187
26
                .get(&mapping.source.id)
188
26
                .expect("missing mapped document");
189
26
            Some(MappedDocument {
190
26
                key: &mapping.key,
191
26
                value: &mapping.value,
192
26
                document,
193
26
            })
194
        } else {
195
5
            None
196
        }
197
31
    }
198
}
199

            
200
/// An iterator of mapped documents.
201
pub struct MappedDocumentsIter<'a, D, V: View> {
202
    docs: &'a MappedDocuments<D, V>,
203
    index: usize,
204
}
205

            
206
impl<'a, D, V: View> IntoIterator for &'a MappedDocuments<D, V> {
207
    type Item = MappedDocument<'a, D, V::Key, V::Value>;
208

            
209
    type IntoIter = MappedDocumentsIter<'a, D, V>;
210

            
211
11
    fn into_iter(self) -> Self::IntoIter {
212
11
        MappedDocumentsIter {
213
11
            docs: self,
214
11
            index: 0,
215
11
        }
216
11
    }
217
}
218

            
219
impl<'a, D, V: View> Iterator for MappedDocumentsIter<'a, D, V> {
220
    type Item = MappedDocument<'a, D, V::Key, V::Value>;
221

            
222
23
    fn next(&mut self) -> Option<Self::Item> {
223
23
        let doc = self.docs.get(self.index);
224
23
        self.index = self.index.saturating_add(1);
225
23
        doc
226
23
    }
227
}
228

            
229
/// A mapped document returned from a view query.
230
pub struct MappedDocument<'a, D, K, V> {
231
    /// The key that this document mapped to.
232
    pub key: &'a K,
233
    /// The associated value of this key.
234
    pub value: &'a V,
235
    /// The source document of this mapping.
236
    pub document: &'a D,
237
}
238

            
239
/// Represents a document's entry in a View's mappings, serialized and ready to store.
240
605682
#[derive(Serialize, Deserialize, Debug, Clone)]
241
pub struct Serialized {
242
    /// The header of the document that emitted this entry.
243
    pub source: Header,
244

            
245
    /// The key used to index the View.Operation
246
    pub key: Bytes,
247

            
248
    /// An associated value stored in the view.Operation
249
    pub value: Bytes,
250
}
251

            
252
impl Serialized {
253
    /// Deserializes this map.
254
    pub fn deserialized<View: SerializedView>(
255
        &self,
256
    ) -> Result<Map<View::Key, View::Value>, view::Error> {
257
        Ok(Map::new(
258
            self.source.clone(),
259
            <View::Key as Key>::from_ord_bytes(&self.key)
260
                .map_err(view::Error::key_serialization)?,
261
            View::deserialize(&self.value)?,
262
        ))
263
    }
264
}
265

            
266
/// A serialized [`MappedDocument`](MappedDocument).
267
#[derive(Clone, Serialize, Deserialize, Debug)]
268
pub struct MappedSerializedDocuments {
269
    /// The serialized mapped value.
270
    pub mappings: Vec<Serialized>,
271
    /// The source document.
272
    pub documents: BTreeMap<DocumentId, OwnedDocument>,
273
}
274

            
275
impl MappedSerializedDocuments {
276
    /// Deserialize into a [`MappedDocument`](MappedDocument).
277
    pub fn deserialized<View: SerializedView>(
278
        self,
279
    ) -> Result<MappedDocuments<OwnedDocument, View>, crate::Error> {
280
        let mappings = self
281
            .mappings
282
            .iter()
283
            .map(Serialized::deserialized::<View>)
284
            .collect::<Result<Vec<_>, _>>()?;
285

            
286
        Ok(MappedDocuments {
287
            mappings,
288
            documents: self.documents,
289
        })
290
    }
291
}
292

            
293
/// A key value pair
294
24
#[derive(Clone, PartialEq, Debug)]
295
pub struct MappedValue<K: for<'a> Key<'a>, V> {
296
    /// The key responsible for generating the value
297
    pub key: K,
298

            
299
    /// The value generated by the `View`
300
    pub value: V,
301
}
302

            
303
impl<K: for<'a> Key<'a>, V> MappedValue<K, V> {
304
    /// Returns a new instance with the key/value pair.
305
108532
    pub fn new(key: K, value: V) -> Self {
306
108532
        Self { key, value }
307
108532
    }
308
}
309

            
310
/// A mapped value in a [`View`].
311
pub type ViewMappedValue<V> = MappedValue<<V as View>::Key, <V as View>::Value>;
312

            
313
/// A serialized [`MappedValue`].
314
2375
#[derive(Clone, Serialize, Deserialize, Debug)]
315
pub struct MappedSerializedValue {
316
    /// The serialized key.
317
    pub key: Bytes,
318
    /// The serialized value.
319
    pub value: Bytes,
320
}