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
9
#[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
35634
    pub(crate) fn serialized<View: SerializedView<Value = V>>(
27
35634
        &self,
28
35634
    ) -> Result<Serialized, view::Error> {
29
35634
        Ok(Serialized {
30
35634
            source: self.source.clone(),
31
35634
            key: Bytes::from(
32
35634
                self.key
33
35634
                    .as_ord_bytes()
34
35634
                    .map_err(view::Error::key_serialization)?
35
35634
                    .to_vec(),
36
35634
            ),
37
35634
            value: Bytes::from(View::serialize(&self.value)?),
38
        })
39
35634
    }
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
317920
    pub fn new(source: Header, key: K, value: V) -> Self {
45
317920
        Self { source, key, value }
46
317920
    }
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
459
    pub fn none() -> Self {
68
459
        Self::Simple(None)
69
459
    }
70

            
71
    /// Appends `mapping` to the end of this collection.
72
406
    pub fn push(&mut self, mapping: Map<K, V>) {
73
406
        match self {
74
406
            Self::Simple(existing_mapping) => {
75
406
                *self = if let Some(existing_mapping) = existing_mapping.take() {
76
406
                    Self::List(vec![existing_mapping, mapping])
77
                } else {
78
                    Self::Simple(Some(mapping))
79
                };
80
            }
81
            Self::List(vec) => vec.push(mapping),
82
        }
83
406
    }
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
406
    fn extend<T: IntoIterator<Item = Map<K, V>>>(&mut self, iter: T) {
94
406
        let iter = iter.into_iter();
95
812
        for map in iter {
96
406
            self.push(map);
97
406
        }
98
406
    }
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
1397
    fn from_iter<T: IntoIterator<Item = Self>>(iter: T) -> Self {
111
1397
        let mut iter = iter.into_iter();
112
1397
        if let Some(mut collected) = iter.next() {
113
1640
            for mappings in iter {
114
405
                collected.extend(mappings);
115
405
            }
116
1235
            collected
117
        } else {
118
162
            Self::none()
119
        }
120
1397
    }
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
85578
    fn into_iter(self) -> Self::IntoIter {
129
85578
        match self {
130
85173
            Mappings::Simple(option) => MappingsIter::Inline(option),
131
405
            Mappings::List(list) => MappingsIter::Vec(list.into_iter()),
132
        }
133
85578
    }
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
171102
    fn next(&mut self) -> Option<Self::Item> {
148
171102
        match self {
149
169887
            MappingsIter::Inline(opt) => opt.take(),
150
1215
            MappingsIter::Vec(iter) => iter.next(),
151
        }
152
171102
    }
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
34
    pub fn len(&self) -> usize {
170
34
        self.mappings.len()
171
34
    }
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
21
    pub fn get(&self, index: usize) -> Option<MappedDocument<'_, D, V::Key, V::Value>> {
183
21
        if index < self.len() {
184
18
            let mapping = &self.mappings[index];
185
18
            let document = self
186
18
                .documents
187
18
                .get(&mapping.source.id)
188
18
                .expect("missing mapped document");
189
18
            Some(MappedDocument {
190
18
                key: &mapping.key,
191
18
                value: &mapping.value,
192
18
                document,
193
18
            })
194
        } else {
195
3
            None
196
        }
197
21
    }
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
9
    fn into_iter(self) -> Self::IntoIter {
212
9
        MappedDocumentsIter {
213
9
            docs: self,
214
9
            index: 0,
215
9
        }
216
9
    }
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
16
    fn next(&mut self) -> Option<Self::Item> {
223
16
        let doc = self.docs.get(self.index);
224
16
        self.index = self.index.saturating_add(1);
225
16
        doc
226
16
    }
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
7888
#[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
3944
    pub fn deserialized<View: SerializedView>(
255
3944
        &self,
256
3944
    ) -> Result<Map<View::Key, View::Value>, view::Error> {
257
3944
        Ok(Map::new(
258
3944
            self.source.clone(),
259
3944
            <View::Key as Key>::from_ord_bytes(&self.key)
260
3944
                .map_err(view::Error::key_serialization)?,
261
3944
            View::deserialize(&self.value)?,
262
        ))
263
3944
    }
264
}
265

            
266
/// A serialized [`MappedDocument`](MappedDocument).
267
7756
#[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
3878
    pub fn deserialized<View: SerializedView>(
278
3878
        self,
279
3878
    ) -> Result<MappedDocuments<OwnedDocument, View>, crate::Error> {
280
3878
        let mappings = self
281
3878
            .mappings
282
3878
            .iter()
283
3878
            .map(Serialized::deserialized::<View>)
284
3878
            .collect::<Result<Vec<_>, _>>()?;
285

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

            
293
/// A key value pair
294
15
#[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
86091
    pub fn new(key: K, value: V) -> Self {
306
86091
        Self { key, value }
307
86091
    }
308
}
309

            
310
/// A mapped value in a [`View`].
311
#[allow(type_alias_bounds)] // False positive, required for associated types
312
pub type ViewMappedValue<V: View> = MappedValue<V::Key, V::Value>;
313

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