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
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

//! Graph traits and implementations.

pub mod adaptors;
pub mod adjset;
pub mod complete;
pub mod static_;

mod common;
mod ref_;

pub use self::common::*;

use prelude::*;
use params::IntoOwned;

use std::fmt::Debug;
use std::hash::Hash;

pub type Vertex<G> = <G as WithVertex>::Vertex;
pub type OptionVertex<G> = <G as WithVertex>::OptionVertex;
pub type VertexIndexProp<G> = <G as WithVertexIndexProp>::VertexIndexProp;
pub type VertexIter<'a, G> = <G as VertexTypes<'a, G>>::VertexIter;
pub type OutNeighborIter<'a, G> = <G as VertexTypes<'a, G>>::OutNeighborIter;
pub type DefaultVertexPropMut<G, T> = <G as WithVertexProp<T>>::VertexProp;

pub type Edge<G> = <G as WithEdge>::Edge;
pub type OptionEdge<G> = <G as WithEdge>::OptionEdge;
pub type EdgeIndexProp<G> = <G as WithEdgeIndexProp>::EdgeIndexProp;
pub type EdgeIter<'a, G> = <G as EdgeTypes<'a, G>>::EdgeIter;
pub type OutEdgeIter<'a, G> = <G as EdgeTypes<'a, G>>::OutEdgeIter;
pub type DefaultEdgePropMut<G, T> = <G as WithEdgeProp<T>>::EdgeProp;

macro_rules! items {
    ($($item:item)*) => ($($item)*);
}

macro_rules! trait_alias {
    ($name:ident = $($base:tt)+) => {
        items! {
            pub trait $name: $($base)+ { }
            impl<T: $($base)+> $name for T { }
        }
    };
}

trait_alias!(Graph = VertexList + EdgeList<Kind = Undirected> + BasicProps);
trait_alias!(AdjacencyGraph = Graph + Adjacency);
trait_alias!(IncidenceGraph = AdjacencyGraph + Incidence);

trait_alias!(Digraph = VertexList + EdgeList<Kind = Directed> + BasicProps);
trait_alias!(AdjacencyDigraph = Digraph + Adjacency);
trait_alias!(IncidenceDigraph = AdjacencyDigraph + Incidence);

trait_alias!(GraphItem = Copy + Eq + Hash + Debug);

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum Orientation {
    Directed,
    Undirected,
}

impl Orientation {
    #[inline]
    pub fn is_directed(&self) -> bool {
        *self == Orientation::Directed
    }

    #[inline]
    pub fn is_undirected(&self) -> bool {
        *self == Orientation::Undirected
    }
}

pub trait EdgeKind {}

pub trait UniformEdgeKind: EdgeKind {
    fn orientation() -> Orientation;

    #[inline]
    fn is_directed() -> bool {
        Self::orientation().is_directed()
    }

    #[inline]
    fn is_undirected() -> bool {
        Self::orientation().is_undirected()
    }
}

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum Directed {}

impl EdgeKind for Directed {}

impl UniformEdgeKind for Directed {
    #[inline]
    fn orientation() -> Orientation {
        Orientation::Directed
    }
}

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum Undirected {}

impl EdgeKind for Undirected {}

impl UniformEdgeKind for Undirected {
    #[inline]
    fn orientation() -> Orientation {
        Orientation::Undirected
    }
}

// TODO: write a graph with mixed edges and test it
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum Mixed {}

impl EdgeKind for Mixed {}

pub trait VertexTypes<'a, G: WithVertex> {
    type VertexIter: Iterator<Item = Vertex<G>>;
    type OutNeighborIter: Iterator<Item = Vertex<G>>;
}

pub trait WithVertex: Sized + for<'a> VertexTypes<'a, Self> {
    type Vertex: 'static + GraphItem;
    type OptionVertex: 'static + GraphItem + Optional<Vertex<Self>> + From<Option<Vertex<Self>>>;

    // TODO: is this necessary?
    fn vertex_none() -> OptionVertex<Self> {
        Default::default()
    }

    // TODO: is this necessary?
    fn vertex_some(v: Vertex<Self>) -> OptionVertex<Self> {
        From::from(v)
    }

    fn vertex_prop<P, T>(&self, value: T) -> P
    where
        P: VertexPropMutNew<Self, T>,
        T: Clone,
    {
        P::new_vertex_prop(self, value)
    }

    fn vertex_prop_from_fn<P, T, F>(&self, mut fun: F) -> P
    where
        Self: VertexList,
        P: VertexPropMutNew<Self, T>,
        F: FnMut(Vertex<Self>) -> T,
        T: Default + Clone,
    {
        // FIXME: Can we remove T: Default + Clone?
        let mut p: P = self.vertex_prop(T::default());
        for v in self.vertices() {
            p[v] = fun(v);
        }
        p
    }
}

pub trait EdgeTypes<'a, G: WithEdge> {
    type EdgeIter: Iterator<Item = Edge<G>>;
    type OutEdgeIter: Iterator<Item = Edge<G>>;
}

pub trait WithEdge: Sized + WithVertex + for<'a> EdgeTypes<'a, Self> {
    type Kind: EdgeKind;
    type Edge: 'static + GraphItem;
    type OptionEdge: 'static + GraphItem + Optional<Edge<Self>> + From<Option<Edge<Self>>>;

    fn orientation(&self, _e: Edge<Self>) -> Orientation;

    fn source(&self, e: Edge<Self>) -> Vertex<Self>;

    fn target(&self, e: Edge<Self>) -> Vertex<Self>;

    fn ends<'a, I, O>(&'a self, item: I) -> O
    where
        I: Ends<'a, Self, O>,
    {
        item._ends(self)
    }

    fn end_vertices(&self, e: Edge<Self>) -> (Vertex<Self>, Vertex<Self>) {
        self.ends(e)
    }

    fn with_ends<I>(&self, iter: I) -> EdgesWithEnds<Self, I::IntoIter>
    where
        I: IntoIterator,
        I::Item: IntoOwned<Edge<Self>>,
    {
        EdgesWithEnds {
            g: self,
            iter: iter.into_iter(),
        }
    }

    fn opposite(&self, u: Vertex<Self>, e: Edge<Self>) -> Vertex<Self> {
        let (s, t) = self.ends(e);
        if u == s {
            t
        } else if u == t {
            s
        } else {
            panic!("u is not an end of e");
        }
    }

    fn is_incident(&self, v: Vertex<Self>, e: Edge<Self>) -> bool {
        let (s, t) = self.ends(e);
        v == s || v == t
    }

    fn reverse(&self, e: Edge<Self>) -> Edge<Self>
    where
        Self: WithEdge<Kind = Undirected>,
    {
        self.get_reverse(e)
            .expect("the reverse of an edge (all undirected graphs must implement reverse)")
    }

    fn get_reverse(&self, _e: Edge<Self>) -> Option<Edge<Self>> {
        // TODO: remove default impl
        None
    }

    // TODO: is this necessary?
    fn edge_none() -> OptionEdge<Self> {
        Default::default()
    }

    // TODO: is this necessary?
    fn edge_some(e: Edge<Self>) -> OptionEdge<Self> {
        From::from(e)
    }

    fn edge_prop<P, T>(&self, value: T) -> P
    where
        P: EdgePropMutNew<Self, T>,
        T: Clone,
    {
        P::new_edge_prop(self, value)
    }

    fn edge_prop_from_fn<P, F, T>(&self, mut fun: F) -> P
    where
        Self: EdgeList,
        P: EdgePropMutNew<Self, T>,
        F: FnMut(Edge<Self>) -> T,
        T: Default + Clone,
    {
        // FIXME: Can we remove T: Default + Clone?
        let mut p: P = self.edge_prop(T::default());
        for e in self.edges() {
            p[e] = fun(e);
        }
        p
    }
}

pub trait VertexList: Sized + WithVertex {
    fn vertices(&self) -> VertexIter<Self>;

    fn num_vertices(&self) -> usize {
        self.vertices().count()
    }
}

pub trait EdgeList: Sized + WithEdge {
    fn edges(&self) -> EdgeIter<Self>;

    fn edges_ends(&self) -> EdgesEnds<Self, EdgeIter<Self>> {
        // TODO: specialize
        self.ends(self.edges())
    }

    fn edges_with_ends(&self) -> EdgesWithEnds<Self, EdgeIter<Self>> {
        // TODO: specialize
        self.with_ends(self.edges())
    }

    fn num_edges(&self) -> usize {
        self.edges().count()
    }

    fn get_edge_by_ends(&self, u: Vertex<Self>, v: Vertex<Self>) -> Option<Edge<Self>> {
        // TODO: specialize for Incidence
        for (e, a, b) in self.edges_with_ends() {
            if (u, v) == (a, b) {
                return Some(e);
            }
            if self.orientation(e).is_directed() {
                continue;
            }
            if let Some(e) = self.get_reverse(e) {
                if (u, v) == (b, a) {
                    return Some(e);
                }
            }
        }
        None
    }

    fn edge_by_ends(&self, u: Vertex<Self>, v: Vertex<Self>) -> Edge<Self> {
        // TODO: fix expect message
        self.get_edge_by_ends(u, v).expect("an edge (u, v)")
    }
}

pub trait Adjacency: WithVertex {
    fn out_neighbors(&self, v: Vertex<Self>) -> OutNeighborIter<Self>;

    fn out_degree(&self, v: Vertex<Self>) -> usize {
        self.out_neighbors(v).count()
    }
}

pub trait Incidence: WithEdge + Adjacency {
    fn out_edges(&self, v: Vertex<Self>) -> OutEdgeIter<Self>;

    fn out_edges_ends(&self, v: Vertex<Self>) -> EdgesEnds<Self, OutEdgeIter<Self>> {
        // TODO: specialize
        self.ends(self.out_edges(v))
    }

    fn out_edges_with_ends(&self, v: Vertex<Self>) -> EdgesWithEnds<Self, OutEdgeIter<Self>> {
        // TODO: specialize
        self.with_ends(self.out_edges(v))
    }
}

// Ends

pub trait Ends<'a, G, O> {
    fn _ends(self, g: &'a G) -> O;
}

impl<'a, G> Ends<'a, G, (Vertex<G>, Vertex<G>)> for Edge<G>
where
    G: WithEdge,
{
    fn _ends(self, g: &'a G) -> (Vertex<G>, Vertex<G>) {
        (g.source(self), g.target(self))
    }
}

impl<'a, G> Ends<'a, G, (Edge<G>, Vertex<G>, Vertex<G>)> for Edge<G>
where
    G: WithEdge,
{
    fn _ends(self, g: &'a G) -> (Edge<G>, Vertex<G>, Vertex<G>) {
        let (u, v) = g.ends(self);
        (self, u, v)
    }
}

impl<'a, G, I> Ends<'a, G, EdgesEnds<'a, G, I::IntoIter>> for I
where
    G: WithEdge,
    I: IntoIterator,
    I::Item: IntoOwned<Edge<G>>,
{
    fn _ends(self, g: &'a G) -> EdgesEnds<'a, G, I::IntoIter> {
        EdgesEnds {
            g: g,
            iter: self.into_iter(),
        }
    }
}

// Iterators

pub struct EdgesEnds<'a, G: 'a, I> {
    g: &'a G,
    iter: I,
}

impl<'a, G, I> Iterator for EdgesEnds<'a, G, I>
where
    G: WithEdge,
    I: Iterator,
    I::Item: IntoOwned<Edge<G>>,
{
    type Item = (Vertex<G>, Vertex<G>);

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next().map(|e| self.g.ends(e.into_owned()))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl<'a, G, I> ExactSizeIterator for EdgesEnds<'a, G, I>
where
    G: WithEdge,
    I: Iterator,
    I::Item: IntoOwned<Edge<G>>,
{
}

pub struct EdgesWithEnds<'a, G: 'a, I> {
    g: &'a G,
    iter: I,
}

impl<'a, G, I> Iterator for EdgesWithEnds<'a, G, I>
where
    G: WithEdge,
    I: Iterator,
    I::Item: IntoOwned<Edge<G>>,
{
    type Item = (Edge<G>, Vertex<G>, Vertex<G>);

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next().map(|e| self.g.ends(e.into_owned()))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl<'a, G, I> ExactSizeIterator for EdgesWithEnds<'a, G, I>
where
    G: WithEdge,
    I: Iterator,
    I::Item: IntoOwned<Edge<G>>,
{
}