1
use bonsaidb::core::document::{CollectionDocument, Emit};
2
use bonsaidb::core::schema::{
3
    Collection, CollectionMapReduce, ReduceResult, View, ViewMapResult, ViewMappedValue, ViewSchema,
4
};
5
use serde::{Deserialize, Serialize};
6

            
7
334
#[derive(Debug, Serialize, Deserialize, Collection)]
8
#[collection(name = "shapes", views = [ShapesByNumberOfSides])]
9
pub struct Shape {
10
    pub sides: u32,
11
}
12

            
13
impl Shape {
14
106
    pub fn new(sides: u32) -> Self {
15
106
        Self { sides }
16
106
    }
17
}
18

            
19
379
#[derive(Debug, Clone, View, ViewSchema)]
20
#[view(collection = Shape, key = u32, value = usize, name = "by-number-of-sides")]
21
pub struct ShapesByNumberOfSides;
22

            
23
impl CollectionMapReduce for ShapesByNumberOfSides {
24
104
    fn map<'doc>(
25
104
        &self,
26
104
        document: CollectionDocument<<Self::View as View>::Collection>,
27
104
    ) -> ViewMapResult<'doc, Self::View> {
28
104
        document
29
104
            .header
30
104
            .emit_key_and_value(document.contents.sides, 1)
31
104
    }
32

            
33
14
    fn reduce(
34
14
        &self,
35
14
        mappings: &[ViewMappedValue<Self::View>],
36
14
        _rereduce: bool,
37
14
    ) -> ReduceResult<Self::View> {
38
152
        Ok(mappings.iter().map(|m| m.value).sum())
39
14
    }
40
}