fera_graph/props/
array.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::*;
6
7use std::ops::{Index, IndexMut};
8
9// TODO: define a feature to disable bounds check (or a property type?).
10/// A vertex property backed by a [`Vec`].
11///
12/// [`Vec`]: https://doc.rust-lang.org/stable/std/vec/struct.Vec.html
13pub type VecVertexProp<G, T> = ArrayProp<VertexIndexProp<G>, Vec<T>>;
14
15/// A edge property backed by a [`Vec`].
16///
17/// [`Vec`]: https://doc.rust-lang.org/stable/std/vec/struct.Vec.html
18pub type VecEdgeProp<G, T> = ArrayProp<EdgeIndexProp<G>, Vec<T>>;
19
20// TODO: Define SliceVertexProp and SliceEdgeProp
21
22// TODO: Rename to SequenceProp
23/// A property backed by an array.
24#[derive(Clone, Debug)]
25pub struct ArrayProp<P, D> {
26    index: P,
27    data: D,
28}
29
30impl<P, D> ArrayProp<P, D> {
31    fn new(index: P, data: D) -> Self {
32        Self { index, data }
33    }
34}
35
36impl<I, P, D> PropGet<I> for ArrayProp<P, D>
37where
38    P: PropGet<I, Output = usize>,
39    D: Index<usize>,
40    D::Output: Clone + Sized,
41{
42    type Output = D::Output;
43
44    #[inline(always)]
45    fn get(&self, item: I) -> D::Output {
46        self.data.index(self.index.get(item)).clone()
47    }
48}
49
50impl<I, P, D> Index<I> for ArrayProp<P, D>
51where
52    P: PropGet<I, Output = usize>,
53    D: Index<usize>,
54{
55    type Output = D::Output;
56
57    #[inline(always)]
58    fn index(&self, item: I) -> &Self::Output {
59        self.data.index(self.index.get(item))
60    }
61}
62
63impl<I, P, D> IndexMut<I> for ArrayProp<P, D>
64where
65    P: PropGet<I, Output = usize>,
66    D: IndexMut<usize>,
67{
68    #[inline(always)]
69    fn index_mut(&mut self, item: I) -> &mut Self::Output {
70        self.data.index_mut(self.index.get(item))
71    }
72}
73
74impl<T, G> VertexPropMutNew<G, T> for ArrayProp<VertexIndexProp<G>, Vec<T>>
75where
76    G: VertexList + WithVertexIndexProp,
77{
78    fn new_vertex_prop(g: &G, value: T) -> Self
79    where
80        T: Clone,
81    {
82        ArrayProp::new(g.vertex_index(), vec![value; g.num_vertices()])
83    }
84}
85
86impl<T, G> EdgePropMutNew<G, T> for ArrayProp<EdgeIndexProp<G>, Vec<T>>
87where
88    G: EdgeList + WithEdgeIndexProp,
89{
90    fn new_edge_prop(g: &G, value: T) -> Self
91    where
92        T: Clone,
93    {
94        ArrayProp::new(g.edge_index(), vec![value; g.num_edges()])
95    }
96}