Merge pull request 'Initial release' (#1) from dev into main
Reviewed-on: #1
This commit was merged in pull request #1.
This commit is contained in:
Generated
+8
@@ -0,0 +1,8 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Editor-based HTTP Client requests
|
||||
/httpRequests/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
Generated
+12
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="EMPTY_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/tests" isTestSource="true" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/target" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
Generated
+8
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/grapherity.iml" filepath="$PROJECT_DIR$/.idea/grapherity.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
Generated
+7
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="" vcs="Git" />
|
||||
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1,10 @@
|
||||
# Contributing
|
||||
|
||||
By submitting a contribution (pull request, patch, or commit), you agree that:
|
||||
|
||||
1. You have the right to license the contribution.
|
||||
2. Your contribution is licensed under the project's dual license:
|
||||
- MIT License
|
||||
- Apache License 2.0
|
||||
|
||||
If you do not agree, please do not submit contributions.
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "grapherity"
|
||||
version = "0.1.0"
|
||||
authors = ["Stefan Müller"]
|
||||
edition = "2024"
|
||||
rust-version = "1.85.0"
|
||||
description = "Graph models and algorithms"
|
||||
repository = "https://git.aksdb.de/warrence/grapherity"
|
||||
license = "MIT OR Apache-2.0"
|
||||
keywords = ["graph", "graph-algorithms"]
|
||||
categories = ["algorithms", "data-structures", "mathematics"]
|
||||
|
||||
[dependencies]
|
||||
typed-generational-arena = "0.2.9"
|
||||
@@ -1,9 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025 warrence
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
Copyright 2025-2026 Stefan Müller
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the “Software”), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -0,0 +1,7 @@
|
||||
This product includes software developed by Stefan Müller.
|
||||
|
||||
Copyright 2025-2026 Stefan Müller
|
||||
|
||||
Licensed under the MIT License and the Apache License 2.0.
|
||||
|
||||
No additional attribution notices.
|
||||
@@ -1,3 +1,18 @@
|
||||
# grapherity
|
||||
|
||||
Graph editing, algorithms, and visualization
|
||||
Library for graph models and algorithms.
|
||||
|
||||
This library is still experimental and its API may therefore change frequently.
|
||||
|
||||
## License
|
||||
|
||||
This project is dual-licensed under the terms of both:
|
||||
|
||||
- Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or https://www.apache.org/licenses/LICENSE-2.0)
|
||||
- MIT license ([LICENSE-MIT](LICENSE-MIT) or https://opensource.org/license/mit)
|
||||
|
||||
You may choose either license for your use of this software.
|
||||
|
||||
### Contributions
|
||||
|
||||
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
use std::cmp::Ordering;
|
||||
use std::collections::{BinaryHeap, VecDeque};
|
||||
|
||||
use crate::maps::VertexMap;
|
||||
use crate::traits::{GraphTopology, IncidenceCursor};
|
||||
|
||||
#[derive(PartialEq, Eq)]
|
||||
struct DistanceOrderedVertex<V> {
|
||||
distance: u32,
|
||||
vertex: V,
|
||||
}
|
||||
|
||||
impl<V: Eq> PartialOrd for DistanceOrderedVertex<V> {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: Eq> Ord for DistanceOrderedVertex<V> {
|
||||
fn cmp(&self, other: &Self) -> Ordering {
|
||||
other.distance.cmp(&self.distance)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DijkstraResult<V: Copy> {
|
||||
pub distances: VertexMap<V, Option<u32>>,
|
||||
pub predecessors: VertexMap<V, Option<V>>,
|
||||
}
|
||||
|
||||
// TODO: Generalize the return type of the weight function.
|
||||
pub fn dijkstra<G, W>(graph: &G, source: G::Vertex, weight: W) -> DijkstraResult<G::Vertex>
|
||||
where
|
||||
G: GraphTopology,
|
||||
W: Fn(G::Edge) -> u32,
|
||||
{
|
||||
let mut predecessors = graph.vertex_map(None);
|
||||
let distances = dijkstra_impl(graph, source, weight, |adjacent, predecessor| {
|
||||
predecessors[adjacent] = Some(predecessor);
|
||||
});
|
||||
DijkstraResult {
|
||||
distances,
|
||||
predecessors,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dijkstra_unweighted<G>(graph: &G, source: G::Vertex) -> DijkstraResult<G::Vertex>
|
||||
where
|
||||
G: GraphTopology,
|
||||
{
|
||||
dijkstra(graph, source, |_| 1)
|
||||
}
|
||||
|
||||
pub fn dijkstra_distances<G, W>(
|
||||
graph: &G,
|
||||
source: G::Vertex,
|
||||
weight: W,
|
||||
) -> VertexMap<G::Vertex, Option<u32>>
|
||||
where
|
||||
G: GraphTopology,
|
||||
W: Fn(G::Edge) -> u32,
|
||||
{
|
||||
dijkstra_impl(graph, source, weight, |_, _| {})
|
||||
}
|
||||
|
||||
pub fn dijkstra_distances_unweighted<G>(
|
||||
graph: &G,
|
||||
source: G::Vertex,
|
||||
) -> VertexMap<G::Vertex, Option<u32>>
|
||||
where
|
||||
G: GraphTopology,
|
||||
{
|
||||
dijkstra_distances(graph, source, |_| 1)
|
||||
}
|
||||
|
||||
fn dijkstra_impl<G, W, F>(
|
||||
graph: &G,
|
||||
source: G::Vertex,
|
||||
weight: W,
|
||||
mut on_relax: F,
|
||||
) -> VertexMap<G::Vertex, Option<u32>>
|
||||
where
|
||||
G: GraphTopology,
|
||||
W: Fn(G::Edge) -> u32,
|
||||
F: FnMut(G::Vertex, G::Vertex),
|
||||
{
|
||||
let mut distances = graph.vertex_map(None);
|
||||
let mut heap = BinaryHeap::new();
|
||||
|
||||
distances[source] = Some(0);
|
||||
heap.push(DistanceOrderedVertex {
|
||||
vertex: source,
|
||||
distance: 0,
|
||||
});
|
||||
|
||||
while let Some(v) = heap.pop() {
|
||||
for incidence in graph.incidences(v.vertex) {
|
||||
let new_distance = distances[v.vertex].unwrap() + weight(incidence.1);
|
||||
if match distances[incidence.0] {
|
||||
None => true,
|
||||
Some(old_distance) if old_distance > new_distance => true,
|
||||
_ => false,
|
||||
} {
|
||||
distances[incidence.0] = Some(new_distance);
|
||||
on_relax(incidence.0, v.vertex);
|
||||
heap.push(DistanceOrderedVertex {
|
||||
vertex: incidence.0,
|
||||
distance: new_distance,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
distances
|
||||
}
|
||||
|
||||
pub struct BfsResult<V: Copy> {
|
||||
pub distances: VertexMap<V, Option<u32>>,
|
||||
pub predecessors: VertexMap<V, Option<V>>,
|
||||
}
|
||||
|
||||
pub fn bfs<G>(graph: &G, source: G::Vertex) -> BfsResult<G::Vertex>
|
||||
where
|
||||
G: GraphTopology,
|
||||
{
|
||||
let mut predecessors = graph.vertex_map(None);
|
||||
let (distances, _) = bfs_impl(graph, source, |neighbor, predecessor| {
|
||||
predecessors[neighbor] = Some(predecessor);
|
||||
true
|
||||
});
|
||||
BfsResult {
|
||||
distances,
|
||||
predecessors,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bfs_distances<G>(graph: &G, source: G::Vertex) -> VertexMap<G::Vertex, Option<u32>>
|
||||
where
|
||||
G: GraphTopology,
|
||||
{
|
||||
bfs_impl(graph, source, |_, _| true).0
|
||||
}
|
||||
|
||||
pub fn bfs_find<G>(graph: &G, source: G::Vertex, target: G::Vertex) -> Option<u32>
|
||||
where
|
||||
G: GraphTopology,
|
||||
{
|
||||
bfs_find_where(graph, source, |v| v == target).map(|(_, distance)| distance)
|
||||
}
|
||||
|
||||
pub fn bfs_find_where<G, P>(graph: &G, source: G::Vertex, predicate: P) -> Option<(G::Vertex, u32)>
|
||||
where
|
||||
G: GraphTopology,
|
||||
P: Fn(G::Vertex) -> bool,
|
||||
{
|
||||
if predicate(source) {
|
||||
return Some((source, 0));
|
||||
}
|
||||
bfs_impl(graph, source, |neighbor, _| !predicate(neighbor)).1
|
||||
}
|
||||
|
||||
fn bfs_impl<G, F>(
|
||||
graph: &G,
|
||||
source: G::Vertex,
|
||||
mut on_discover: F,
|
||||
) -> (VertexMap<G::Vertex, Option<u32>>, Option<(G::Vertex, u32)>)
|
||||
where
|
||||
G: GraphTopology,
|
||||
F: FnMut(G::Vertex, G::Vertex) -> bool,
|
||||
{
|
||||
let mut distances = graph.vertex_map(None);
|
||||
let mut queue = VecDeque::new();
|
||||
|
||||
distances[source] = Some(0);
|
||||
queue.push_back(source);
|
||||
|
||||
while let Some(v) = queue.pop_front() {
|
||||
for neighbor in graph.adjacent_vertices(v) {
|
||||
if distances[neighbor].is_none() {
|
||||
let distance = distances[v].unwrap() + 1;
|
||||
distances[neighbor] = Some(distance);
|
||||
if !on_discover(neighbor, v) {
|
||||
return (distances, Some((neighbor, distance)));
|
||||
}
|
||||
queue.push_back(neighbor);
|
||||
}
|
||||
}
|
||||
}
|
||||
(distances, None)
|
||||
}
|
||||
|
||||
pub struct DfsResult<V: Copy> {
|
||||
pub visited: VertexMap<V, bool>,
|
||||
pub predecessors: VertexMap<V, Option<V>>,
|
||||
}
|
||||
|
||||
pub fn dfs<G>(graph: &G, source: G::Vertex) -> DfsResult<G::Vertex>
|
||||
where
|
||||
G: GraphTopology,
|
||||
{
|
||||
let mut predecessors = graph.vertex_map(None);
|
||||
let (visited, _) = dfs_impl(graph, source, |neighbor, predecessor| {
|
||||
predecessors[neighbor] = Some(predecessor);
|
||||
true
|
||||
});
|
||||
DfsResult {
|
||||
visited,
|
||||
predecessors,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dfs_visited<G>(graph: &G, source: G::Vertex) -> VertexMap<G::Vertex, bool>
|
||||
where
|
||||
G: GraphTopology,
|
||||
{
|
||||
dfs_impl(graph, source, |_, _| true).0
|
||||
}
|
||||
|
||||
pub fn dfs_find<G>(graph: &G, source: G::Vertex, target: G::Vertex) -> bool
|
||||
where
|
||||
G: GraphTopology,
|
||||
{
|
||||
dfs_find_where(graph, source, |v| v == target).is_some()
|
||||
}
|
||||
|
||||
pub fn dfs_find_where<G, P>(graph: &G, source: G::Vertex, predicate: P) -> Option<G::Vertex>
|
||||
where
|
||||
G: GraphTopology,
|
||||
P: Fn(G::Vertex) -> bool,
|
||||
{
|
||||
if predicate(source) {
|
||||
return Some(source);
|
||||
}
|
||||
dfs_impl(graph, source, |neighbor, _| !predicate(neighbor)).1
|
||||
}
|
||||
|
||||
fn dfs_impl<G, F>(
|
||||
graph: &G,
|
||||
source: G::Vertex,
|
||||
mut on_discover: F,
|
||||
) -> (VertexMap<G::Vertex, bool>, Option<G::Vertex>)
|
||||
where
|
||||
G: GraphTopology,
|
||||
F: FnMut(G::Vertex, G::Vertex) -> bool,
|
||||
{
|
||||
let mut visited = graph.vertex_map(false);
|
||||
visited[source] = true;
|
||||
let mut stack = vec![(source, None::<G::Vertex>)];
|
||||
|
||||
while let Some((v, predecessor)) = stack.pop() {
|
||||
if let Some(p) = predecessor {
|
||||
if !on_discover(v, p) {
|
||||
return (visited, Some(v));
|
||||
}
|
||||
}
|
||||
for neighbor in graph.adjacent_vertices(v) {
|
||||
if !visited[neighbor] {
|
||||
visited[neighbor] = true;
|
||||
stack.push((neighbor, Some(v)));
|
||||
}
|
||||
}
|
||||
}
|
||||
(visited, None)
|
||||
}
|
||||
|
||||
pub fn find_path<G>(graph: &G, source: G::Vertex, target: G::Vertex) -> Option<Vec<G::Edge>>
|
||||
where
|
||||
G: GraphTopology,
|
||||
{
|
||||
find_path_where(graph, source, |v| v == target)
|
||||
}
|
||||
|
||||
pub fn find_path_where<G, P>(graph: &G, source: G::Vertex, predicate: P) -> Option<Vec<G::Edge>>
|
||||
where
|
||||
G: GraphTopology,
|
||||
P: Fn(G::Vertex) -> bool,
|
||||
{
|
||||
if predicate(source) {
|
||||
return Some(vec![]);
|
||||
}
|
||||
|
||||
let mut visited = graph.vertex_map(false);
|
||||
visited[source] = true;
|
||||
|
||||
struct Frame<G: GraphTopology> {
|
||||
arrival_edge: Option<G::Edge>,
|
||||
cursor: G::IncidenceCursor,
|
||||
}
|
||||
|
||||
let mut stack: Vec<Frame<G>> = vec![Frame {
|
||||
arrival_edge: None,
|
||||
cursor: graph.incidence_cursor(source),
|
||||
}];
|
||||
|
||||
while let Some(frame) = stack.last_mut() {
|
||||
match frame.cursor.next(graph) {
|
||||
None => {
|
||||
stack.pop();
|
||||
}
|
||||
Some((neighbor, edge)) => {
|
||||
if predicate(neighbor) {
|
||||
let mut path: Vec<G::Edge> =
|
||||
stack.iter().filter_map(|f| f.arrival_edge).collect();
|
||||
path.push(edge);
|
||||
return Some(path);
|
||||
}
|
||||
if !visited[neighbor] {
|
||||
visited[neighbor] = true;
|
||||
stack.push(Frame {
|
||||
arrival_edge: Some(edge),
|
||||
cursor: graph.incidence_cursor(neighbor),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
pub mod algorithms;
|
||||
pub mod maps;
|
||||
pub mod models;
|
||||
pub mod traits;
|
||||
|
||||
mod testing;
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
use std::ops::{Index, IndexMut};
|
||||
|
||||
use crate::traits::GraphTopology;
|
||||
|
||||
pub struct VertexMap<V: Copy, T: Clone> {
|
||||
inner: EntityMap<V, T>,
|
||||
}
|
||||
|
||||
impl<V: Copy, T: Clone> VertexMap<V, T> {
|
||||
pub fn new(default: T, to_index: fn(V) -> usize, capacity: usize) -> Self {
|
||||
Self {
|
||||
inner: EntityMap::new(default, to_index, capacity),
|
||||
}
|
||||
}
|
||||
|
||||
// Reads beyond len() are valid and return the default value.
|
||||
pub fn len(&self) -> usize {
|
||||
self.inner.len()
|
||||
}
|
||||
|
||||
pub fn sync<G: GraphTopology<Vertex = V>>(&mut self, graph: &G) {
|
||||
self.inner.resize(graph.vertex_capacity());
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: Copy, T: Clone> Index<V> for VertexMap<V, T> {
|
||||
type Output = T;
|
||||
|
||||
fn index(&self, v: V) -> &T {
|
||||
&self.inner[v]
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: Copy, T: Clone> IndexMut<V> for VertexMap<V, T> {
|
||||
fn index_mut(&mut self, v: V) -> &mut T {
|
||||
&mut self.inner[v]
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EdgeMap<E: Copy, T: Clone> {
|
||||
inner: EntityMap<E, T>,
|
||||
}
|
||||
|
||||
impl<E: Copy, T: Clone> EdgeMap<E, T> {
|
||||
pub fn new(default: T, to_index: fn(E) -> usize, capacity: usize) -> Self {
|
||||
Self {
|
||||
inner: EntityMap::new(default, to_index, capacity),
|
||||
}
|
||||
}
|
||||
|
||||
// Reads beyond len() are valid and return the default value.
|
||||
pub fn len(&self) -> usize {
|
||||
self.inner.len()
|
||||
}
|
||||
|
||||
pub fn sync<G: GraphTopology<Edge = E>>(&mut self, graph: &G) {
|
||||
self.inner.resize(graph.edge_capacity());
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: Copy, T: Clone> Index<E> for EdgeMap<E, T> {
|
||||
type Output = T;
|
||||
|
||||
fn index(&self, e: E) -> &T {
|
||||
&self.inner[e]
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: Copy, T: Clone> IndexMut<E> for EdgeMap<E, T> {
|
||||
fn index_mut(&mut self, e: E) -> &mut T {
|
||||
&mut self.inner[e]
|
||||
}
|
||||
}
|
||||
|
||||
struct EntityMap<E: Copy, T: Clone> {
|
||||
data: Vec<T>,
|
||||
default: T,
|
||||
to_index: fn(E) -> usize,
|
||||
}
|
||||
|
||||
impl<E: Copy, T: Clone> EntityMap<E, T> {
|
||||
pub fn new(default: T, to_index: fn(E) -> usize, capacity: usize) -> Self {
|
||||
Self {
|
||||
data: vec![default.clone(); capacity],
|
||||
default,
|
||||
to_index,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.data.len()
|
||||
}
|
||||
|
||||
pub fn resize(&mut self, capacity: usize) {
|
||||
if capacity > self.data.len() {
|
||||
self.data.resize(capacity, self.default.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: Copy, T: Clone> Index<E> for EntityMap<E, T> {
|
||||
type Output = T;
|
||||
|
||||
fn index(&self, e: E) -> &T {
|
||||
let i = (self.to_index)(e);
|
||||
if i < self.data.len() {
|
||||
&self.data[i]
|
||||
} else {
|
||||
&self.default
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: Copy, T: Clone> IndexMut<E> for EntityMap<E, T> {
|
||||
fn index_mut(&mut self, e: E) -> &mut T {
|
||||
let i = (self.to_index)(e);
|
||||
if i >= self.data.len() {
|
||||
self.data.resize(i + 1, self.default.clone());
|
||||
}
|
||||
&mut self.data[i]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod append_graph;
|
||||
pub mod graph;
|
||||
@@ -0,0 +1,185 @@
|
||||
use crate::maps::{EdgeMap, VertexMap};
|
||||
use crate::traits::{GraphTopology, IncidenceCursor};
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
||||
pub struct Vertex(usize);
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
||||
pub struct Incidence(usize);
|
||||
|
||||
impl Incidence {
|
||||
fn normalize(&self) -> Self {
|
||||
Self(self.0 & !1)
|
||||
}
|
||||
}
|
||||
|
||||
struct VertexIncidenceHeader {
|
||||
incidence_count: usize,
|
||||
first_incidence: Option<Incidence>,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
struct IncidenceEntry {
|
||||
next: Option<Incidence>,
|
||||
adjacent: Vertex,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct AppendGraphIncidenceCursor {
|
||||
incidence: Option<Incidence>,
|
||||
}
|
||||
|
||||
impl IncidenceCursor<AppendGraph> for AppendGraphIncidenceCursor {
|
||||
fn next(&mut self, graph: &AppendGraph) -> Option<(Vertex, Incidence)> {
|
||||
graph.step_incidence(&mut self.incidence)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AppendGraph {
|
||||
vertices: Vec<VertexIncidenceHeader>,
|
||||
incidences: Vec<IncidenceEntry>,
|
||||
}
|
||||
|
||||
impl AppendGraph {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
vertices: vec![],
|
||||
incidences: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
// Adds a single incidence of an edge, which is composed by two such incidences, to the
|
||||
// incidences vector.
|
||||
fn add_incidence(&mut self, v1: Vertex, v2: Vertex) {
|
||||
self.incidences.push(IncidenceEntry {
|
||||
next: self.vertices[v1.0].first_incidence.take(),
|
||||
adjacent: v2,
|
||||
});
|
||||
self.vertices[v1.0].incidence_count += 1;
|
||||
self.vertices[v1.0].first_incidence = Some(Incidence(self.incidences.len() - 1));
|
||||
}
|
||||
|
||||
fn raw_incidences(&self, v: Vertex) -> impl Iterator<Item = (Vertex, Incidence)> {
|
||||
let mut incidence = self.vertices[v.0].first_incidence;
|
||||
std::iter::from_fn(move || self.step_incidence(&mut incidence))
|
||||
}
|
||||
|
||||
fn step_incidence(&self, incidence: &mut Option<Incidence>) -> Option<(Vertex, Incidence)> {
|
||||
let current = (*incidence)?;
|
||||
let entry = self.incidences[current.0];
|
||||
*incidence = entry.next;
|
||||
Some((entry.adjacent, current))
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for AppendGraph {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl GraphTopology for AppendGraph {
|
||||
type Vertex = Vertex;
|
||||
type Edge = Incidence;
|
||||
type IncidenceCursor = AppendGraphIncidenceCursor;
|
||||
|
||||
fn vertex_count(&self) -> usize {
|
||||
self.vertices.len()
|
||||
}
|
||||
|
||||
fn vertex_capacity(&self) -> usize {
|
||||
self.vertices.len()
|
||||
}
|
||||
|
||||
fn vertex_map<T: Clone>(&self, default: T) -> VertexMap<Self::Vertex, T> {
|
||||
VertexMap::new(default, |v| v.0, self.vertex_capacity())
|
||||
}
|
||||
|
||||
fn edge_count(&self) -> usize {
|
||||
self.incidences.len() / 2
|
||||
}
|
||||
|
||||
fn edge_capacity(&self) -> usize {
|
||||
self.incidences.len() / 2
|
||||
}
|
||||
|
||||
fn edge_map<T: Clone>(&self, default: T) -> EdgeMap<Self::Edge, T> {
|
||||
EdgeMap::new(default, |e| e.0 / 2, self.edge_capacity())
|
||||
}
|
||||
|
||||
fn degree(&self, v: Self::Vertex) -> usize {
|
||||
self.vertices[v.0].incidence_count
|
||||
}
|
||||
|
||||
fn are_adjacent(&self, v1: Self::Vertex, v2: Self::Vertex) -> bool {
|
||||
self.adjacent_vertices(v1).any(|x| x == v2)
|
||||
}
|
||||
|
||||
fn vertices(&self) -> impl Iterator<Item = Self::Vertex> {
|
||||
(0..self.vertices.len()).map(Vertex)
|
||||
}
|
||||
|
||||
fn adjacent_vertices(&self, v: Self::Vertex) -> impl Iterator<Item = Self::Vertex> {
|
||||
self.raw_incidences(v).map(|(v, _)| v)
|
||||
}
|
||||
|
||||
fn incident_vertices(&self, e: Self::Edge) -> (Self::Vertex, Self::Vertex) {
|
||||
let v2 = self.incidences[e.0].adjacent;
|
||||
let v1 = self.incidences[e.0 ^ 1].adjacent;
|
||||
(v1, v2)
|
||||
}
|
||||
|
||||
fn edges(&self) -> impl Iterator<Item = Self::Edge> {
|
||||
(0..self.incidences.len()).step_by(2).map(Incidence)
|
||||
}
|
||||
|
||||
fn incident_edges(&self, v: Self::Vertex) -> impl Iterator<Item = Self::Edge> {
|
||||
self.raw_incidences(v).map(|(_, e)| e.normalize())
|
||||
}
|
||||
|
||||
fn incidences(&self, v: Self::Vertex) -> impl Iterator<Item = (Self::Vertex, Self::Edge)> {
|
||||
self.raw_incidences(v).map(|(v, e)| (v, e.normalize()))
|
||||
}
|
||||
|
||||
fn incidence_cursor(&self, v: Self::Vertex) -> Self::IncidenceCursor {
|
||||
AppendGraphIncidenceCursor {
|
||||
incidence: self.vertices[v.0].first_incidence,
|
||||
}
|
||||
}
|
||||
|
||||
fn add_vertex(&mut self) -> Self::Vertex {
|
||||
self.vertices.push(VertexIncidenceHeader {
|
||||
incidence_count: 0,
|
||||
first_incidence: None,
|
||||
});
|
||||
Vertex(self.vertices.len() - 1)
|
||||
}
|
||||
|
||||
fn add_edge(&mut self, v1: Self::Vertex, v2: Self::Vertex) -> Self::Edge {
|
||||
self.add_incidence(v1, v2);
|
||||
self.add_incidence(v2, v1);
|
||||
Incidence(self.incidences.len() - 2)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
crate::graph_topology_test_fixtures!(AppendGraph);
|
||||
crate::graph_topology_tests!(AppendGraph);
|
||||
|
||||
#[test]
|
||||
fn incident_vertices_paired_index() {
|
||||
let mut graph = AppendGraph::new();
|
||||
let v1 = graph.add_vertex();
|
||||
let v2 = graph.add_vertex();
|
||||
let e = graph.add_edge(v1, v2);
|
||||
let f = Incidence(e.0 + 1);
|
||||
let (u1, u2) = graph.incident_vertices(f);
|
||||
assert!(
|
||||
(u1 == v1 && u2 == v2) || (u1 == v2 && u2 == v1),
|
||||
"unexpected incident vertices {u1:?} and {u2:?} for edge {f:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
use typed_generational_arena::{Arena, Index};
|
||||
|
||||
use crate::maps::{EdgeMap, VertexMap};
|
||||
use crate::traits::{GraphTopology, GraphTopologyDeletion, IncidenceCursor};
|
||||
|
||||
type Vertex = Index<VertexIncidenceHeader, usize, usize>;
|
||||
|
||||
type Edge = Index<IncidenceEntry, usize, usize>;
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
||||
struct VertexSlot(usize);
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
||||
struct IncidenceSlot(usize);
|
||||
|
||||
pub struct VertexIncidenceHeader {
|
||||
incidence_count: usize,
|
||||
first_incidence: Option<IncidenceSlot>,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct IncidenceEntry {
|
||||
next: Option<IncidenceSlot>,
|
||||
adjacent: VertexSlot,
|
||||
}
|
||||
|
||||
struct IncidentEdgeCursor {
|
||||
incidence: Option<IncidenceSlot>,
|
||||
}
|
||||
|
||||
impl IncidentEdgeCursor {
|
||||
fn next(&mut self, graph: &Graph) -> Option<Edge> {
|
||||
graph.step_incidence(&mut self.incidence).map(|(_, e)| e)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct GraphIncidenceCursor {
|
||||
incidence: Option<IncidenceSlot>,
|
||||
}
|
||||
|
||||
impl IncidenceCursor<Graph> for GraphIncidenceCursor {
|
||||
fn next(&mut self, graph: &Graph) -> Option<(Vertex, Edge)> {
|
||||
graph
|
||||
.step_incidence(&mut self.incidence)
|
||||
.map(|(vs, e)| (graph.vertices.get_idx(vs.0).unwrap(), e))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Graph {
|
||||
// TODO: Arena index and generation types could be externalized to Graph.
|
||||
vertices: Arena<VertexIncidenceHeader, usize, usize>,
|
||||
incidences: Arena<IncidenceEntry, usize, usize>,
|
||||
}
|
||||
|
||||
impl Graph {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
vertices: Arena::new(),
|
||||
incidences: Arena::new(),
|
||||
}
|
||||
}
|
||||
|
||||
// Adds a single incidence of an edge, which is composed by two such incidences, to the
|
||||
// incidences arena, and returns its index.
|
||||
fn add_incidence(&mut self, v1: Vertex, v2: Vertex) -> Edge {
|
||||
let edge = self.incidences.insert(IncidenceEntry {
|
||||
next: self.vertices[v1].first_incidence.take(),
|
||||
adjacent: VertexSlot(v2.arr_idx()),
|
||||
});
|
||||
self.vertices[v1].incidence_count += 1;
|
||||
self.vertices[v1].first_incidence = Some(IncidenceSlot(edge.arr_idx()));
|
||||
edge
|
||||
}
|
||||
|
||||
fn remove_incidence_pair(&mut self, e: Edge) -> (Edge, IncidenceEntry, IncidenceEntry) {
|
||||
let f = self
|
||||
.incidences
|
||||
.get_idx(e.arr_idx() ^ 1)
|
||||
.expect("invalid paired incidence index, corrupt internal data state");
|
||||
let e_entry = self
|
||||
.incidences
|
||||
.remove(e)
|
||||
.expect("attempt to delete an invalid edge");
|
||||
let f_entry = self
|
||||
.incidences
|
||||
.remove(f)
|
||||
.expect("cannot read paired incidence, corrupt internal data state");
|
||||
(f, e_entry, f_entry)
|
||||
}
|
||||
|
||||
// Updates the source vertex incidence list after the incidence "e" was deleted from the
|
||||
// incidence arena. "next" is the next incidence after "e" in the source vertex incidence list.
|
||||
fn update_incidence_list(
|
||||
&mut self,
|
||||
e: Edge,
|
||||
source: VertexSlot,
|
||||
next: Option<IncidenceSlot>,
|
||||
is_loop: bool,
|
||||
) {
|
||||
let source_vertex = self
|
||||
.vertices
|
||||
.get_idx(source.0)
|
||||
.expect("missing incident vertex, corrupt internal data state");
|
||||
let vertex_header = &mut self.vertices[source_vertex];
|
||||
vertex_header.incidence_count -= if is_loop { 2 } else { 1 };
|
||||
let first = vertex_header
|
||||
.first_incidence
|
||||
.expect("incident vertex without incidences, corrupt internal data state");
|
||||
if first.0 == e.arr_idx() {
|
||||
vertex_header.first_incidence = next;
|
||||
} else {
|
||||
let graph: &Graph = self;
|
||||
let (_, previous) = self
|
||||
.raw_incidences(source_vertex)
|
||||
.find(|(_, f)| {
|
||||
graph.incidences[*f]
|
||||
.next
|
||||
.is_some_and(|i| i.0 == e.arr_idx())
|
||||
})
|
||||
.expect("cannot find previous incidence, corrupt internal data state");
|
||||
self.incidences[previous].next = next;
|
||||
}
|
||||
}
|
||||
|
||||
fn raw_incidences(&self, v: Vertex) -> impl Iterator<Item = (VertexSlot, Edge)> {
|
||||
let mut incidence = self.vertices[v].first_incidence;
|
||||
std::iter::from_fn(move || self.step_incidence(&mut incidence))
|
||||
}
|
||||
|
||||
fn step_incidence(&self, incidence: &mut Option<IncidenceSlot>) -> Option<(VertexSlot, Edge)> {
|
||||
// TODO: Benchmark storing full Index (one read, larger entries) vs. slot + get_idx() (two reads, smaller entries).
|
||||
let current = (*incidence)?;
|
||||
let e = self.incidences.get_idx(current.0).unwrap();
|
||||
let entry = self.incidences[e];
|
||||
*incidence = entry.next;
|
||||
Some((entry.adjacent, e))
|
||||
}
|
||||
|
||||
fn normalize_edge(&self, e: Edge) -> Edge {
|
||||
self.incidences.get_idx(e.arr_idx() & !1).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Graph {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl GraphTopology for Graph {
|
||||
type Vertex = Vertex;
|
||||
type Edge = Edge;
|
||||
type IncidenceCursor = GraphIncidenceCursor;
|
||||
|
||||
fn vertex_count(&self) -> usize {
|
||||
self.vertices.len()
|
||||
}
|
||||
|
||||
fn vertex_capacity(&self) -> usize {
|
||||
self.vertices.capacity()
|
||||
}
|
||||
|
||||
fn vertex_map<T: Clone>(&self, default: T) -> VertexMap<Self::Vertex, T> {
|
||||
VertexMap::new(default, |v| v.arr_idx(), self.vertex_capacity())
|
||||
}
|
||||
|
||||
fn edge_count(&self) -> usize {
|
||||
self.incidences.len() / 2
|
||||
}
|
||||
|
||||
fn edge_capacity(&self) -> usize {
|
||||
self.incidences.capacity() / 2
|
||||
}
|
||||
|
||||
fn edge_map<T: Clone>(&self, default: T) -> EdgeMap<Self::Edge, T> {
|
||||
EdgeMap::new(default, |e| e.arr_idx() / 2, self.edge_capacity())
|
||||
}
|
||||
|
||||
fn degree(&self, v: Self::Vertex) -> usize {
|
||||
self.vertices[v].incidence_count
|
||||
}
|
||||
|
||||
fn are_adjacent(&self, v1: Self::Vertex, v2: Self::Vertex) -> bool {
|
||||
self.adjacent_vertices(v1).any(|x| x == v2)
|
||||
}
|
||||
|
||||
fn vertices(&self) -> impl Iterator<Item = Self::Vertex> {
|
||||
self.vertices.iter().map(|(i, _)| i)
|
||||
}
|
||||
|
||||
fn adjacent_vertices(&self, v: Self::Vertex) -> impl Iterator<Item = Self::Vertex> {
|
||||
self.raw_incidences(v)
|
||||
.map(|(vs, _)| self.vertices.get_idx(vs.0).unwrap())
|
||||
}
|
||||
|
||||
fn incident_vertices(&self, e: Self::Edge) -> (Self::Vertex, Self::Vertex) {
|
||||
let v2 = self
|
||||
.vertices
|
||||
.get_idx(self.incidences[e].adjacent.0)
|
||||
.unwrap();
|
||||
let f = self.incidences.get_idx(e.arr_idx() ^ 1).unwrap();
|
||||
let v1 = self
|
||||
.vertices
|
||||
.get_idx(self.incidences[f].adjacent.0)
|
||||
.unwrap();
|
||||
(v1, v2)
|
||||
}
|
||||
|
||||
fn edges(&self) -> impl Iterator<Item = Self::Edge> {
|
||||
self.incidences
|
||||
.iter()
|
||||
.filter(|(i, _)| i.arr_idx() % 2 == 0)
|
||||
.map(|(i, _)| i)
|
||||
}
|
||||
|
||||
fn incident_edges(&self, v: Self::Vertex) -> impl Iterator<Item = Self::Edge> {
|
||||
self.raw_incidences(v).map(|(_, e)| self.normalize_edge(e))
|
||||
}
|
||||
|
||||
fn incidences(&self, v: Self::Vertex) -> impl Iterator<Item = (Self::Vertex, Self::Edge)> {
|
||||
self.raw_incidences(v)
|
||||
.map(|(vs, e)| (self.vertices.get_idx(vs.0).unwrap(), self.normalize_edge(e)))
|
||||
}
|
||||
|
||||
fn incidence_cursor(&self, v: Self::Vertex) -> Self::IncidenceCursor {
|
||||
GraphIncidenceCursor {
|
||||
incidence: self.vertices[v].first_incidence,
|
||||
}
|
||||
}
|
||||
|
||||
fn add_vertex(&mut self) -> Self::Vertex {
|
||||
self.vertices.insert(VertexIncidenceHeader {
|
||||
incidence_count: 0,
|
||||
first_incidence: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn add_edge(&mut self, v1: Self::Vertex, v2: Self::Vertex) -> Self::Edge {
|
||||
let first = self.add_incidence(v1, v2);
|
||||
self.add_incidence(v2, v1);
|
||||
first
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Benchmark delete with storing "previous" in O(1) vs. linear lookup in O(degree).
|
||||
impl GraphTopologyDeletion for Graph {
|
||||
fn delete_vertex(&mut self, v: Self::Vertex) {
|
||||
let v_header = self
|
||||
.vertices
|
||||
.remove(v)
|
||||
.expect("attempt to delete an invalid vertex");
|
||||
let mut cursor = IncidentEdgeCursor {
|
||||
incidence: v_header.first_incidence,
|
||||
};
|
||||
while let Some(e) = cursor.next(self) {
|
||||
// Since v is being deleted, there are no update_incidence_list() calls for e, no need
|
||||
// to fix v's incidence list.
|
||||
let (f, e_entry, f_entry) = self.remove_incidence_pair(e);
|
||||
if e_entry.adjacent != f_entry.adjacent {
|
||||
self.update_incidence_list(f, e_entry.adjacent, f_entry.next, false);
|
||||
} else {
|
||||
cursor.incidence = f_entry.next;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The incidence entries are removed before patching the linked lists. This is safe because
|
||||
// update_incidence_list() searches by raw slot index (IncidenceSlot.0) and only dereferences
|
||||
// the predecessor, never the removed entries themselves.
|
||||
fn delete_edge(&mut self, e: Self::Edge) {
|
||||
let (f, e_entry, f_entry) = self.remove_incidence_pair(e);
|
||||
if e_entry.adjacent != f_entry.adjacent {
|
||||
self.update_incidence_list(e, f_entry.adjacent, e_entry.next, false);
|
||||
self.update_incidence_list(f, e_entry.adjacent, f_entry.next, false);
|
||||
} else if f_entry.next.is_some_and(|i| e.arr_idx() == i.0) {
|
||||
self.update_incidence_list(f, e_entry.adjacent, e_entry.next, true);
|
||||
} else {
|
||||
self.update_incidence_list(e, e_entry.adjacent, f_entry.next, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
crate::graph_topology_test_fixtures!(Graph);
|
||||
crate::graph_topology_tests!(Graph);
|
||||
crate::graph_topology_deletion_tests!(Graph);
|
||||
|
||||
#[test]
|
||||
fn incident_vertices_paired_index() {
|
||||
let mut graph = Graph::new();
|
||||
let v1 = graph.add_vertex();
|
||||
let v2 = graph.add_vertex();
|
||||
let e = graph.add_edge(v1, v2);
|
||||
let f = graph
|
||||
.incidences
|
||||
.get_idx(e.arr_idx() + 1)
|
||||
.expect("paired index should be valid");
|
||||
let (u1, u2) = graph.incident_vertices(f);
|
||||
assert!(
|
||||
(u1 == v1 && u2 == v2) || (u1 == v2 && u2 == v1),
|
||||
"unexpected incident vertices {u1:?} and {u2:?} for edge {f:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_edge_paired_index() {
|
||||
let mut graph = Graph::new();
|
||||
let v1 = graph.add_vertex();
|
||||
let v2 = graph.add_vertex();
|
||||
let e = graph.add_edge(v1, v2);
|
||||
let f = graph
|
||||
.incidences
|
||||
.get_idx(e.arr_idx() + 1)
|
||||
.expect("paired index should be valid");
|
||||
graph.delete_edge(f);
|
||||
assert_eq!(graph.edge_count(), 0, "unexpected edge count after delete");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_edge_loop_paired_index() {
|
||||
let mut graph = Graph::new();
|
||||
let v = graph.add_vertex();
|
||||
let e = graph.add_edge(v, v);
|
||||
let f = graph
|
||||
.incidences
|
||||
.get_idx(e.arr_idx() + 1)
|
||||
.expect("paired index should be valid");
|
||||
graph.delete_edge(f);
|
||||
assert_eq!(graph.edge_count(), 0, "unexpected edge count after delete");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
pub(crate) mod bfs_testing;
|
||||
pub(crate) mod dfs_testing;
|
||||
pub(crate) mod dijkstra_testing;
|
||||
pub(crate) mod find_path_testing;
|
||||
pub(crate) mod graph_topology_testing;
|
||||
pub(crate) mod maps_testing;
|
||||
@@ -0,0 +1,257 @@
|
||||
#[macro_export]
|
||||
macro_rules! bfs_tests {
|
||||
($T:ty) => {
|
||||
#[test]
|
||||
fn bfs_single_vertex() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
let v = graph.add_vertex();
|
||||
let result = $crate::algorithms::bfs(&graph, v);
|
||||
assert_eq!(
|
||||
result.distances[v],
|
||||
Some(0),
|
||||
"unexpected distance of source vertex"
|
||||
);
|
||||
assert_eq!(
|
||||
result.predecessors[v], None,
|
||||
"unexpected predecessor of source vertex"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bfs_disconnected() {
|
||||
let (graph, vertices) = make_test_graph_disconnected();
|
||||
let result = $crate::algorithms::bfs(&graph, vertices[0]);
|
||||
assert_eq!(
|
||||
result.distances[vertices[0]],
|
||||
Some(0),
|
||||
"unexpected distance of source vertex"
|
||||
);
|
||||
assert_eq!(
|
||||
result.predecessors[vertices[0]], None,
|
||||
"unexpected predecessor of source vertex"
|
||||
);
|
||||
for &v in &vertices[1..3] {
|
||||
assert_eq!(
|
||||
result.distances[v], None,
|
||||
"disconnected vertex {v:?} should have no distance"
|
||||
);
|
||||
assert_eq!(
|
||||
result.predecessors[v], None,
|
||||
"disconnected vertex {v:?} should have no predecessor"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bfs() {
|
||||
let (graph, vertices, _, _) = make_test_graph();
|
||||
let result = $crate::algorithms::bfs(&graph, vertices[0]);
|
||||
assert_bfs_distances(&result.distances, &vertices);
|
||||
assert_bfs_predecessors(&result.predecessors, &vertices);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bfs_distances_single_vertex() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
let v = graph.add_vertex();
|
||||
let distances = $crate::algorithms::bfs_distances(&graph, v);
|
||||
assert_eq!(
|
||||
distances[v],
|
||||
Some(0),
|
||||
"unexpected distance of source vertex"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bfs_distances_disconnected() {
|
||||
let (graph, vertices) = make_test_graph_disconnected();
|
||||
let distances = $crate::algorithms::bfs_distances(&graph, vertices[0]);
|
||||
assert_eq!(
|
||||
distances[vertices[0]],
|
||||
Some(0),
|
||||
"unexpected distance of source vertex"
|
||||
);
|
||||
for &v in &vertices[1..3] {
|
||||
assert_eq!(
|
||||
distances[v], None,
|
||||
"disconnected vertex {v:?} should have no distance"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bfs_distances() {
|
||||
let (graph, vertices, _, _) = make_test_graph();
|
||||
let distances = $crate::algorithms::bfs_distances(&graph, vertices[0]);
|
||||
assert_bfs_distances(&distances, &vertices);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bfs_find_source() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
let v = graph.add_vertex();
|
||||
assert_eq!(
|
||||
$crate::algorithms::bfs_find(&graph, v, v),
|
||||
Some(0),
|
||||
"source should be found at distance 0"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bfs_find_disconnected() {
|
||||
let (graph, vertices) = make_test_graph_disconnected();
|
||||
assert_eq!(
|
||||
$crate::algorithms::bfs_find(&graph, vertices[0], vertices[1]),
|
||||
None,
|
||||
"disconnected target should not be found"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bfs_find() {
|
||||
let (graph, vertices, _, _) = make_test_graph();
|
||||
let expected_distances = [
|
||||
Some(0),
|
||||
Some(1),
|
||||
Some(2),
|
||||
Some(2),
|
||||
Some(2),
|
||||
Some(3),
|
||||
Some(3),
|
||||
Some(3),
|
||||
Some(3),
|
||||
Some(4),
|
||||
];
|
||||
for i in 0..10 {
|
||||
assert_eq!(
|
||||
$crate::algorithms::bfs_find(&graph, vertices[0], vertices[i]),
|
||||
expected_distances[i],
|
||||
"unexpected distance from {:?} to {:?}",
|
||||
vertices[0],
|
||||
vertices[i]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bfs_find_where_source_matches() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
let v = graph.add_vertex();
|
||||
assert_eq!(
|
||||
$crate::algorithms::bfs_find_where(&graph, v, |u| u == v),
|
||||
Some((v, 0)),
|
||||
"source should match with distance 0"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bfs_find_where_disconnected() {
|
||||
let (graph, vertices) = make_test_graph_disconnected();
|
||||
assert_eq!(
|
||||
$crate::algorithms::bfs_find_where(&graph, vertices[0], |v| v == vertices[1]),
|
||||
None,
|
||||
"disconnected vertex {:?} should not be found",
|
||||
vertices[1]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bfs_find_where_no_match() {
|
||||
let (graph, vertices, _, _) = make_test_graph();
|
||||
assert_eq!(
|
||||
$crate::algorithms::bfs_find_where(&graph, vertices[0], |_| false),
|
||||
None,
|
||||
"no vertex should match an always-false predicate"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bfs_find_where_nearest() {
|
||||
let (graph, vertices, _, _) = make_test_graph();
|
||||
// vertices[5], vertices[6], vertices[7], vertices[8] are all at distance 3 from vertices[0].
|
||||
// vertices[9] is at distance 4. Predicate matches vertices[7], vertices[8], vertices[9].
|
||||
// BFS must return one of the distance-3 ones, not vertices[9].
|
||||
let result = $crate::algorithms::bfs_find_where(&graph, vertices[0], |v| {
|
||||
v == vertices[7] || v == vertices[8] || v == vertices[9]
|
||||
});
|
||||
assert!(result.is_some(), "expected a match");
|
||||
let (found, distance) = result.unwrap();
|
||||
assert_eq!(
|
||||
distance, 3,
|
||||
"unexpected distance to nearest matching vertex {found:?}",
|
||||
);
|
||||
assert!(
|
||||
found == vertices[7] || found == vertices[8],
|
||||
"unexpected nearest match vertex {found:?}, should be {:?} or {:?}",
|
||||
vertices[7],
|
||||
vertices[8]
|
||||
);
|
||||
}
|
||||
|
||||
fn assert_bfs_distances(
|
||||
distances: &$crate::maps::VertexMap<
|
||||
<$T as $crate::traits::GraphTopology>::Vertex,
|
||||
Option<u32>,
|
||||
>,
|
||||
vertices: &[<$T as $crate::traits::GraphTopology>::Vertex],
|
||||
) {
|
||||
let expected = [
|
||||
Some(0),
|
||||
Some(1),
|
||||
Some(2),
|
||||
Some(2),
|
||||
Some(2),
|
||||
Some(3),
|
||||
Some(3),
|
||||
Some(3),
|
||||
Some(3),
|
||||
Some(4),
|
||||
];
|
||||
for i in 0..10 {
|
||||
assert_eq!(
|
||||
distances[vertices[i]], expected[i],
|
||||
"unexpected BFS distance from {:?} to {:?}",
|
||||
vertices[0], vertices[i]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_bfs_predecessors(
|
||||
predecessors: &$crate::maps::VertexMap<
|
||||
<$T as $crate::traits::GraphTopology>::Vertex,
|
||||
Option<<$T as $crate::traits::GraphTopology>::Vertex>,
|
||||
>,
|
||||
vertices: &[<$T as $crate::traits::GraphTopology>::Vertex],
|
||||
) {
|
||||
assert_eq!(
|
||||
predecessors[vertices[0]], None,
|
||||
"source should have no predecessor"
|
||||
);
|
||||
// Each non-source vertex's predecessor must be adjacent and at distance one less.
|
||||
let expected_predecessors = [
|
||||
vec![None],
|
||||
vec![Some(vertices[0])],
|
||||
vec![Some(vertices[1])],
|
||||
vec![Some(vertices[1])],
|
||||
vec![Some(vertices[1])],
|
||||
vec![Some(vertices[2])],
|
||||
vec![Some(vertices[2]), Some(vertices[3])],
|
||||
vec![Some(vertices[4])],
|
||||
vec![Some(vertices[4])],
|
||||
vec![Some(vertices[5]), Some(vertices[6]), Some(vertices[7])],
|
||||
];
|
||||
for i in 1..10 {
|
||||
assert!(
|
||||
expected_predecessors[i].contains(&predecessors[vertices[i]]),
|
||||
"unexpected predecessor {:?} of {:?}",
|
||||
predecessors[vertices[i]],
|
||||
vertices[i]
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
#[macro_export]
|
||||
macro_rules! dfs_tests {
|
||||
($T:ty) => {
|
||||
#[test]
|
||||
fn dfs_single_vertex() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
let v = graph.add_vertex();
|
||||
let result = $crate::algorithms::dfs(&graph, v);
|
||||
assert!(result.visited[v], "source vertex should be visited");
|
||||
assert_eq!(
|
||||
result.predecessors[v], None,
|
||||
"unexpected predecessor of source vertex"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dfs_disconnected() {
|
||||
let (graph, vertices) = make_test_graph_disconnected();
|
||||
let result = $crate::algorithms::dfs(&graph, vertices[0]);
|
||||
assert!(
|
||||
result.visited[vertices[0]],
|
||||
"source vertex should be visited"
|
||||
);
|
||||
assert_eq!(
|
||||
result.predecessors[vertices[0]], None,
|
||||
"unexpected predecessor of source vertex"
|
||||
);
|
||||
for &v in &vertices[1..3] {
|
||||
assert!(
|
||||
!result.visited[v],
|
||||
"disconnected vertex {v:?} should not be visited"
|
||||
);
|
||||
assert_eq!(
|
||||
result.predecessors[v], None,
|
||||
"disconnected vertex {v:?} should have no predecessor"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dfs() {
|
||||
let (graph, vertices, _, _) = make_test_graph();
|
||||
let result = $crate::algorithms::dfs(&graph, vertices[0]);
|
||||
assert_dfs_visited(&result.visited, &vertices);
|
||||
assert_dfs_predecessors(&graph, &result.visited, &result.predecessors, &vertices);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dfs_visited_single_vertex() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
let v = graph.add_vertex();
|
||||
let visited = $crate::algorithms::dfs_visited(&graph, v);
|
||||
assert!(visited[v], "source vertex should be visited");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dfs_visited_disconnected() {
|
||||
let (graph, vertices) = make_test_graph_disconnected();
|
||||
let visited = $crate::algorithms::dfs_visited(&graph, vertices[0]);
|
||||
assert!(visited[vertices[0]], "source vertex should be visited");
|
||||
for &v in &vertices[1..3] {
|
||||
assert!(
|
||||
!visited[v],
|
||||
"disconnected vertex {v:?} should not be visited"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dfs_visited() {
|
||||
let (graph, vertices, _, _) = make_test_graph();
|
||||
let visited = $crate::algorithms::dfs_visited(&graph, vertices[0]);
|
||||
assert_dfs_visited(&visited, &vertices);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dfs_find_source() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
let v = graph.add_vertex();
|
||||
assert!(
|
||||
$crate::algorithms::dfs_find(&graph, v, v),
|
||||
"source should find itself"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dfs_find_disconnected() {
|
||||
let (graph, vertices) = make_test_graph_disconnected();
|
||||
assert!(
|
||||
!$crate::algorithms::dfs_find(&graph, vertices[0], vertices[1]),
|
||||
"disconnected target should not be found"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dfs_find() {
|
||||
let (graph, vertices, _, _) = make_test_graph();
|
||||
for i in 0..10 {
|
||||
assert!(
|
||||
$crate::algorithms::dfs_find(&graph, vertices[0], vertices[i]),
|
||||
"vertex {:?} should be reachable from {:?}",
|
||||
vertices[i],
|
||||
vertices[0]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dfs_find_where_source_matches() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
let v = graph.add_vertex();
|
||||
assert_eq!(
|
||||
$crate::algorithms::dfs_find_where(&graph, v, |u| u == v),
|
||||
Some(v),
|
||||
"source should find itself"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dfs_find_where_disconnected() {
|
||||
let (graph, vertices) = make_test_graph_disconnected();
|
||||
assert_eq!(
|
||||
$crate::algorithms::dfs_find_where(&graph, vertices[0], |v| v == vertices[1]),
|
||||
None,
|
||||
"disconnected vertex {:?} should not be found",
|
||||
vertices[1]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dfs_find_where_no_match() {
|
||||
let (graph, vertices, _, _) = make_test_graph();
|
||||
assert_eq!(
|
||||
$crate::algorithms::dfs_find_where(&graph, vertices[0], |_| false),
|
||||
None,
|
||||
"no vertex should match an always-false predicate"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dfs_find_where_adjacent() {
|
||||
let (graph, vertices, _, _) = make_test_graph();
|
||||
assert_eq!(
|
||||
$crate::algorithms::dfs_find_where(&graph, vertices[0], |v| v == vertices[1]),
|
||||
Some(vertices[1]),
|
||||
"expected to find adjacent vertex"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dfs_find_where() {
|
||||
let (graph, vertices, _, _) = make_test_graph();
|
||||
assert_eq!(
|
||||
$crate::algorithms::dfs_find_where(&graph, vertices[0], |v| v == vertices[9]),
|
||||
Some(vertices[9]),
|
||||
"expected to find connected vertex"
|
||||
);
|
||||
}
|
||||
|
||||
fn assert_dfs_visited(
|
||||
visited: &$crate::maps::VertexMap<<$T as $crate::traits::GraphTopology>::Vertex, bool>,
|
||||
vertices: &[<$T as $crate::traits::GraphTopology>::Vertex],
|
||||
) {
|
||||
for i in 0..10 {
|
||||
assert!(
|
||||
visited[vertices[i]],
|
||||
"vertex {:?} should be visited",
|
||||
vertices[i]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_dfs_predecessors(
|
||||
graph: &$T,
|
||||
visited: &$crate::maps::VertexMap<<$T as $crate::traits::GraphTopology>::Vertex, bool>,
|
||||
predecessors: &$crate::maps::VertexMap<
|
||||
<$T as $crate::traits::GraphTopology>::Vertex,
|
||||
Option<<$T as $crate::traits::GraphTopology>::Vertex>,
|
||||
>,
|
||||
vertices: &[<$T as $crate::traits::GraphTopology>::Vertex],
|
||||
) {
|
||||
use $crate::traits::GraphTopology;
|
||||
assert_eq!(
|
||||
predecessors[vertices[0]], None,
|
||||
"source should have no predecessor"
|
||||
);
|
||||
for i in 1..10 {
|
||||
let v = vertices[i];
|
||||
let p = predecessors[v].expect(&format!("vertex {v:?} should have a predecessor"));
|
||||
assert!(
|
||||
visited[p],
|
||||
"predecessor {p:?} of vertex {v:?} should be visited"
|
||||
);
|
||||
assert!(
|
||||
graph.are_adjacent(v, p),
|
||||
"predecessor {p:?} of vertex {v:?} should be adjacent"
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
#[macro_export]
|
||||
macro_rules! dijkstra_tests {
|
||||
($T:ty) => {
|
||||
#[test]
|
||||
fn dijkstra_single_vertex() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
let v = graph.add_vertex();
|
||||
let result = $crate::algorithms::dijkstra(&graph, v, |_| {
|
||||
panic!("unexpected call of weight functor")
|
||||
});
|
||||
assert_single_vertex(&result, v);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dijkstra_disconnected() {
|
||||
let (graph, vertices) = make_test_graph_disconnected();
|
||||
let result = $crate::algorithms::dijkstra(&graph, vertices[0], |_| {
|
||||
panic!("unexpected call of weight functor")
|
||||
});
|
||||
assert_single_vertex(&result, vertices[0]);
|
||||
assert_disconnected(&result, &vertices[1..3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dijkstra_zero_weight_loop() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
let vertices: [<$T as $crate::traits::GraphTopology>::Vertex; 3] =
|
||||
core::array::from_fn(|_| graph.add_vertex());
|
||||
let e1 = graph.add_edge(vertices[0], vertices[0]);
|
||||
let e2 = graph.add_edge(vertices[1], vertices[1]);
|
||||
graph.add_edge(vertices[0], vertices[1]);
|
||||
graph.add_edge(vertices[1], vertices[2]);
|
||||
let mut weights = graph.edge_map(1);
|
||||
weights[e1] = 0;
|
||||
weights[e2] = 0;
|
||||
let result = $crate::algorithms::dijkstra(&graph, vertices[0], |e| weights[e]);
|
||||
assert_single_vertex(&result, vertices[0]);
|
||||
for i in 1..3 {
|
||||
assert_eq!(
|
||||
result.predecessors[vertices[i]],
|
||||
Some(vertices[i - 1]),
|
||||
"unexpected predecessor of vertex {:?}",
|
||||
vertices[i]
|
||||
);
|
||||
assert_eq!(
|
||||
result.distances[vertices[i]],
|
||||
Some(i.try_into().unwrap()),
|
||||
"unexpected distance of vertex {:?}",
|
||||
vertices[i]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dijkstra() {
|
||||
let (graph, vertices, edges, _, weights) = make_test_graph_weighted();
|
||||
let result = $crate::algorithms::dijkstra(&graph, vertices[0], |e| weights[e]);
|
||||
assert_test_graph(&result, &vertices);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dijkstra_distances() {
|
||||
let (graph, vertices, edges, _, weights) = make_test_graph_weighted();
|
||||
let distances =
|
||||
$crate::algorithms::dijkstra_distances(&graph, vertices[0], |e| weights[e]);
|
||||
assert_distances_test_graph(&distances, &vertices);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dijkstra_unweighted_single_vertex() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
let v = graph.add_vertex();
|
||||
let result = $crate::algorithms::dijkstra_unweighted(&graph, v);
|
||||
assert_single_vertex(&result, v)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dijkstra_unweighted_disconnected() {
|
||||
let (graph, vertices) = make_test_graph_disconnected();
|
||||
let result = $crate::algorithms::dijkstra_unweighted(&graph, vertices[0]);
|
||||
assert_single_vertex(&result, vertices[0]);
|
||||
assert_disconnected(&result, &vertices[1..3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dijkstra_unweighted() {
|
||||
let (graph, vertices, _, _) = make_test_graph();
|
||||
let result = $crate::algorithms::dijkstra_unweighted(&graph, vertices[0]);
|
||||
assert_unweighted_test_graph(&result, &vertices);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dijkstra_distances_unweighted_single_vertex() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
let v = graph.add_vertex();
|
||||
let distances = $crate::algorithms::dijkstra_distances_unweighted(&graph, v);
|
||||
assert_distances_single_vertex(&distances, v);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dijkstra_distances_unweighted_disconnected() {
|
||||
let (graph, vertices) = make_test_graph_disconnected();
|
||||
let distances = $crate::algorithms::dijkstra_distances_unweighted(&graph, vertices[0]);
|
||||
assert_distances_single_vertex(&distances, vertices[0]);
|
||||
assert_distances_disconnected(&distances, &vertices[1..3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dijkstra_distances_unweighted() {
|
||||
let (graph, vertices, _, _) = make_test_graph();
|
||||
let distances = $crate::algorithms::dijkstra_distances_unweighted(&graph, vertices[0]);
|
||||
assert_distances_unweighted_test_graph(&distances, &vertices);
|
||||
}
|
||||
|
||||
fn assert_single_vertex(
|
||||
result: &$crate::algorithms::DijkstraResult<
|
||||
<$T as $crate::traits::GraphTopology>::Vertex,
|
||||
>,
|
||||
v: <$T as $crate::traits::GraphTopology>::Vertex,
|
||||
) {
|
||||
assert_distances_single_vertex(&result.distances, v);
|
||||
assert_eq!(
|
||||
result.predecessors[v], None,
|
||||
"unexpected predecessor of source vertex",
|
||||
);
|
||||
}
|
||||
|
||||
fn assert_distances_single_vertex(
|
||||
distances: &$crate::maps::VertexMap<
|
||||
<$T as $crate::traits::GraphTopology>::Vertex,
|
||||
Option<u32>,
|
||||
>,
|
||||
v: <$T as $crate::traits::GraphTopology>::Vertex,
|
||||
) {
|
||||
assert_eq!(
|
||||
distances[v],
|
||||
Some(0),
|
||||
"unexpected distance of source vertex"
|
||||
);
|
||||
}
|
||||
|
||||
fn assert_disconnected(
|
||||
result: &$crate::algorithms::DijkstraResult<
|
||||
<$T as $crate::traits::GraphTopology>::Vertex,
|
||||
>,
|
||||
vertices: &[<$T as $crate::traits::GraphTopology>::Vertex],
|
||||
) {
|
||||
assert_distances_disconnected(&result.distances, &vertices);
|
||||
for &v in vertices {
|
||||
assert_eq!(
|
||||
result.predecessors[v], None,
|
||||
"unexpected predecessor of disconnected vertex {v:?}",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_distances_disconnected(
|
||||
distances: &$crate::maps::VertexMap<
|
||||
<$T as $crate::traits::GraphTopology>::Vertex,
|
||||
Option<u32>,
|
||||
>,
|
||||
vertices: &[<$T as $crate::traits::GraphTopology>::Vertex],
|
||||
) {
|
||||
for &v in vertices {
|
||||
assert_eq!(
|
||||
distances[v], None,
|
||||
"unexpected distance of disconnected vertex {v:?}",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_test_graph(
|
||||
result: &$crate::algorithms::DijkstraResult<
|
||||
<$T as $crate::traits::GraphTopology>::Vertex,
|
||||
>,
|
||||
vertices: &[<$T as $crate::traits::GraphTopology>::Vertex],
|
||||
) {
|
||||
assert_distances_test_graph(&result.distances, &vertices);
|
||||
let expected_predecessors_from_v0 = [
|
||||
vec![None],
|
||||
vec![Some(vertices[0])],
|
||||
vec![Some(vertices[4])],
|
||||
vec![Some(vertices[1])],
|
||||
vec![Some(vertices[7])],
|
||||
vec![Some(vertices[9])],
|
||||
vec![Some(vertices[3])],
|
||||
vec![Some(vertices[9])],
|
||||
vec![Some(vertices[7])],
|
||||
vec![Some(vertices[6])],
|
||||
];
|
||||
for i in 0..10 {
|
||||
assert!(
|
||||
expected_predecessors_from_v0[i].contains(&result.predecessors[vertices[i]]),
|
||||
"unexpected predecessor {:?} of {:?}",
|
||||
result.predecessors[vertices[i]],
|
||||
vertices[i]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_distances_test_graph(
|
||||
distances: &$crate::maps::VertexMap<
|
||||
<$T as $crate::traits::GraphTopology>::Vertex,
|
||||
Option<u32>,
|
||||
>,
|
||||
vertices: &[<$T as $crate::traits::GraphTopology>::Vertex],
|
||||
) {
|
||||
let expected_distances_from_v0 = [
|
||||
Some(0),
|
||||
Some(1),
|
||||
Some(65),
|
||||
Some(4),
|
||||
Some(58),
|
||||
Some(43),
|
||||
Some(14),
|
||||
Some(46),
|
||||
Some(145),
|
||||
Some(29),
|
||||
];
|
||||
for i in 0..10 {
|
||||
assert_eq!(
|
||||
distances[vertices[i]], expected_distances_from_v0[i],
|
||||
"unexpected distance from {:?} to {:?}",
|
||||
vertices[0], vertices[i]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_unweighted_test_graph(
|
||||
result: &$crate::algorithms::DijkstraResult<
|
||||
<$T as $crate::traits::GraphTopology>::Vertex,
|
||||
>,
|
||||
vertices: &[<$T as $crate::traits::GraphTopology>::Vertex],
|
||||
) {
|
||||
assert_distances_unweighted_test_graph(&result.distances, &vertices);
|
||||
let expected_predecessors_from_v0 = [
|
||||
vec![None],
|
||||
vec![Some(vertices[0])],
|
||||
vec![Some(vertices[1])],
|
||||
vec![Some(vertices[1])],
|
||||
vec![Some(vertices[1])],
|
||||
vec![Some(vertices[2])],
|
||||
vec![Some(vertices[2]), Some(vertices[3])],
|
||||
vec![Some(vertices[4])],
|
||||
vec![Some(vertices[4])],
|
||||
vec![Some(vertices[5]), Some(vertices[6]), Some(vertices[7])],
|
||||
];
|
||||
for i in 0..10 {
|
||||
assert!(
|
||||
expected_predecessors_from_v0[i].contains(&result.predecessors[vertices[i]]),
|
||||
"unexpected predecessor {:?} of {:?}",
|
||||
result.predecessors[vertices[i]],
|
||||
vertices[i]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_distances_unweighted_test_graph(
|
||||
distances: &$crate::maps::VertexMap<
|
||||
<$T as $crate::traits::GraphTopology>::Vertex,
|
||||
Option<u32>,
|
||||
>,
|
||||
vertices: &[<$T as $crate::traits::GraphTopology>::Vertex],
|
||||
) {
|
||||
let expected_distances_from_v0 = [
|
||||
Some(0),
|
||||
Some(1),
|
||||
Some(2),
|
||||
Some(2),
|
||||
Some(2),
|
||||
Some(3),
|
||||
Some(3),
|
||||
Some(3),
|
||||
Some(3),
|
||||
Some(4),
|
||||
];
|
||||
for i in 0..10 {
|
||||
assert_eq!(
|
||||
distances[vertices[i]], expected_distances_from_v0[i],
|
||||
"unexpected distance from {:?} to {:?}",
|
||||
vertices[0], vertices[i]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn make_test_graph_weighted() -> (
|
||||
$T,
|
||||
[<$T as $crate::traits::GraphTopology>::Vertex; 10],
|
||||
[(
|
||||
<$T as $crate::traits::GraphTopology>::Edge,
|
||||
<$T as $crate::traits::GraphTopology>::Vertex,
|
||||
<$T as $crate::traits::GraphTopology>::Vertex,
|
||||
); 18],
|
||||
[Vec<(
|
||||
<$T as $crate::traits::GraphTopology>::Vertex,
|
||||
<$T as $crate::traits::GraphTopology>::Edge,
|
||||
)>; 10],
|
||||
$crate::maps::EdgeMap<<$T as $crate::traits::GraphTopology>::Edge, u32>,
|
||||
) {
|
||||
use $crate::traits::GraphTopology;
|
||||
let (graph, vertices, edges, incidences) = make_test_graph();
|
||||
let mut weights = graph.edge_map(99_u32);
|
||||
for i in [1, 3, 7, 10, 12, 14, 15, 17] {
|
||||
weights[edges[i].0] = i.try_into().unwrap();
|
||||
}
|
||||
(graph, vertices, edges, incidences, weights)
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
#[macro_export]
|
||||
macro_rules! find_path_tests {
|
||||
($T:ty) => {
|
||||
#[test]
|
||||
fn find_path_source_equals_target() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
let v = graph.add_vertex();
|
||||
assert_eq!(
|
||||
$crate::algorithms::find_path(&graph, v, v),
|
||||
Some(vec![]),
|
||||
"path from source to itself should be empty"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_path_disconnected() {
|
||||
let (graph, vertices) = make_test_graph_disconnected();
|
||||
assert_eq!(
|
||||
$crate::algorithms::find_path(&graph, vertices[0], vertices[1]),
|
||||
None,
|
||||
"no path should exist to disconnected vertex"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_path_adjacent() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
let v1 = graph.add_vertex();
|
||||
let v2 = graph.add_vertex();
|
||||
let e = graph.add_edge(v1, v2);
|
||||
let path = $crate::algorithms::find_path(&graph, v1, v2)
|
||||
.expect("path should exist between adjacent vertices");
|
||||
assert_eq!(
|
||||
path.len(),
|
||||
1,
|
||||
"unexpected path length between adjacent vertices"
|
||||
);
|
||||
assert_eq!(path[0], e, "path should use the connecting edge");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_path() {
|
||||
let (graph, vertices, _, _) = make_test_graph();
|
||||
let path = $crate::algorithms::find_path(&graph, vertices[0], vertices[9])
|
||||
.expect(&format!(
|
||||
"path should exist between connected vertices {:?} and {:?}",
|
||||
vertices[0], vertices[9]
|
||||
));
|
||||
assert_valid_path(&graph, &path, vertices[0], vertices[9]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_path_where_source_matches() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
let v = graph.add_vertex();
|
||||
assert_eq!(
|
||||
$crate::algorithms::find_path_where(&graph, v, |u| u == v),
|
||||
Some(vec![]),
|
||||
"path from source to itself should be empty"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_path_where_disconnected() {
|
||||
let (graph, vertices) = make_test_graph_disconnected();
|
||||
assert_eq!(
|
||||
$crate::algorithms::find_path_where(&graph, vertices[0], |v| v == vertices[1]),
|
||||
None,
|
||||
"no path should exist to disconnected vertex"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_path_where_no_match() {
|
||||
let (graph, vertices, _, _) = make_test_graph();
|
||||
assert_eq!(
|
||||
$crate::algorithms::find_path_where(&graph, vertices[0], |_| false),
|
||||
None,
|
||||
"no path should exist when predicate never matches"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_path_where() {
|
||||
let (graph, vertices, _, _) = make_test_graph();
|
||||
let path =
|
||||
$crate::algorithms::find_path_where(&graph, vertices[0], |v| v == vertices[9])
|
||||
.expect(&format!(
|
||||
"path should exist between connected vertices {:?} and {:?}",
|
||||
vertices[0], vertices[9]
|
||||
));
|
||||
assert_valid_path(&graph, &path, vertices[0], vertices[9]);
|
||||
}
|
||||
|
||||
fn assert_valid_path(
|
||||
graph: &$T,
|
||||
path: &[<$T as $crate::traits::GraphTopology>::Edge],
|
||||
source: <$T as $crate::traits::GraphTopology>::Vertex,
|
||||
target: <$T as $crate::traits::GraphTopology>::Vertex,
|
||||
) {
|
||||
use $crate::traits::GraphTopology;
|
||||
assert!(!path.is_empty(), "path should be non-empty");
|
||||
// Walks the path: tracks current vertex, confirm each edge is incident to it.
|
||||
let mut current = source;
|
||||
for (i, &e) in path.iter().enumerate() {
|
||||
let (v1, v2) = graph.incident_vertices(e);
|
||||
assert_ne!(v1, v2, "path should not contain loop edge {e:?}");
|
||||
assert!(
|
||||
v1 == current || v2 == current,
|
||||
"path edge {e:?} (index {i}, from {v1:?} to {v2:?}) is not incident to current path vertex {current:?}"
|
||||
);
|
||||
current = if v1 == current { v2 } else { v1 };
|
||||
}
|
||||
assert_eq!(
|
||||
current, target,
|
||||
"path should end at target {target:?}, but ended at {current:?}"
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,281 @@
|
||||
#[macro_export]
|
||||
macro_rules! vertex_map_tests {
|
||||
($T:ty) => {
|
||||
#[test]
|
||||
fn initial_values_are_default() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
let v1 = graph.add_vertex();
|
||||
let v2 = graph.add_vertex();
|
||||
let map = graph.vertex_map(42);
|
||||
assert_eq!(map[v1], 42);
|
||||
assert_eq!(map[v2], 42);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_and_read() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
let v1 = graph.add_vertex();
|
||||
let v2 = graph.add_vertex();
|
||||
let mut map = graph.vertex_map(0);
|
||||
map[v1] = 7;
|
||||
assert_eq!(map[v1], 7);
|
||||
assert_eq!(map[v2], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lazy_growth_on_read() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
graph.add_vertex();
|
||||
let map = graph.vertex_map(99);
|
||||
let v = graph.add_vertex();
|
||||
assert_eq!(map[v], 99);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lazy_growth_on_write() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
let v1 = graph.add_vertex();
|
||||
let mut map = graph.vertex_map(0);
|
||||
let v2 = graph.add_vertex();
|
||||
map[v2] = 7;
|
||||
assert_eq!(map[v1], 0);
|
||||
assert_eq!(map[v2], 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_expands_to_new_vertices() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
graph.add_vertex();
|
||||
let mut map = graph.vertex_map(42);
|
||||
let initial_len = map.len();
|
||||
while graph.vertex_capacity() <= initial_len {
|
||||
graph.add_vertex();
|
||||
}
|
||||
assert!(
|
||||
map.len() < graph.vertex_capacity(),
|
||||
"precondition: map is stale before sync"
|
||||
);
|
||||
map.sync(&graph);
|
||||
assert_eq!(map.len(), graph.vertex_capacity());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_does_not_overwrite_existing_values() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
let v = graph.add_vertex();
|
||||
let mut map = graph.vertex_map(0);
|
||||
map[v] = 5;
|
||||
graph.add_vertex();
|
||||
map.sync(&graph);
|
||||
assert_eq!(map[v], 5);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! vertex_map_deletion_tests {
|
||||
($T:ty) => {
|
||||
#[test]
|
||||
fn surviving_vertex_readable_after_delete() {
|
||||
use $crate::traits::GraphTopology;
|
||||
use $crate::traits::GraphTopologyDeletion;
|
||||
let mut graph = <$T>::new();
|
||||
let v1 = graph.add_vertex();
|
||||
let v2 = graph.add_vertex();
|
||||
let mut map = graph.vertex_map(0);
|
||||
map[v1] = 1;
|
||||
map[v2] = 2;
|
||||
graph.delete_vertex(v2);
|
||||
assert_eq!(map[v1], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capacity_does_not_shrink_after_delete() {
|
||||
use $crate::traits::GraphTopology;
|
||||
use $crate::traits::GraphTopologyDeletion;
|
||||
let mut graph = <$T>::new();
|
||||
let v1 = graph.add_vertex();
|
||||
let v2 = graph.add_vertex();
|
||||
let mut map = graph.vertex_map(0);
|
||||
map[v1] = 5;
|
||||
let capacity_before = graph.vertex_capacity();
|
||||
graph.delete_vertex(v2);
|
||||
map.sync(&graph);
|
||||
assert_eq!(map.len(), capacity_before);
|
||||
assert_eq!(map[v1], 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reused_slot_returns_old_value() {
|
||||
use $crate::traits::GraphTopology;
|
||||
use $crate::traits::GraphTopologyDeletion;
|
||||
let mut graph = <$T>::new();
|
||||
graph.add_vertex();
|
||||
let v1 = graph.add_vertex();
|
||||
let mut map = graph.vertex_map(0);
|
||||
map[v1] = 99;
|
||||
graph.delete_vertex(v1);
|
||||
let v2 = graph.add_vertex();
|
||||
// VertexMap uses raw indices, not vertex identity. A new vertex v2 reusing the slot
|
||||
// of previously deleted v1 sees the old value. Callers must reinitialize stale slots
|
||||
// after deletion.
|
||||
assert_eq!(map[v2], 99);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! edge_map_tests {
|
||||
($T:ty) => {
|
||||
#[test]
|
||||
fn initial_values_are_default() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
let v1 = graph.add_vertex();
|
||||
let v2 = graph.add_vertex();
|
||||
let e1 = graph.add_edge(v1, v2);
|
||||
let e2 = graph.add_edge(v1, v2);
|
||||
let map = graph.edge_map(42);
|
||||
assert_eq!(map[e1], 42);
|
||||
assert_eq!(map[e2], 42);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_and_read() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
let v1 = graph.add_vertex();
|
||||
let v2 = graph.add_vertex();
|
||||
let e1 = graph.add_edge(v1, v2);
|
||||
let e2 = graph.add_edge(v1, v2);
|
||||
let mut map = graph.edge_map(0);
|
||||
map[e1] = 7;
|
||||
assert_eq!(map[e1], 7);
|
||||
assert_eq!(map[e2], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lazy_growth_on_read() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
let v1 = graph.add_vertex();
|
||||
let v2 = graph.add_vertex();
|
||||
graph.add_edge(v1, v2);
|
||||
let map = graph.edge_map(99);
|
||||
let e = graph.add_edge(v1, v2);
|
||||
assert_eq!(map[e], 99);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lazy_growth_on_write() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
let v1 = graph.add_vertex();
|
||||
let v2 = graph.add_vertex();
|
||||
let e1 = graph.add_edge(v1, v2);
|
||||
let mut map = graph.edge_map(0);
|
||||
let e2 = graph.add_edge(v1, v2);
|
||||
map[e2] = 7;
|
||||
assert_eq!(map[e1], 0);
|
||||
assert_eq!(map[e2], 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_expands_to_new_edges() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
let v1 = graph.add_vertex();
|
||||
let v2 = graph.add_vertex();
|
||||
graph.add_edge(v1, v2);
|
||||
let mut map = graph.edge_map(42);
|
||||
let initial_len = map.len();
|
||||
while graph.edge_capacity() <= initial_len {
|
||||
graph.add_edge(v1, v2);
|
||||
}
|
||||
assert!(
|
||||
map.len() < graph.edge_capacity(),
|
||||
"precondition: map is stale before sync"
|
||||
);
|
||||
map.sync(&graph);
|
||||
assert_eq!(map.len(), graph.edge_capacity());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_does_not_overwrite_existing_values() {
|
||||
use $crate::traits::GraphTopology;
|
||||
let mut graph = <$T>::new();
|
||||
let v1 = graph.add_vertex();
|
||||
let v2 = graph.add_vertex();
|
||||
let e = graph.add_edge(v1, v2);
|
||||
let mut map = graph.edge_map(0);
|
||||
map[e] = 5;
|
||||
graph.add_edge(v1, v2);
|
||||
map.sync(&graph);
|
||||
assert_eq!(map[e], 5);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! edge_map_deletion_tests {
|
||||
($T:ty) => {
|
||||
#[test]
|
||||
fn surviving_edge_readable_after_delete() {
|
||||
use $crate::traits::GraphTopology;
|
||||
use $crate::traits::GraphTopologyDeletion;
|
||||
let mut graph = <$T>::new();
|
||||
let v1 = graph.add_vertex();
|
||||
let v2 = graph.add_vertex();
|
||||
let e1 = graph.add_edge(v1, v2);
|
||||
let e2 = graph.add_edge(v1, v2);
|
||||
let mut map = graph.edge_map(0);
|
||||
map[e1] = 1;
|
||||
map[e2] = 2;
|
||||
graph.delete_edge(e2);
|
||||
assert_eq!(map[e1], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capacity_does_not_shrink_after_delete() {
|
||||
use $crate::traits::GraphTopology;
|
||||
use $crate::traits::GraphTopologyDeletion;
|
||||
let mut graph = <$T>::new();
|
||||
let v1 = graph.add_vertex();
|
||||
let v2 = graph.add_vertex();
|
||||
let e1 = graph.add_edge(v1, v2);
|
||||
let e2 = graph.add_edge(v1, v2);
|
||||
let mut map = graph.edge_map(0);
|
||||
map[e1] = 5;
|
||||
let capacity_before = graph.edge_capacity();
|
||||
graph.delete_edge(e2);
|
||||
map.sync(&graph);
|
||||
assert_eq!(map.len(), capacity_before);
|
||||
assert_eq!(map[e1], 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reused_slot_returns_old_value() {
|
||||
use $crate::traits::GraphTopology;
|
||||
use $crate::traits::GraphTopologyDeletion;
|
||||
let mut graph = <$T>::new();
|
||||
let v1 = graph.add_vertex();
|
||||
let v2 = graph.add_vertex();
|
||||
graph.add_edge(v1, v2);
|
||||
let e1 = graph.add_edge(v1, v2);
|
||||
let mut map = graph.edge_map(0);
|
||||
map[e1] = 99;
|
||||
graph.delete_edge(e1);
|
||||
let e2 = graph.add_edge(v1, v2);
|
||||
// EdgeMap uses raw indices, not edge identity. Because to_index uses arr_idx/2,
|
||||
// both halves of a deleted edge pair map to the same index, so a new edge reusing
|
||||
// either slot sees the old value. Callers must reinitialize stale slots after deletion.
|
||||
assert_eq!(map[e2], 99);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
use crate::maps::{EdgeMap, VertexMap};
|
||||
|
||||
// TODO: Add functions to reserve memory for vertices and edges.
|
||||
// TODO: Split out GraphTopologyAddition trait.
|
||||
pub trait GraphTopology {
|
||||
type Vertex: Copy + Eq;
|
||||
type Edge: Copy + Eq;
|
||||
type IncidenceCursor: IncidenceCursor<Self> + Copy;
|
||||
|
||||
fn vertex_count(&self) -> usize;
|
||||
fn vertex_capacity(&self) -> usize;
|
||||
fn vertex_map<T: Clone>(&self, default: T) -> VertexMap<Self::Vertex, T>;
|
||||
fn edge_count(&self) -> usize;
|
||||
fn edge_capacity(&self) -> usize;
|
||||
fn edge_map<T: Clone>(&self, default: T) -> EdgeMap<Self::Edge, T>;
|
||||
fn degree(&self, v: Self::Vertex) -> usize;
|
||||
fn are_adjacent(&self, v1: Self::Vertex, v2: Self::Vertex) -> bool;
|
||||
fn vertices(&self) -> impl Iterator<Item = Self::Vertex>;
|
||||
fn adjacent_vertices(&self, v: Self::Vertex) -> impl Iterator<Item = Self::Vertex>;
|
||||
fn incident_vertices(&self, e: Self::Edge) -> (Self::Vertex, Self::Vertex);
|
||||
fn edges(&self) -> impl Iterator<Item = Self::Edge>;
|
||||
fn incident_edges(&self, v: Self::Vertex) -> impl Iterator<Item = Self::Edge>;
|
||||
fn incidences(&self, v: Self::Vertex) -> impl Iterator<Item = (Self::Vertex, Self::Edge)>;
|
||||
fn incidence_cursor(&self, v: Self::Vertex) -> Self::IncidenceCursor;
|
||||
fn add_vertex(&mut self) -> Self::Vertex;
|
||||
fn add_edge(&mut self, v1: Self::Vertex, v2: Self::Vertex) -> Self::Edge;
|
||||
}
|
||||
|
||||
pub trait GraphTopologyDeletion: GraphTopology {
|
||||
fn delete_vertex(&mut self, v: Self::Vertex);
|
||||
fn delete_edge(&mut self, e: Self::Edge);
|
||||
}
|
||||
|
||||
pub trait IncidenceCursor<G: GraphTopology + ?Sized> {
|
||||
fn next(&mut self, graph: &G) -> Option<(G::Vertex, G::Edge)>;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
mod append_graph_tests {
|
||||
use grapherity::models::append_graph::AppendGraph;
|
||||
|
||||
grapherity::graph_topology_test_fixtures!(AppendGraph);
|
||||
grapherity::bfs_tests!(AppendGraph);
|
||||
}
|
||||
|
||||
mod graph_tests {
|
||||
use grapherity::models::graph::Graph;
|
||||
|
||||
grapherity::graph_topology_test_fixtures!(Graph);
|
||||
grapherity::bfs_tests!(Graph);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
mod append_graph_tests {
|
||||
use grapherity::models::append_graph::AppendGraph;
|
||||
|
||||
grapherity::graph_topology_test_fixtures!(AppendGraph);
|
||||
grapherity::dfs_tests!(AppendGraph);
|
||||
}
|
||||
|
||||
mod graph_tests {
|
||||
use grapherity::models::graph::Graph;
|
||||
|
||||
grapherity::graph_topology_test_fixtures!(Graph);
|
||||
grapherity::dfs_tests!(Graph);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
mod append_graph_tests {
|
||||
use grapherity::models::append_graph::AppendGraph;
|
||||
|
||||
grapherity::graph_topology_test_fixtures!(AppendGraph);
|
||||
grapherity::dijkstra_tests!(AppendGraph);
|
||||
}
|
||||
|
||||
mod graph_tests {
|
||||
use grapherity::models::graph::Graph;
|
||||
|
||||
grapherity::graph_topology_test_fixtures!(Graph);
|
||||
grapherity::dijkstra_tests!(Graph);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
mod append_graph_tests {
|
||||
use grapherity::models::append_graph::AppendGraph;
|
||||
|
||||
grapherity::graph_topology_test_fixtures!(AppendGraph);
|
||||
grapherity::find_path_tests!(AppendGraph);
|
||||
}
|
||||
|
||||
mod graph_tests {
|
||||
use grapherity::models::graph::Graph;
|
||||
|
||||
grapherity::graph_topology_test_fixtures!(Graph);
|
||||
grapherity::find_path_tests!(Graph);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
mod append_graph_vertex_map_tests {
|
||||
use grapherity::models::append_graph::AppendGraph;
|
||||
|
||||
grapherity::vertex_map_tests!(AppendGraph);
|
||||
}
|
||||
|
||||
mod append_graph_edge_map_tests {
|
||||
use grapherity::models::append_graph::AppendGraph;
|
||||
|
||||
grapherity::edge_map_tests!(AppendGraph);
|
||||
}
|
||||
|
||||
mod graph_vertex_map_tests {
|
||||
use grapherity::models::graph::Graph;
|
||||
|
||||
grapherity::vertex_map_tests!(Graph);
|
||||
grapherity::vertex_map_deletion_tests!(Graph);
|
||||
}
|
||||
|
||||
mod graph_edge_map_tests {
|
||||
use grapherity::models::graph::Graph;
|
||||
|
||||
grapherity::edge_map_tests!(Graph);
|
||||
grapherity::edge_map_deletion_tests!(Graph);
|
||||
}
|
||||
Reference in New Issue
Block a user