Skip to main content

DfsTraverser

Struct DfsTraverser 

Source
pub struct DfsTraverser { /* private fields */ }
Expand description

The base of a depth-first search of your own over a Graph - Java’s abstract class DfsTraverser. A type of yours implements the hooks enter_node and leave_node of DfsHooks, and a run method starts the search with them.

The search visits each node it reaches once. It calls enter_node when it reaches a node (preorder) and leave_node when it has searched from all out-nodes of the node (postorder). It takes the out-nodes of each node in ascending order, so the hooks come in the order of a textbook recursive depth-first search. The search itself runs without recursion and keeps its stack on the heap, so a deep graph does not overflow the call stack. Here, calls are the calls between the methods of a program, and the postorder puts each method after the methods it calls, except along calls that close a cycle:

struct CalleesFirst {
    order: Vec<u32>,
}

impl DfsHooks for CalleesFirst {
    fn enter_node(&mut self, _method: u32, _: &mut DfsControl<'_>) -> bool {
        true
    }

    fn leave_node(&mut self, method: u32, _: &mut DfsControl<'_>) {
        self.order.push(method);
    }
}

let mut callees_first = CalleesFirst { order: Vec::new() };
DfsTraverser::new(&calls).run_from(main, &mut callees_first);
// callees_first.order: [1, 6, 8, 3, 7, 9, 4, 5, 2, 0] - parseArgs, parse, read, load,
// format, write, save, show, run and main

Between its two hooks, a node is on the current path. The current path leads from the node where the search started to the node being searched. The hooks may call DfsControl::is_visited and DfsControl::is_on_stack, end the search at a node by returning false from enter_node, and end the whole run with DfsControl::stop. A closure, which is a set of hooks with only the preorder hook, counts the nodes that a run from node 1 reaches:

use graphity_core::{DfsTraverser, GraphBuilder};

let mut b = GraphBuilder::new();
b.add_nodes(4);
b.add_edge_pairs(&[0, 1, 1, 2, 0, 3]);
let graph = b.build();

let mut count = 0;
DfsTraverser::new(&graph).run_from(1, &mut |_node| { count += 1; true });
assert_eq!(count, 2);

run searches from every node in ascending order, run_from from one node and run_from_nodes from several, such as the root nodes that graphs::root_nodes returns. The visited nodes add up over the runs of a traverser: a node is visited at most once in the lifetime of the traverser, and a later run skips it.

A hook cannot start another run of the same traverser. Java throws IllegalStateException; in Rust, a run borrows the traverser mutably and a hook receives only a DfsControl, so the borrow checker rejects the call at compile time:

ⓘ
use graphity_core::{DfsTraverser, GraphBuilder};

let graph = GraphBuilder::new().build();
let mut traverser = DfsTraverser::new(&graph);
traverser.run(&mut |_node| {
    traverser.run_from(0, &mut |_| true); // error: the traverser is borrowed by the run
    true
});

If a run ends with a panic from a hook or from the search, the state of the traverser is undefined: nodes of the interrupted path may still count as on the path, for example. A new traverser is needed for further runs.

DfsEdgeTraverser also calls a hook for every edge, which suits searches that look at edges to nodes already visited. This type calls no such hook, which makes it the faster choice where node hooks suffice. FrontierTraverser searches breadth-first. Common searches are ready-made, such as top_order, EdgeTypes, back_edges and graphs::find_cycle.

A traverser is mutable, and a run borrows it mutably, so the borrow rules keep two threads from running it at once - Java’s instances are not safe to share between threads.

Memory: 2 bits per node for the visited state, and up to 8 x node_count bytes for the stack, which grows with the deepest path searched; the graph’s arrays are shared.

Implementations§

Source§

impl DfsTraverser

Source

pub fn new(graph: &Graph) -> Self

Returns a traverser for graph, with no node visited - Java’s constructor. The graph’s arrays are shared.

Time: O(node_count).

Source

pub fn graph(&self) -> &Graph

Returns the graph that this traverser searches - Java’s protected field graph.

Time: O(1).

Source

pub fn is_visited(&self, node: u32) -> bool

Returns whether a run has reached node so far - DfsControl::is_visited outside a run.

node is a node ID in 0..node_count; for any other value the method returns false or panics with an index out of bounds message.

Time: O(1).

Source

pub fn is_on_stack(&self, node: u32) -> bool

Returns whether node is on the current path - DfsControl::is_on_stack outside a run. Outside a run, no node is on the path.

node is a node ID in 0..node_count; for any other value the method returns false or panics with an index out of bounds message.

Time: O(1).

Source

pub fn run<H: DfsHooks + ?Sized>(&mut self, hooks: &mut H)

Searches from every node not visited yet, in ascending order, until every node is visited.

A node that no earlier search has reached when its turn comes starts a search of its own.

Time: O(node_count + edge_count), plus the hooks.

§Panics

With an invalid argument message if a depth-first path is longer than 2^30 - 5 nodes.

Source

pub fn run_from<H: DfsHooks + ?Sized>(&mut self, start_node: u32, hooks: &mut H)

Searches from start_node, visiting the nodes it reaches that are not visited yet - Java’s overload run(int).

If start_node is visited already, nothing happens.

Time: O(reachable nodes + reachable edges), plus the hooks.

§Panics

With an index out of bounds message if start_node is not in 0..node_count; with an invalid argument message if a depth-first path is longer than 2^30 - 5 nodes.

Source

pub fn run_from_nodes<H: DfsHooks + ?Sized>( &mut self, start_nodes: &[u32], hooks: &mut H, )

Searches from each of start_nodes in list order, skipping those visited already - Java’s overload run(IntList).

The list is checked before the first hook, so a start node out of range leaves the traverser unchanged. DfsControl::stop ends the whole call, not only the search from one start node. The run borrows the list, so it cannot change until the call returns.

Time: O(start_nodes.len() + reachable nodes + reachable edges), plus the hooks.

§Panics

With an index out of bounds message if a start node is not in 0..node_count; with an invalid argument message if a depth-first path is longer than 2^30 - 5 nodes.

Trait Implementations§

Source§

impl Clone for DfsTraverser

Source§

fn clone(&self) -> DfsTraverser

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DfsTraverser

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.