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

            
70
    /// Appends `mapping` to the end of this collection.
71
391
    pub fn push(&mut self, mapping: Map<K, V>) {
72
391
        match self {
73
391
            Self::Simple(existing_mapping) => {
74
391
                *self = if let Some(existing_mapping) = existing_mapping.take() {
75
391
                    Self::List(vec![existing_mapping, mapping])
76
                } else {
77
                    Self::Simple(Some(mapping))
78
                };
79
            }
80
            Self::List(vec) => vec.push(mapping),
81
        }
82
391
    }
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
391
    fn extend<T: IntoIterator<Item = Map<K, V>>>(&mut self, iter: T) {
93
391
        let iter = iter.into_iter();
94
782
        for map in iter {
95
391
            self.push(map);
96
391
        }
97
391
    }
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
1370
    fn from_iter<T: IntoIterator<Item = Self>>(iter: T) -> Self {
110
1370
        let mut iter = iter.into_iter();
111
1370
        if let Some(mut collected) = iter.next() {
112
1604
            for mappings in iter {
113
390
                collected.extend(mappings);
114
390
            }
115
1214
            collected
116
        } else {
117
156
            Self::none()
118
        }
119
1370
    }
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
72904
    fn into_iter(self) -> Self::IntoIter {
128
72904
        match self {
129
72514
            Mappings::Simple(option) => MappingsIter::Inline(option),
130
390
            Mappings::List(list) => MappingsIter::Vec(list.into_iter()),
131
        }
132
72904
    }
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
145756
    fn next(&mut self) -> Option<Self::Item> {
147
145756
        match self {
148
144586
            MappingsIter::Inline(opt) => opt.take(),
149
1170
            MappingsIter::Vec(iter) => iter.next(),
150
        }
151
145756
    }
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<DocumentId, 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
7812
#[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
3906
    pub fn deserialized<View: SerializedView>(
254
3906
        &self,
255
3906
    ) -> Result<Map<View::Key, View::Value>, view::Error> {
256
3906
        Ok(Map::new(
257
3906
            self.source.clone(),
258
3906
            <View::Key as Key>::from_ord_bytes(&self.key)
259
3906
                .map_err(view::Error::key_serialization)?,
260
3906
            View::deserialize(&self.value)?,
261
        ))
262
3906
    }
263
}
264

            
265
/// A serialized [`MappedDocument`](MappedDocument).
266
7680
#[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<DocumentId, OwnedDocument>,
272
}
273

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

            
285
3840
        Ok(MappedDocuments {
286
3840
            mappings,
287
3840
            documents: self.documents,
288
3840
        })
289
3840
    }
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
76025
    pub fn new(key: K, value: V) -> Self {
305
76025
        Self { key, value }
306
76025
    }
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
}