1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use crate::{
    objects::{Face, Shell},
    storage::Handle,
};

/// Update a [`Shell`]
pub trait UpdateShell {
    /// Add faces to the shell
    #[must_use]
    fn add_faces(&self, faces: impl IntoIterator<Item = Handle<Face>>) -> Self;

    /// Update a face of the shell
    ///
    /// # Panics
    ///
    /// Panics, if the object can't be found.
    ///
    /// Panics, if the update results in a duplicate object.
    #[must_use]
    fn update_face(
        &self,
        handle: &Handle<Face>,
        update: impl FnOnce(&Handle<Face>) -> Handle<Face>,
    ) -> Self;

    /// Replace a face of the shell
    ///
    /// This is a more general version of [`UpdateShell::update_face`] which can
    /// replace a single face with multiple others.
    ///
    /// # Panics
    ///
    /// Panics, if the object can't be found.
    ///
    /// Panics, if the update results in a duplicate object.
    #[must_use]
    fn replace_face<const N: usize>(
        &self,
        handle: &Handle<Face>,
        replace: impl FnOnce(&Handle<Face>) -> [Handle<Face>; N],
    ) -> Self;

    /// Remove a face from the shell
    #[must_use]
    fn remove_face(&self, handle: &Handle<Face>) -> Self;
}

impl UpdateShell for Shell {
    fn add_faces(&self, faces: impl IntoIterator<Item = Handle<Face>>) -> Self {
        let faces = self.faces().iter().cloned().chain(faces);
        Shell::new(faces)
    }

    fn update_face(
        &self,
        handle: &Handle<Face>,
        update: impl FnOnce(&Handle<Face>) -> Handle<Face>,
    ) -> Self {
        let faces = self
            .faces()
            .replace(handle, [update(handle)])
            .expect("Face not found");
        Shell::new(faces)
    }

    fn replace_face<const N: usize>(
        &self,
        handle: &Handle<Face>,
        replace: impl FnOnce(&Handle<Face>) -> [Handle<Face>; N],
    ) -> Self {
        let faces = self
            .faces()
            .replace(handle, replace(handle))
            .expect("Face not found");
        Shell::new(faces)
    }

    fn remove_face(&self, handle: &Handle<Face>) -> Self {
        let faces = self
            .faces()
            .iter()
            .filter(|face| face.id() != handle.id())
            .cloned();

        Shell::new(faces)
    }
}