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

/// Update a [`Cycle`]
pub trait UpdateCycle {
    /// Add edges to the cycle
    #[must_use]
    fn add_half_edges(
        &self,
        edges: impl IntoIterator<Item = Handle<HalfEdge>>,
    ) -> Self;

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

    /// Replace an edge of the cycle
    ///
    /// This is a more general version of [`UpdateCycle::update_half_edge`]
    /// 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_half_edge<const N: usize>(
        &self,
        handle: &Handle<HalfEdge>,
        replace: impl FnOnce(&Handle<HalfEdge>) -> [Handle<HalfEdge>; N],
    ) -> Self;
}

impl UpdateCycle for Cycle {
    fn add_half_edges(
        &self,
        edges: impl IntoIterator<Item = Handle<HalfEdge>>,
    ) -> Self {
        let edges = self.half_edges().iter().cloned().chain(edges);
        Cycle::new(edges)
    }

    fn update_half_edge(
        &self,
        handle: &Handle<HalfEdge>,
        update: impl FnOnce(&Handle<HalfEdge>) -> Handle<HalfEdge>,
    ) -> Self {
        let edges = self
            .half_edges()
            .replace(handle, [update(handle)])
            .expect("Half-edge not found");
        Cycle::new(edges)
    }

    fn replace_half_edge<const N: usize>(
        &self,
        handle: &Handle<HalfEdge>,
        replace: impl FnOnce(&Handle<HalfEdge>) -> [Handle<HalfEdge>; N],
    ) -> Self {
        let edges = self
            .half_edges()
            .replace(handle, replace(handle))
            .expect("Half-edge not found");
        Cycle::new(edges)
    }
}