fera_graph/props/
ignore.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5use prelude::*;
6use std::ops::{Index, IndexMut};
7
8/// A property that ignore writes.
9///
10/// This `struct` maintains two values, one that is returned when a shared reference is requested
11/// and one that is returned when a mutable reference is requested. Before returning the mutable
12/// reference, the value is cloned from the original value, so it seems that all previous writes
13/// was ignored.
14///
15/// # Example
16///
17/// ```
18/// use fera_graph::prelude::*;
19/// use fera_graph::props::IgnoreWriteProp;
20///
21/// let g = CompleteGraph::new(5);
22/// let mut p: IgnoreWriteProp<u32> = g.vertex_prop(3);
23///
24/// assert_eq!(3, p[0]);
25/// p[0] = 20;
26/// // the previous write was "ignored"
27/// assert_eq!(3, p[0]);
28/// ```
29pub struct IgnoreWriteProp<T> {
30    read: T,
31    write: T,
32}
33
34impl<I, T: Clone> Index<I> for IgnoreWriteProp<T> {
35    type Output = T;
36
37    #[inline]
38    fn index(&self, _: I) -> &Self::Output {
39        &self.read
40    }
41}
42
43impl<I, T: Clone> IndexMut<I> for IgnoreWriteProp<T> {
44    #[inline]
45    fn index_mut(&mut self, _: I) -> &mut Self::Output {
46        self.write.clone_from(&self.read);
47        &mut self.write
48    }
49}
50
51impl<G, T> VertexPropMutNew<G, T> for IgnoreWriteProp<T>
52where
53    G: WithVertex,
54    T: Clone,
55{
56    fn new_vertex_prop(_: &G, value: T) -> Self {
57        IgnoreWriteProp {
58            read: value.clone(),
59            write: value,
60        }
61    }
62}
63
64impl<G, T> EdgePropMutNew<G, T> for IgnoreWriteProp<T>
65where
66    G: WithEdge,
67    T: Clone,
68{
69    fn new_edge_prop(_: &G, value: T) -> Self {
70        IgnoreWriteProp {
71            read: value.clone(),
72            write: value,
73        }
74    }
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80
81    #[test]
82    fn basic() {
83        let n = 3;
84        let val = 7;
85        let g = CompleteGraph::new(n);
86        let mut p: IgnoreWriteProp<u32> = g.vertex_prop(val);
87
88        for i in 0..n {
89            assert_eq!(val, p[i]);
90            p[i] = 20;
91            for j in 0..n {
92                assert_eq!(val, p[j]);
93            }
94        }
95    }
96}