1
use std::collections::BTreeMap;
2
use std::fmt::Debug;
3

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

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

            
11
/// A document's entry in a View's mappings.
12
6
#[derive(Eq, PartialEq, Debug)]
13
pub struct Map<K = (), 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, V> Map<K, V> {
25
    /// Serializes this map.
26
564573
    pub(crate) fn serialized<'a, View>(&self) -> Result<Serialized, view::Error>
27
564573
    where
28
564573
        K: Key<'a>,
29
564573
        View: SerializedView<Value = V>,
30
564573
    {
31
564573
        Ok(Serialized {
32
564573
            source: self.source.clone(),
33
564573
            key: Bytes::from(
34
564573
                self.key
35
564573
                    .as_ord_bytes()
36
564573
                    .map_err(view::Error::key_serialization)?
37
564573
                    .to_vec(),
38
564573
            ),
39
564573
            value: Bytes::from(View::serialize(&self.value)?),
40
        })
41
564573
    }
42
}
43

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

            
51
/// A document's entry in a View's mappings.
52
6
#[derive(Eq, PartialEq, Debug)]
53
pub struct CollectionMap<PrimaryKey, K = (), V = ()> {
54
    /// The header of the document that emitted this entry.
55
    pub source: CollectionHeader<PrimaryKey>,
56

            
57
    /// The key used to index the View.
58
    pub key: K,
59

            
60
    /// An associated value stored in the view.
61
    pub value: V,
62
}
63

            
64
/// This type is the result of `query()`. It is a list of mappings, which
65
/// contains:
66
///
67
/// - The key emitted during the map function.
68
/// - The value emitted during the map function.
69
/// - The source document header that the mappings originated from.
70
pub type ViewMappings<V> = Vec<
71
    CollectionMap<
72
        <<V as View>::Collection as Collection>::PrimaryKey,
73
        <V as View>::Key,
74
        <V as View>::Value,
75
    >,
76
>;
77

            
78
/// A collection of [`Map`]s.
79
5
#[derive(Debug, Eq, PartialEq)]
80
#[must_use]
81
pub enum Mappings<K = (), V = ()> {
82
    /// Zero or one mappings.
83
    Simple(Option<Map<K, V>>),
84
    /// More than one mapping.
85
    List(Vec<Map<K, V>>),
86
}
87

            
88
impl<K, V> Default for Mappings<K, V> {
89
    fn default() -> Self {
90
        Self::none()
91
    }
92
}
93

            
94
impl<K, V> Mappings<K, V> {
95
    /// Returns an empty collection of mappings.
96
1080
    pub const fn none() -> Self {
97
1080
        Self::Simple(None)
98
1080
    }
99

            
100
    /// Appends `mapping` to the end of this collection.
101
971
    pub fn push(&mut self, mapping: Map<K, V>) {
102
971
        match self {
103
964
            Self::Simple(existing_mapping) => {
104
964
                *self = if let Some(existing_mapping) = existing_mapping.take() {
105
964
                    Self::List(vec![existing_mapping, mapping])
106
                } else {
107
                    Self::Simple(Some(mapping))
108
                };
109
            }
110
7
            Self::List(vec) => vec.push(mapping),
111
        }
112
971
    }
113

            
114
    /// Appends `mappings` to the end of this collection and returns self.
115
1
    pub fn and(mut self, mappings: Self) -> Self {
116
1
        self.extend(mappings);
117
1
        self
118
1
    }
119

            
120
    /// Returns an iterator for these mappings.
121
636261
    pub fn iter(&self) -> MappingsIter<'_, K, V> {
122
636261
        self.into_iter()
123
636261
    }
124

            
125
    /// Returns the number of mappings contained.
126
    pub fn len(&self) -> usize {
127
        match self {
128
            Mappings::Simple(None) => 0,
129
            Mappings::Simple(Some(_)) => 1,
130
            Mappings::List(v) => v.len(),
131
        }
132
    }
133

            
134
    /// Returns true if there are no mappings in this collection.
135
    pub fn is_empty(&self) -> bool {
136
        self.len() == 0
137
    }
138
}
139

            
140
impl<K, V> Extend<Map<K, V>> for Mappings<K, V> {
141
971
    fn extend<T: IntoIterator<Item = Map<K, V>>>(&mut self, iter: T) {
142
971
        let iter = iter.into_iter();
143
1942
        for map in iter {
144
971
            self.push(map);
145
971
        }
146
971
    }
147
}
148

            
149
impl<K, V> FromIterator<Map<K, V>> for Mappings<K, V> {
150
    fn from_iter<T: IntoIterator<Item = Map<K, V>>>(iter: T) -> Self {
151
        let mut mappings = Self::none();
152
        mappings.extend(iter);
153
        mappings
154
    }
155
}
156

            
157
impl<K, V> FromIterator<Self> for Mappings<K, V> {
158
2005
    fn from_iter<T: IntoIterator<Item = Self>>(iter: T) -> Self {
159
2005
        let mut iter = iter.into_iter();
160
2005
        if let Some(mut collected) = iter.next() {
161
2615
            for mappings in iter {
162
970
                collected.extend(mappings);
163
970
            }
164
1645
            collected
165
        } else {
166
360
            Self::none()
167
        }
168
2005
    }
169
}
170

            
171
impl<K, V> IntoIterator for Mappings<K, V> {
172
    type IntoIter = MappingsIntoIter<K, V>;
173
    type Item = Map<K, V>;
174

            
175
971
    fn into_iter(self) -> Self::IntoIter {
176
971
        match self {
177
971
            Mappings::Simple(option) => MappingsIntoIter::Inline(option),
178
            Mappings::List(list) => MappingsIntoIter::Vec(list.into_iter()),
179
        }
180
971
    }
181
}
182

            
183
impl<'a, K, V> IntoIterator for &'a Mappings<K, V> {
184
    type IntoIter = MappingsIter<'a, K, V>;
185
    type Item = &'a Map<K, V>;
186

            
187
636261
    fn into_iter(self) -> Self::IntoIter {
188
636261
        match self {
189
635298
            Mappings::Simple(option) => MappingsIter::Inline(option.iter()),
190
963
            Mappings::List(list) => MappingsIter::Vec(list.iter()),
191
        }
192
636261
    }
193
}
194

            
195
/// An iterator over [`Mappings`] that returns owned [`Map`] entries.
196
pub enum MappingsIntoIter<K = (), V = ()> {
197
    /// An iterator over a [`Mappings::Simple`] value.
198
    Inline(Option<Map<K, V>>),
199
    /// An iterator over a [`Mappings::List`] value.
200
    Vec(std::vec::IntoIter<Map<K, V>>),
201
}
202

            
203
impl<K, V> Iterator for MappingsIntoIter<K, V> {
204
    type Item = Map<K, V>;
205

            
206
1942
    fn next(&mut self) -> Option<Self::Item> {
207
1942
        match self {
208
1942
            MappingsIntoIter::Inline(opt) => opt.take(),
209
            MappingsIntoIter::Vec(iter) => iter.next(),
210
        }
211
1942
    }
212
}
213

            
214
/// An iterator over [`Mappings`] that returns [`Map`] entry references.
215
pub enum MappingsIter<'a, K = (), V = ()> {
216
    /// An iterator over a [`Mappings::Simple`] value.
217
    Inline(std::option::Iter<'a, Map<K, V>>),
218
    /// An iterator over a [`Mappings::List`] value.
219
    Vec(std::slice::Iter<'a, Map<K, V>>),
220
}
221

            
222
impl<'a, K, V> Iterator for MappingsIter<'a, K, V> {
223
    type Item = &'a Map<K, V>;
224

            
225
1272412
    fn next(&mut self) -> Option<Self::Item> {
226
1272412
        match self {
227
1269516
            MappingsIter::Inline(i) => i.next(),
228
2896
            MappingsIter::Vec(i) => i.next(),
229
        }
230
1272412
    }
231
}
232

            
233
/// A collection of mappings and the associated documents.
234
pub struct MappedDocuments<D, V: View> {
235
    /// The collection of mappings.
236
    pub mappings: ViewMappings<V>,
237
    /// All associated documents by ID.
238
    ///
239
    /// Documents can appear in a mapping query multiple times. As a result, they are stored separately to avoid duplication.
240
    pub documents: BTreeMap<<V::Collection as Collection>::PrimaryKey, D>,
241
}
242

            
243
impl<D, V: View> MappedDocuments<D, V> {
244
    /// The number of mappings contained in this collection.
245
    #[must_use]
246
47
    pub fn len(&self) -> usize {
247
47
        self.mappings.len()
248
47
    }
249

            
250
    /// Returns true if there are no mappings in this collection.
251
    #[must_use]
252
    pub fn is_empty(&self) -> bool {
253
        self.len() == 0
254
    }
255

            
256
    /// Returns the mapped document at`index`, or `None` if `index >=
257
    /// self.len()`.
258
    #[must_use]
259
    #[allow(clippy::missing_panics_doc)]
260
31
    pub fn get(&self, index: usize) -> Option<MappedDocument<'_, D, V::Key, V::Value>> {
261
31
        if index < self.len() {
262
26
            let mapping = &self.mappings[index];
263
26
            let document = self
264
26
                .documents
265
26
                .get(&mapping.source.id)
266
26
                .expect("missing mapped document");
267
26
            Some(MappedDocument {
268
26
                key: &mapping.key,
269
26
                value: &mapping.value,
270
26
                document,
271
26
            })
272
        } else {
273
5
            None
274
        }
275
31
    }
276

            
277
    /// Returns an iterator over the contained mapped documents.
278
    #[must_use]
279
11
    pub const fn iter(&self) -> MappedDocumentsIter<'_, D, V> {
280
11
        MappedDocumentsIter {
281
11
            docs: self,
282
11
            index: 0,
283
11
        }
284
11
    }
285
}
286

            
287
impl<D, V: View> Debug for MappedDocuments<D, V>
288
where
289
    V::Key: Debug,
290
    V::Value: Debug,
291
    D: Debug,
292
    <V::Collection as Collection>::PrimaryKey: Debug,
293
{
294
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
295
        f.debug_struct("MappedDocuments")
296
            .field("mappings", &self.mappings)
297
            .field("documents", &self.documents)
298
            .finish()
299
    }
300
}
301

            
302
/// An iterator of mapped documents.
303
pub struct MappedDocumentsIter<'a, D, V: View> {
304
    docs: &'a MappedDocuments<D, V>,
305
    index: usize,
306
}
307

            
308
impl<'a, D, V: View> IntoIterator for &'a MappedDocuments<D, V> {
309
    type IntoIter = MappedDocumentsIter<'a, D, V>;
310
    type Item = MappedDocument<'a, D, V::Key, V::Value>;
311

            
312
11
    fn into_iter(self) -> Self::IntoIter {
313
11
        self.iter()
314
11
    }
315
}
316

            
317
impl<'a, D, V: View> Iterator for MappedDocumentsIter<'a, D, V> {
318
    type Item = MappedDocument<'a, D, V::Key, V::Value>;
319

            
320
23
    fn next(&mut self) -> Option<Self::Item> {
321
23
        let doc = self.docs.get(self.index);
322
23
        self.index = self.index.saturating_add(1);
323
23
        doc
324
23
    }
325
}
326

            
327
/// A mapped document returned from a view query.
328
pub struct MappedDocument<'a, D, K, V> {
329
    /// The key that this document mapped to.
330
    pub key: &'a K,
331
    /// The associated value of this key.
332
    pub value: &'a V,
333
    /// The source document of this mapping.
334
    pub document: &'a D,
335
}
336

            
337
/// Represents a document's entry in a View's mappings, serialized and ready to store.
338
996030
#[derive(Serialize, Deserialize, Debug, Clone)]
339
pub struct Serialized {
340
    /// The header of the document that emitted this entry.
341
    pub source: Header,
342

            
343
    /// The key used to index the View.Operation
344
    pub key: Bytes,
345

            
346
    /// An associated value stored in the view.Operation
347
    pub value: Bytes,
348
}
349

            
350
impl Serialized {
351
    /// Deserializes this map.
352
    pub fn deserialized<View: SerializedView>(
353
        &self,
354
    ) -> Result<Map<View::Key, View::Value>, view::Error> {
355
        Ok(Map::new(
356
            self.source.clone(),
357
            <View::Key as Key>::from_ord_bytes(ByteSource::Borrowed(&self.key))
358
                .map_err(view::Error::key_serialization)?,
359
            View::deserialize(&self.value)?,
360
        ))
361
    }
362
}
363

            
364
/// A serialized [`MappedDocument`](MappedDocument).
365
#[derive(Clone, Serialize, Deserialize, Debug)]
366
pub struct MappedSerializedDocuments {
367
    /// The serialized mapped value.
368
    pub mappings: Vec<Serialized>,
369
    /// The source document.
370
    pub documents: BTreeMap<DocumentId, OwnedDocument>,
371
}
372

            
373
impl MappedSerializedDocuments {
374
    /// Deserialize into a [`MappedDocument`](MappedDocument).
375
    pub fn deserialized<View: SerializedView>(
376
        self,
377
    ) -> Result<MappedDocuments<OwnedDocument, View>, crate::Error> {
378
        let mappings = self
379
            .mappings
380
            .iter()
381
            .map(|mapping| {
382
                let deserialized = Serialized::deserialized::<View>(mapping)?;
383
                Ok(CollectionMap {
384
                    source: deserialized.source.try_into()?,
385
                    key: deserialized.key,
386
                    value: deserialized.value,
387
                })
388
            })
389
            .collect::<Result<Vec<_>, crate::Error>>()?;
390

            
391
        Ok(MappedDocuments {
392
            mappings,
393
            documents: self
394
                .documents
395
                .into_iter()
396
                .map(|(key, value)| {
397
                    let key = key.deserialize()?;
398
                    Ok((key, value))
399
                })
400
                .collect::<Result<BTreeMap<_, _>, crate::Error>>()?,
401
        })
402
    }
403
}
404

            
405
/// A key value pair
406
24
#[derive(Clone, Eq, PartialEq, Debug)]
407
pub struct MappedValue<K, V> {
408
    /// The key responsible for generating the value
409
    pub key: K,
410

            
411
    /// The value generated by the `View`
412
    pub value: V,
413
}
414

            
415
impl<K, V> MappedValue<K, V> {
416
    /// Returns a new instance with the key/value pair.
417
161006661
    pub const fn new(key: K, value: V) -> Self {
418
161006661
        Self { key, value }
419
161006661
    }
420
}
421

            
422
/// A mapped value in a [`View`].
423
pub type ViewMappedValue<'doc, V> =
424
    MappedValue<<V as ViewSchema>::MappedKey<'doc>, <<V as ViewSchema>::View as View>::Value>;
425

            
426
/// A serialized [`MappedValue`].
427
3750
#[derive(Clone, Serialize, Deserialize, Debug)]
428
pub struct MappedSerializedValue {
429
    /// The serialized key.
430
    pub key: Bytes,
431
    /// The serialized value.
432
    pub value: Bytes,
433
}