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
88
89
90
91
92
93
94
use crate::{
    objects::{Cycle, Region},
    storage::Handle,
};

/// Update a [`Region`]
pub trait UpdateRegion {
    /// Update the exterior of the region
    #[must_use]
    fn update_exterior(
        &self,
        update: impl FnOnce(&Handle<Cycle>) -> Handle<Cycle>,
    ) -> Self;

    /// Add the provided interiors to the region
    #[must_use]
    fn add_interiors(
        &self,
        interiors: impl IntoIterator<Item = Handle<Cycle>>,
    ) -> Self;

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

    /// Replace an interior cycle of the region
    ///
    /// This is a more general version of [`UpdateRegion::update_interior`]
    /// which can replace a single cycle 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_interior<const N: usize>(
        &self,
        handle: &Handle<Cycle>,
        replace: impl FnOnce(&Handle<Cycle>) -> [Handle<Cycle>; N],
    ) -> Self;
}

impl UpdateRegion for Region {
    fn update_exterior(
        &self,
        update: impl FnOnce(&Handle<Cycle>) -> Handle<Cycle>,
    ) -> Self {
        let exterior = update(self.exterior());
        Region::new(exterior, self.interiors().iter().cloned(), self.color())
    }

    fn add_interiors(
        &self,
        interiors: impl IntoIterator<Item = Handle<Cycle>>,
    ) -> Self {
        let interiors = self.interiors().iter().cloned().chain(interiors);
        Region::new(self.exterior().clone(), interiors, self.color())
    }

    fn update_interior(
        &self,
        handle: &Handle<Cycle>,
        update: impl FnOnce(&Handle<Cycle>) -> Handle<Cycle>,
    ) -> Self {
        let interiors = self
            .interiors()
            .replace(handle, [update(handle)])
            .expect("Cycle not found");
        Region::new(self.exterior().clone(), interiors, self.color())
    }

    fn replace_interior<const N: usize>(
        &self,
        handle: &Handle<Cycle>,
        replace: impl FnOnce(&Handle<Cycle>) -> [Handle<Cycle>; N],
    ) -> Self {
        let interiors = self
            .interiors()
            .replace(handle, replace(handle))
            .expect("Cycle not found");
        Region::new(self.exterior().clone(), interiors, self.color())
    }
}