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
/*
 * Copyright (c) 2017-2020 Frank Fischer <frank-fischer@shadow-soft.de>
 *
 * This program is free software: you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see  <http://www.gnu.org/licenses/>
 */

//! This module provides vectors that can be indexed by nodes, edges or arcs.

use crate::traits::refs::{GraphSizeRef, IndexGraphRef};

use std::marker::PhantomData;
use std::ops::{Index, IndexMut};

/// A indexer maps items to numeric indices.
pub trait Indexer {
    /// The type of the index items.
    type Idx;
    /// The an iterator over all allowed items.
    type Iter: Iterator<Item = Self::Idx>;

    /// Return the number of items.
    ///
    /// This is the maximal allowed index.
    fn num_items(&self) -> usize;

    /// Return the index associated with an item.
    fn index(&self, i: Self::Idx) -> usize;

    /// Return an iterator over all items.
    fn iter(&self) -> Self::Iter;
}

/// An indexer for a graph.
pub trait GraphIndexer<G>: Indexer {
    /// Create a new indexer for the given graph.
    fn new(g: G) -> Self;
}

/// A vector that can be indexed by nodes or edges.
///
/// In fact, the vector can be indexed by some arbitrary item that can be mapped
/// to a numeric index using an `Indexer`.
pub struct ItemVec<I, T> {
    indexer: I,
    data: Vec<T>,
}

impl<I, T> ItemVec<I, T>
where
    I: Indexer,
{
    pub fn from_indexer(indexer: I, value: T) -> Self
    where
        T: Clone,
    {
        ItemVec {
            data: vec![value; indexer.num_items()],
            indexer,
        }
    }

    pub fn from_indexer_with<F>(indexer: I, f: F) -> Self
    where
        F: Fn(I::Idx) -> T,
    {
        ItemVec {
            data: indexer.iter().map(f).collect(),
            indexer,
        }
    }

    pub fn from_indexer_and_vec(indexer: I, values: Vec<T>) -> Self {
        assert_eq!(values.len(), indexer.num_items());
        ItemVec { data: values, indexer }
    }

    pub fn new2<G>(g: G, value: T) -> Self
    where
        I: GraphIndexer<G>,
        T: Clone,
    {
        Self::from_indexer(I::new(g), value)
    }

    pub fn new<G>(g: G, value: T) -> Self
    where
        I: GraphIndexer<G>,
        T: Clone,
    {
        Self::from_indexer(I::new(g), value)
    }

    pub fn new_with<G, F>(g: G, f: F) -> Self
    where
        I: GraphIndexer<G>,
        F: Fn(I::Idx) -> T,
    {
        Self::from_indexer_with(I::new(g), f)
    }

    pub fn new_from_vec<G>(g: G, values: Vec<T>) -> Self
    where
        I: GraphIndexer<G>,
    {
        Self::from_indexer_and_vec(I::new(g), values)
    }

    pub fn iter(&self) -> std::iter::Zip<I::Iter, std::slice::Iter<T>> {
        self.indexer.iter().zip(self.data.iter())
    }

    pub fn iter_mut(&mut self) -> std::iter::Zip<I::Iter, std::slice::IterMut<T>> {
        self.indexer.iter().zip(self.data.iter_mut())
    }

    pub fn map<F>(&self, f: F) -> Self
    where
        I: Clone,
        F: Fn((I::Idx, &T)) -> T,
    {
        Self::from_indexer_and_vec(self.indexer.clone(), self.iter().map(f).collect())
    }

    pub fn reset(&mut self, value: T)
    where
        T: Clone,
    {
        for u in self.indexer.iter() {
            self.data[self.indexer.index(u)] = value.clone();
        }
    }
}

impl<I, T> Index<I::Idx> for ItemVec<I, T>
where
    I: Indexer,
{
    type Output = T;
    fn index(&self, i: I::Idx) -> &T {
        &self.data[self.indexer.index(i)]
    }
}

impl<I, T> IndexMut<I::Idx> for ItemVec<I, T>
where
    I: Indexer,
{
    fn index_mut(&mut self, i: I::Idx) -> &mut T {
        &mut self.data[self.indexer.index(i)]
    }
}

/// An indexer for nodes of an `IndexGraph`.
#[derive(Copy)]
pub struct NodeIndexer<'a, G>(pub G, PhantomData<&'a ()>);

impl<'a, G> Clone for NodeIndexer<'a, G>
where
    G: Clone,
{
    fn clone(&self) -> Self {
        NodeIndexer(self.0.clone(), PhantomData)
    }
}

impl<'a, G> Indexer for NodeIndexer<'a, G>
where
    G: IndexGraphRef<'a>,
{
    type Idx = G::Node;
    type Iter = G::NodeIter;

    fn num_items(&self) -> usize {
        self.0.num_nodes()
    }

    fn index(&self, u: G::Node) -> usize {
        self.0.node_id(u)
    }

    fn iter(&self) -> Self::Iter {
        GraphSizeRef::nodes(&self.0)
    }
}

impl<'a, G> GraphIndexer<G> for NodeIndexer<'a, G>
where
    G: IndexGraphRef<'a>,
{
    fn new(g: G) -> Self {
        NodeIndexer(g, PhantomData)
    }
}

/// An indexer for edges of an `IndexGraph`.
#[derive(Copy)]
pub struct EdgeIndexer<'a, G>(pub G, PhantomData<&'a ()>);

impl<'a, G> Clone for EdgeIndexer<'a, G>
where
    G: Clone,
{
    fn clone(&self) -> Self {
        EdgeIndexer(self.0.clone(), PhantomData)
    }
}

impl<'a, G> Indexer for EdgeIndexer<'a, G>
where
    G: IndexGraphRef<'a>,
{
    type Idx = G::Edge;
    type Iter = G::EdgeIter;

    fn num_items(&self) -> usize {
        self.0.num_edges()
    }

    fn index(&self, e: G::Edge) -> usize {
        self.0.edge_id(e)
    }

    fn iter(&self) -> Self::Iter {
        GraphSizeRef::edges(&self.0)
    }
}

impl<'a, G> GraphIndexer<G> for EdgeIndexer<'a, G>
where
    G: IndexGraphRef<'a>,
{
    fn new(g: G) -> Self {
        EdgeIndexer(g, PhantomData)
    }
}

/// A vector containing a value for each node.
///
/// # Example
///
/// Create a vector with all elements set to some value.
///
/// ```
/// # use rs_graph::LinkedListGraph;
/// # use rs_graph::traits::*;
/// # use rs_graph::classes::peterson;
/// #
/// let g = peterson::<LinkedListGraph>();
/// let weights = rs_graph::vec::NodeVec::new(&g, 0);
/// assert!(g.nodes().all(|u| weights[u] == 0));
/// ```
///
/// Create a vector with an initialization function.
///
/// ```
/// # use rs_graph::LinkedListGraph;
/// # use rs_graph::traits::*;
/// # use rs_graph::classes::peterson;
/// #
/// let g = peterson::<LinkedListGraph>();
/// let weights = rs_graph::vec::NodeVec::new_with(&g, |u| g.node_id(u));
/// assert!(g.nodes().all(|u| weights[u] == g.node_id(u)));
/// ```
pub type NodeVec<'a, G, T> = ItemVec<NodeIndexer<'a, G>, T>;

/// A vector containing a value for each edge.
///
/// # Example
///
/// Create a vector with all elements set to some value.
///
/// ```
/// # use rs_graph::LinkedListGraph;
/// # use rs_graph::traits::*;
/// # use rs_graph::classes::peterson;
/// #
/// let g = peterson::<LinkedListGraph>();
/// let weights = rs_graph::EdgeVec::new(&g, 0);
/// assert!(g.edges().all(|e| weights[e] == 0));
/// ```
///
/// Create a vector with all values initialized by an initializing function.
///
/// ```
/// # use rs_graph::LinkedListGraph;
/// # use rs_graph::traits::*;
/// # use rs_graph::classes::peterson;
/// #
/// let g = peterson::<LinkedListGraph>();
/// let weights = rs_graph::vec::EdgeVec::new_with(&g, |e| g.edge_id(e));
/// assert!(g.edges().all(|e| weights[e] == g.edge_id(e)));
/// ```
pub type EdgeVec<'a, G, T> = ItemVec<EdgeIndexer<'a, G>, T>;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::classes::peterson;
    use crate::traits::*;
    use crate::LinkedListGraph;

    #[test]
    fn test_iter() {
        let g = peterson::<LinkedListGraph>();
        let mut weights = EdgeVec::new_with(&g, |e| g.edge_id(e));

        for (i, (_, &x)) in weights.iter().enumerate() {
            assert_eq!(i, x);
        }

        for (_, x) in weights.iter_mut() {
            *x = *x + 1;
        }

        for (i, (_, &x)) in weights.iter().enumerate() {
            assert_eq!(i + 1, x);
        }
    }

    #[test]
    fn test_map() {
        let g = peterson::<LinkedListGraph>();
        let weights = EdgeVec::new_with(&g, |e| g.edge_id(e));

        let new_weights = weights.map(|(_, i)| i + 1);
        for e in g.edges() {
            assert_eq!(weights[e] + 1, new_weights[e]);
        }

        let new_weights = new_weights.map(|(_, i)| i * 2);
        for e in g.edges() {
            assert_eq!(2 * (weights[e] + 1), new_weights[e]);
        }
    }
}