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::{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
32833
    pub(crate) fn serialized<View: SerializedView<Value = V>>(
27
32833
        &self,
28
32833
    ) -> Result<Serialized, view::Error> {
29
32833
        Ok(Serialized {
30
32833
            source: self.source.clone(),
31
32833
            key: Bytes::from(
32
32833
                self.key
33
32833
                    .as_big_endian_bytes()
34
32833
                    .map_err(view::Error::key_serialization)?
35
32833
                    .to_vec(),
36
32833
            ),
37
32833
            value: Bytes::from(View::serialize(&self.value)?),
38
        })
39
32833
    }
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
237491
    pub fn new(source: Header, key: K, value: V) -> Self {
45
237491
        Self { source, key, value }
46
237491
    }
47
}
48

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

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

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

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

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

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

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

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

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

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

            
127
67603
    fn into_iter(self) -> Self::IntoIter {
128
67603
        match self {
129
67228
            Mappings::Simple(option) => MappingsIter::Inline(option),
130
375
            Mappings::List(list) => MappingsIter::Vec(list.into_iter()),
131
        }
132
67603
    }
133
}
134

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
313
/// A serialized [`MappedValue`].
314
44
#[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
}