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
use crate::{
    objects::{Region, Sketch},
    storage::Handle,
};

/// Update a [`Sketch`]
pub trait UpdateSketch {
    /// Add a region to the sketch
    #[must_use]
    fn add_region(&self, region: Handle<Region>) -> Self;

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

    /// Replace a region of the sketch
    ///
    /// This is a more general version of [`UpdateSketch::update_region`] which
    /// can replace a single edge 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_region<const N: usize>(
        &self,
        handle: &Handle<Region>,
        replace: impl FnOnce(&Handle<Region>) -> [Handle<Region>; N],
    ) -> Self;
}

impl UpdateSketch for Sketch {
    fn add_region(&self, region: Handle<Region>) -> Self {
        Sketch::new(self.regions().iter().cloned().chain([region]))
    }

    fn update_region(
        &self,
        handle: &Handle<Region>,
        update: impl FnOnce(&Handle<Region>) -> Handle<Region>,
    ) -> Self {
        let regions = self
            .regions()
            .replace(handle, [update(handle)])
            .expect("Region not found");
        Sketch::new(regions)
    }

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