summaryrefslogtreecommitdiff
path: root/graph/src/adset.rs
blob: adf2aafcf24edbb8fa1db4103939173a2ef737db (plain)
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
439
440
441
442
443
444
445
446
447
#![warn(missing_docs)]
//! This file implements a data type that implements the trait
//! [`Graph`][super::Graph].  This data type represents graphs using
//! adjacency sets internally.
//!
//! I need this because the derivatives languages should not allow
//! duplications of languages, so it is more convenient if the
//! underlying graph type **cannot** represent duplicate edges.

use std::ops::{Deref, DerefMut};

use crate::{builder::Builder, error::Error, ExtGraph, Graph};

// If one wants to use another implementation for a set, import that
// as Set, and nothing else needs to be changed, ideally.
use std::collections::{hash_set::Iter, HashSet as Set};

#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
struct ASEdge {
    to: usize,
}

impl ASEdge {
    fn new(to: usize) -> Self {
        Self { to }
    }
}

#[derive(Debug, Clone, Default)]
struct ASNode {
    children: Set<ASEdge>,
}

impl ASNode {
    fn new(children: Set<ASEdge>) -> Self {
        Self { children }
    }
}

/// The graph implemented using adjacency sets.
#[derive(Debug, Clone, Default)]
pub struct ASGraph {
    nodes: Vec<ASNode>,
}

/// A delegation of iterators.
///
/// This is here to avoid using a boxed pointer, in order to save some
/// allocations.
pub struct ASIter<'a> {
    iter: Iter<'a, ASEdge>,
}

impl<'a> Iterator for ASIter<'a> {
    type Item = usize;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next().map(|edge| edge.to)
    }

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

impl<'a> ExactSizeIterator for ASIter<'a> {
    fn len(&self) -> usize {
        self.iter.len()
    }
}

impl Graph for ASGraph {
    type Iter<'a> = ASIter<'a>;

    #[inline]
    fn is_empty(&self) -> bool {
        self.nodes.is_empty()
    }

    #[inline]
    fn nodes_len(&self) -> usize {
        self.nodes.len()
    }

    fn children_of(&self, node_id: usize) -> Result<Self::Iter<'_>, Error> {
        match self.nodes.get(node_id) {
            Some(node) => {
                let iter = node.children.iter();
                Ok(Self::Iter { iter })
            }
            None => Err(Error::IndexOutOfBounds(node_id, self.nodes_len())),
        }
    }

    #[inline]
    fn degree(&self, node_id: usize) -> Result<usize, Error> {
        match self.nodes.get(node_id) {
            Some(node) => Ok(node.children.len()),
            None => Err(Error::IndexOutOfBounds(node_id, self.nodes_len())),
        }
    }

    #[inline]
    fn is_empty_node(&self, node_id: usize) -> Result<bool, Error> {
        match self.nodes.get(node_id) {
            Some(node) => Ok(node.children.is_empty()),
            None => Err(Error::IndexOutOfBounds(node_id, self.nodes_len())),
        }
    }

    #[inline]
    fn has_edge(&self, source: usize, target: usize) -> Result<bool, Error> {
        if !self.has_node(source) {
            Err(Error::IndexOutOfBounds(source, self.nodes_len()))
        } else if !self.has_node(target) {
            Err(Error::IndexOutOfBounds(target, self.nodes_len()))
        } else {
            Ok(self
                .nodes
                .get(source)
                .unwrap()
                .children
                .contains(&ASEdge::new(target)))
        }
    }

    #[inline]
    fn replace_by_builder(&mut self, builder: impl Builder<Result = Self>) {
        let graph = builder.build();

        self.nodes = graph.nodes;
    }
}

impl ExtGraph for ASGraph {
    fn extend(&mut self, edges: impl IntoIterator<Item = usize>) -> Result<usize, Error> {
        let mut new_node_children = Set::default();

        for edge_to in edges.into_iter() {
            if !self.has_node(edge_to) {
                return Err(Error::IndexOutOfBounds(edge_to, self.nodes_len()));
            }

            new_node_children.insert(ASEdge::new(edge_to));
        }

        let new_node = ASNode::new(new_node_children);

        self.nodes.push(new_node);

        Ok(self.nodes.len() - 1)
    }
}

// Builder for this implementation of graph

/// A builder for adjacency set graphs.
#[derive(Debug, Default, Clone)]
pub struct ASGBuilder(ASGraph);

impl Deref for ASGBuilder {
    type Target = ASGraph;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for ASGBuilder {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl Builder for ASGBuilder {
    type Label = ();

    type Result = ASGraph;

    #[inline]
    fn with_capacity(size: usize) -> Self {
        Self(ASGraph {
            nodes: Vec::with_capacity(size),
        })
    }

    #[inline]
    fn add_vertex(&mut self) -> usize {
        self.nodes.push(ASNode::default());
        self.nodes.len() - 1
    }

    #[inline]
    fn add_vertices(&mut self, n: usize) {
        self.nodes
            .extend(std::iter::repeat_with(ASNode::default).take(n));
    }

    fn add_edge(&mut self, source: usize, target: usize, _label: Self::Label) -> Result<(), Error> {
        let nodes_len = self.nodes.len();

        let source_children = self
            .nodes
            .get_mut(source)
            .ok_or(Error::IndexOutOfBounds(source, nodes_len))?;

        if !(0..nodes_len).contains(&target) {
            return Err(Error::IndexOutOfBounds(target, nodes_len));
        }

        source_children.children.insert(ASEdge::new(target));

        Ok(())
    }

    fn remove_edge<F>(&mut self, source: usize, target: usize, _predicate: F) -> Result<(), Error>
    where
        F: Fn(Self::Label) -> bool,
    {
        let nodes_len = self.nodes.len();

        let source_children = self
            .nodes
            .get_mut(source)
            .ok_or(Error::IndexOutOfBounds(source, nodes_len))?;

        if !(0..nodes_len).contains(&target) {
            return Err(Error::IndexOutOfBounds(target, nodes_len));
        }

        source_children.children.remove(&ASEdge::new(target));

        Ok(())
    }

    fn build(self) -> Self::Result {
        self.0
    }

    fn build_ref(&self) -> Self::Result {
        self.0.clone()
    }
}

#[cfg(test)]
mod asgraph_test {
    use super::*;

    #[test]
    fn test_graph_apis() -> Result<(), Error> {
        let mut graph = ASGraph::default();

        assert!(graph.is_empty());

        graph.extend(std::iter::empty())?;

        graph.extend([0].iter().copied())?;
        graph.extend([0, 1].iter().copied())?;
        graph.extend([0, 2].iter().copied())?;
        graph.extend([1, 2].iter().copied())?;
        graph.extend([1, 2, 3].iter().copied())?;

        let graph = graph;

        assert_eq!(graph.nodes_len(), 6);

        assert_eq!(graph.children_of(5)?.collect::<Set<_>>(), {
            let mut set = Set::default();
            set.insert(1);
            set.insert(3);
            set.insert(2);
            set
        });

        assert_eq!(graph.degree(4)?, 2);

        assert!(graph.is_empty_node(0)?);
        assert!(!graph.is_empty_node(1)?);

        assert!(graph.has_edge(3, 2)?);
        assert!(!graph.has_edge(3, 1)?);
        assert_eq!(graph.has_edge(3, 6), Err(Error::IndexOutOfBounds(6, 6)));

        Ok(())
    }

    #[test]
    fn test_extending_algraph_normal() -> Result<(), Error> {
        let mut graph = ASGraph::default();

        let new = graph.extend(std::iter::empty())?;

        println!("new index = {new}");

        println!("new graph = {graph:?}");

        let new = graph.extend([0].iter().copied())?;

        println!("new index = {new}");

        println!("new graph = {graph:?}");

        let new = graph.extend([0, 1].iter().copied())?;

        println!("new index = {new}");

        println!("new graph = {graph:?}");

        Ok(())
    }

    #[test]
    fn test_extending_algraph_error() -> Result<(), Error> {
        let mut graph = ASGraph::default();

        graph.extend(std::iter::empty())?;

        graph.extend([0].iter().copied())?;

        assert_eq!(
            graph.extend([2].iter().copied()),
            Err(Error::IndexOutOfBounds(2, 2))
        );

        Ok(())
    }
}

#[cfg(test)]
mod test_asgraph_builder {
    use super::*;

    #[test]
    fn test_builder() -> Result<(), Box<dyn std::error::Error>> {
        let mut builder = ASGBuilder::default();

        // Add five nodes
        builder.add_vertex();
        builder.add_vertex();
        builder.add_vertex();
        builder.add_vertex();
        builder.add_vertex();

        println!("five empty nodes: {builder:?}");

        // Link each node to its successor and link the last node with
        // the first one to form a cycle.
        for i in 0..5 {
            builder.add_edge(i, if i == 4 { 0 } else { i + 1 }, ())?;
        }

        println!("a cycle of five nodes: {builder:?}");

        // Remove the link from the last node to the first node.
        builder.remove_edge(4, 0, |_| true)?;

        println!("a line of five nodes: {builder:?}");

        // build a graph

        let graph = builder.build();

        println!("final graph: {graph:?}");

        Ok(())
    }

    #[test]
    fn test_errors() -> Result<(), Box<dyn std::error::Error>> {
        let mut builder = ASGBuilder::default();

        // Add five nodes
        builder.add_vertex();
        builder.add_vertex();
        builder.add_vertex();
        builder.add_vertex();
        builder.add_vertex();

        println!("five empty nodes: {builder:?}");

        // Errors in add_edge

        println!();
        println!("Testing errors in add_edge:");
        println!();

        assert!(matches!(
            builder.add_edge(0, 5, ()),
            Err(Error::IndexOutOfBounds(5, 5))
        ));

        println!("Right error for an index out of bounds as the target");

        assert!(matches!(
            builder.add_edge(10, 5, ()),
            Err(Error::IndexOutOfBounds(10, 5))
        ));

        println!("Right error for an index out of bounds as the source");

        assert!(matches!(
            builder.add_edge(10, 50, ()),
            Err(Error::IndexOutOfBounds(10, 5))
        ));

        println!("Right error for both indices out of bounds");

        // Errors in remove_edge

        println!();
        println!("Testing errors in remove_edge:");
        println!();

        assert!(matches!(
            builder.remove_edge(0, 5, |_| true),
            Err(Error::IndexOutOfBounds(5, 5))
        ));

        println!("Right error for an index out of bounds as the target");

        assert!(matches!(
            builder.remove_edge(10, 5, |_| true),
            Err(Error::IndexOutOfBounds(10, 5))
        ));

        println!("Right error for an index out of bounds as the source");

        assert!(matches!(
            builder.remove_edge(10, 50, |_| true),
            Err(Error::IndexOutOfBounds(10, 5))
        ));

        println!("Right error for both indices out of bounds");

        assert!(matches!(builder.remove_edge(0, 1, |_| true), Ok(()),));

        println!("No errors for removing a non-existing edge");

        println!();

        let graph = builder.build();

        println!("final graph: {graph:?}");

        Ok(())
    }
}