fera_graph/props/
mod.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
5//! Traits and implementation for properties (key to values mapping).
6//!
7//! # Examples
8//!
9//! ```
10//! use fera_graph::prelude::*;
11//!
12//! let g = CompleteGraph::new(4);
13//! let mut p = g.default_vertex_prop(0i32);
14//! p[3] = -3;
15//! assert_eq!(0, p.get(0));
16//! assert_eq!(-3, p.get(3));
17//! let abs_p = p.map(i32::abs);
18//! assert_eq!(3, abs_p.get(3));
19//! ```
20
21use prelude::*;
22use std::ops::{Index, IndexMut};
23
24mod array;
25mod delegate;
26#[path = "fn.rs"]
27mod fn_;
28mod hashmap;
29mod ignore;
30
31pub use self::array::*;
32pub use self::delegate::*;
33pub use self::fn_::*;
34pub use self::hashmap::*;
35pub use self::ignore::*;
36
37use params::IntoOwned;
38
39/// An abstract property that maps keys in domain `K` to the corresponding values.
40pub trait PropGet<K> {
41    type Output: Sized;
42
43    /// Returns the value associated with `key`.
44    fn get(&self, key: K) -> Self::Output;
45
46    /// Creates a mapped property that maps each property value using `fun`.
47    #[inline]
48    fn map<F, O>(self, fun: F) -> Map<Self, F>
49    where
50        Self: Sized,
51        F: Fn(Self::Output) -> O,
52    {
53        Map(self, fun)
54    }
55
56    /// Returns a reference to this property.
57    #[inline]
58    fn by_ref(&self) -> &Self {
59        self
60    }
61}
62
63impl<'a, K, P: PropGet<K>> PropGet<K> for &'a P {
64    type Output = P::Output;
65
66    #[inline]
67    fn get(&self, key: K) -> Self::Output {
68        P::get(self, key)
69    }
70}
71
72// Indexable properties
73
74// TODO: turn PropIndexMut into a extension trait
75/// A property that can be read/write using indexing operations.
76pub trait PropIndexMut<Idx>: IndexMut<Idx> {
77    /// Set the value associated with each key produced by `iter` to the value associated with the
78    /// key in the property `source`.
79    fn set_values_from<P, I>(&mut self, iter: I, source: &P)
80    where
81        I: IntoIterator,
82        I::Item: IntoOwned<Idx>,
83        Idx: Clone,
84        P: Index<Idx, Output = Self::Output>,
85        Self::Output: Clone,
86    {
87        for v in iter {
88            let v = v.into_owned();
89            self[v.clone()].clone_from(&source[v]);
90        }
91    }
92
93    /// Set the value associated with keys produced by `iter` to `value`.
94    fn set_values<I>(&mut self, iter: I, value: Self::Output)
95    where
96        I: IntoIterator,
97        I::Item: IntoOwned<Idx>,
98        Self::Output: Clone,
99    {
100        for v in iter {
101            self[v.into_owned()].clone_from(&value);
102        }
103    }
104}
105
106impl<P: IndexMut<Idx>, Idx> PropIndexMut<Idx> for P {}
107
108// TODO: explain why the trait repetition for VertexProp and EdgeProp (missing trait alias?)
109
110// Vertex
111
112/// A vertex property.
113pub trait VertexPropGet<G, T>: PropGet<Vertex<G>, Output = T>
114where
115    G: WithVertex,
116{
117}
118
119impl<P, G, T> VertexPropGet<G, T> for P
120where
121    G: WithVertex,
122    P: PropGet<Vertex<G>, Output = T>,
123{
124}
125
126/// A vertex property that can be read using indexing operation.
127pub trait VertexProp<G, T>: Index<Vertex<G>, Output = T>
128where
129    G: WithVertex,
130{
131}
132
133impl<P, G, T> VertexProp<G, T> for P
134where
135    G: WithVertex,
136    P: Index<Vertex<G>, Output = T>,
137{
138}
139
140/// A vertex property that can be read/write using indexing operation.
141pub trait VertexPropMut<G, T>: IndexMut<Vertex<G>, Output = T>
142where
143    G: WithVertex,
144{
145}
146
147impl<P, G, T> VertexPropMut<G, T> for P
148where
149    G: WithVertex,
150    P: IndexMut<Vertex<G>, Output = T>,
151{
152}
153
154/// A vertex property that can be created using a graph reference and a value.
155pub trait VertexPropMutNew<G, T>: VertexPropMut<G, T>
156where
157    G: WithVertex,
158{
159    /// Creates a new vertex prop.
160    ///
161    /// This method is rarely called explicitly, it is instead used through
162    /// [`WithVertex::vertex_prop`].
163    ///
164    /// [`WithVertex::vertex_prop`]: ../trait.WithVertex.html#method.vertex_prop
165    fn new_vertex_prop(g: &G, value: T) -> Self
166    where
167        T: Clone;
168}
169
170/// A graph that has a default vertex property type, that is, has a default implementation to
171/// associated values with vertices.
172pub trait WithVertexProp<T>: WithVertex {
173    /// The vertex property type.
174    type VertexProp: VertexPropMutNew<Self, T>;
175
176    /// Creates a new default vertex property where the initial value associated with each vertex
177    /// is `value`.
178    fn default_vertex_prop(&self, value: T) -> DefaultVertexPropMut<Self, T>
179    where
180        T: Clone,
181    {
182        self.vertex_prop(value)
183    }
184
185    /// Creates a new default vertex property where the initial value associated with each vertex
186    /// `v` is produced by `fun(v)`.
187    fn default_vertex_prop_from_fn<P, F>(&self, fun: F) -> P
188    where
189        Self: VertexList,
190        P: VertexPropMutNew<Self, T>,
191        F: FnMut(Vertex<Self>) -> T,
192        T: Default + Clone,
193    {
194        self.vertex_prop_from_fn(fun)
195    }
196}
197
198/// A graph that has a property that maps each vertex to an integer in the range `0..num_vertices`.
199pub trait WithVertexIndexProp: WithVertex {
200    type VertexIndexProp: VertexPropGet<Self, usize>;
201
202    /// Creates an vertex index map.
203    fn vertex_index(&self) -> VertexIndexProp<Self>;
204}
205
206// Edge
207
208/// A edge property.
209pub trait EdgePropGet<G, T>: PropGet<Edge<G>, Output = T>
210where
211    G: WithEdge,
212{
213}
214
215impl<P, G, T> EdgePropGet<G, T> for P
216where
217    G: WithEdge,
218    P: PropGet<Edge<G>, Output = T>,
219{
220}
221
222/// An edge property that can be read using indexing operation.
223pub trait EdgeProp<G, T>: Index<Edge<G>, Output = T>
224where
225    G: WithEdge,
226{
227}
228
229impl<P, G, T> EdgeProp<G, T> for P
230where
231    G: WithEdge,
232    P: Index<Edge<G>, Output = T>,
233{
234}
235
236/// A edge property that can be read/write using indexing operation.
237pub trait EdgePropMut<G, T>: IndexMut<Edge<G>, Output = T>
238where
239    G: WithEdge,
240{
241}
242
243impl<P, G, T> EdgePropMut<G, T> for P
244where
245    G: WithEdge,
246    P: IndexMut<Edge<G>, Output = T>,
247{
248}
249
250/// An edge property that can be read/write using indexing operation.
251pub trait EdgePropMutNew<G, T>: EdgePropMut<G, T>
252where
253    G: WithEdge,
254{
255    /// Creates a new edge prop.
256    ///
257    /// This method is rarely called explicitly, it is instead used through
258    /// [`WithEdge::edge_prop`].
259    ///
260    /// [`WithEdge::edge_prop`]: ../trait.WithEdge.html#method.edge_prop
261    fn new_edge_prop(g: &G, value: T) -> Self
262    where
263        T: Clone;
264}
265
266/// A graph that has a default edge property type, that is, has a default implementation to
267/// associated values with edges.
268pub trait WithEdgeProp<T>: WithEdge {
269    type EdgeProp: EdgePropMutNew<Self, T>;
270
271    /// Creates a new default edge property where the initial value associated with each edge is
272    /// `value`.
273    fn default_edge_prop(&self, value: T) -> DefaultEdgePropMut<Self, T>
274    where
275        T: Clone,
276    {
277        self.edge_prop(value)
278    }
279
280    /// Creates a new default edge property where the initial value associated with each edge `e`
281    /// is produced by `fun(e)`.
282    fn default_edge_prop_from_fn<P, F>(&self, fun: F) -> P
283    where
284        Self: EdgeList,
285        P: EdgePropMutNew<Self, T>,
286        F: FnMut(Edge<Self>) -> T,
287        T: Default + Clone,
288    {
289        self.edge_prop_from_fn(fun)
290    }
291}
292
293/// A graph that has a property that maps each edge to an integer in the range `0..num_edges`.
294pub trait WithEdgeIndexProp: WithEdge {
295    type EdgeIndexProp: EdgePropGet<Self, usize>;
296
297    /// Creates an edge index map.
298    fn edge_index(&self) -> EdgeIndexProp<Self>;
299}
300
301// Basic properties traits
302
303macro_rules! items {
304    ($($item:item)*) => ($($item)*);
305}
306
307macro_rules! basic_props1 {
308    ($($v:ty),* ; $($e:ty),* ; $($c:ty),*) => (
309        items! {
310            pub trait BasicVertexProps:
311                $(WithVertexProp<$v> +)* { }
312
313            pub trait BasicEdgeProps:
314                $(WithEdgeProp<$e> +)* { }
315
316            pub trait BasicProps:
317                $(WithVertexProp<$c> + WithEdgeProp<$c> +)* { }
318        }
319    )
320}
321
322macro_rules! basic_props2 {
323    ($($v:ty),* ; $($e:ty),* ; $($c:ty),* ) => (
324        basic_props1! {
325            $($v),+ , $(Vec<$v>),+ ;
326            $($e),+ , $(Vec<$e>),+ ;
327            $($c),+ , $(Vec<$c>),+
328        }
329    )
330}
331
332macro_rules! basic_props {
333    ($($t:ty),*) => (
334        basic_props2! {
335            $($t),+, Vertex<Self>, OptionVertex<Self> ;
336            $($t),+, Edge<Self>, OptionEdge<Self> ;
337            $($t),+, Vertex<Self>, OptionVertex<Self>, Edge<Self>, OptionEdge<Self>
338        }
339    )
340}
341
342basic_props! {
343    bool,
344    char,
345    i8, i16, i32, i64, isize,
346    u8, u16, u32, u64, usize,
347    f32, f64,
348    &'static str, String,
349    Color
350}
351
352/// Indicates the status of an item in a traverse algorithm.
353///
354#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
355pub enum Color {
356    /// Generally indicates that an item was not discovered in the search.
357    White,
358    /// Generally indicates that an item was discovered in the search but there is some pending
359    /// work to be done with the item.
360    Gray,
361    /// Generally indicates that the item was discovered and all the work related with the item is
362    /// finished.
363    Black,
364}
365
366impl Default for Color {
367    /// Returns `Color::White`.
368    #[inline]
369    fn default() -> Color {
370        Color::White
371    }
372}
373
374// Adaptors
375
376/// A property that maps the value of a wrapped property with a function.
377///
378/// This `struct` is created by [`PropGet::map`].
379///
380/// [`PropGet::map`]: trait.PropGet.html#method.map
381pub struct Map<P, F>(P, F);
382
383impl<K, P, F, O> PropGet<K> for Map<P, F>
384where
385    P: PropGet<K>,
386    F: Fn(P::Output) -> O,
387{
388    type Output = O;
389
390    #[inline]
391    fn get(&self, k: K) -> Self::Output {
392        (self.1)(self.0.get(k))
393    }
394}