File size: 8,105 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 |
use std::{collections::VecDeque, hash::Hash};
use rustc_hash::{FxHashMap, FxHashSet};
use serde::{Deserialize, Serialize};
use turbo_tasks_macros::{TraceRawVcs, ValueDebugFormat};
use super::graph_store::{GraphNode, GraphStore};
use crate::{self as turbo_tasks, NonLocalValue};
/// A graph traversal that builds an adjacency map
#[derive(Debug, Clone, Serialize, Deserialize, TraceRawVcs, ValueDebugFormat)]
#[serde(bound(
serialize = "T: Serialize + Eq + Hash",
deserialize = "T: Deserialize<'de> + Eq + Hash"
))]
pub struct AdjacencyMap<T> {
adjacency_map: FxHashMap<T, Vec<T>>,
roots: Vec<T>,
}
unsafe impl<T> NonLocalValue for AdjacencyMap<T> where T: NonLocalValue {}
impl<T> PartialEq for AdjacencyMap<T>
where
T: Eq + Hash,
{
fn eq(&self, other: &Self) -> bool {
self.adjacency_map == other.adjacency_map && self.roots == other.roots
}
}
impl<T> Eq for AdjacencyMap<T> where T: Eq + Hash {}
impl<T> Default for AdjacencyMap<T>
where
T: Eq + Hash + Clone,
{
fn default() -> Self {
Self::new()
}
}
impl<T> AdjacencyMap<T>
where
T: Eq + Hash + Clone,
{
/// Creates a new adjacency map
pub fn new() -> Self {
Self {
adjacency_map: FxHashMap::default(),
roots: Vec::new(),
}
}
/// Returns an iterator over the root nodes of the graph
pub fn roots(&self) -> impl Iterator<Item = &T> {
self.roots.iter()
}
/// Returns an iterator over the children of the given node
pub fn get(&self, node: &T) -> Option<impl Iterator<Item = &T>> {
self.adjacency_map.get(node).map(|vec| vec.iter())
}
}
impl<T> GraphStore for AdjacencyMap<T>
where
T: Eq + Hash + Clone + Send,
{
type Node = T;
type Handle = T;
fn insert(&mut self, from_handle: Option<T>, node: GraphNode<T>) -> Option<(Self::Handle, &T)> {
let vec = if let Some(from_handle) = from_handle {
self.adjacency_map
.entry(from_handle)
.or_insert_with(|| Vec::with_capacity(1))
} else {
&mut self.roots
};
vec.push(node.node().clone());
Some((node.into_node(), vec.last().unwrap()))
}
}
impl<T> AdjacencyMap<T>
where
T: Eq + Hash + Clone,
{
/// Returns an owned iterator over the nodes in postorder topological order,
/// starting from the roots.
pub fn into_postorder_topological(self) -> IntoPostorderTopologicalIter<T> {
IntoPostorderTopologicalIter {
adjacency_map: self.adjacency_map,
stack: self
.roots
.into_iter()
.rev()
.map(|root| (ReverseTopologicalPass::Pre, root))
.collect(),
visited: FxHashSet::default(),
}
}
/// Returns an owned iterator over all edges (node pairs) in reverse breadth first order,
/// starting from the roots.
pub fn into_breadth_first_edges(self) -> IntoBreadthFirstEdges<T> {
IntoBreadthFirstEdges {
adjacency_map: self.adjacency_map,
queue: self
.roots
.into_iter()
.rev()
.map(|root| (None, root))
.collect(),
expanded: FxHashSet::default(),
}
}
/// Returns an iterator over the nodes in postorder topological order,
/// starting from the roots.
pub fn postorder_topological(&self) -> PostorderTopologicalIter<'_, T> {
PostorderTopologicalIter {
adjacency_map: &self.adjacency_map,
stack: self
.roots
.iter()
.rev()
.map(|root| (ReverseTopologicalPass::Pre, root))
.collect(),
visited: FxHashSet::default(),
}
}
/// Returns an iterator over the nodes in postorder topological order,
/// starting from the given node.
pub fn postorder_topological_from_node<'graph>(
&'graph self,
node: &'graph T,
) -> PostorderTopologicalIter<'graph, T> {
PostorderTopologicalIter {
adjacency_map: &self.adjacency_map,
stack: vec![(ReverseTopologicalPass::Pre, node)],
visited: FxHashSet::default(),
}
}
}
#[derive(Debug)]
enum ReverseTopologicalPass {
Pre,
Post,
}
/// An iterator over the nodes of a graph in postorder topological order, starting
/// from the roots.
pub struct IntoPostorderTopologicalIter<T>
where
T: Eq + Hash + Clone,
{
adjacency_map: FxHashMap<T, Vec<T>>,
stack: Vec<(ReverseTopologicalPass, T)>,
visited: FxHashSet<T>,
}
impl<T> Iterator for IntoPostorderTopologicalIter<T>
where
T: Eq + Hash + Clone,
{
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
let current = loop {
let (pass, current) = self.stack.pop()?;
match pass {
ReverseTopologicalPass::Post => {
break current;
}
ReverseTopologicalPass::Pre => {
if self.visited.contains(¤t) {
continue;
}
self.visited.insert(current.clone());
let Some(neighbors) = self.adjacency_map.get(¤t) else {
break current;
};
self.stack.push((ReverseTopologicalPass::Post, current));
self.stack.extend(
neighbors
.iter()
.rev()
.map(|neighbor| (ReverseTopologicalPass::Pre, neighbor.clone())),
);
}
}
};
Some(current)
}
}
pub struct IntoBreadthFirstEdges<T>
where
T: Eq + std::hash::Hash + Clone,
{
adjacency_map: FxHashMap<T, Vec<T>>,
queue: VecDeque<(Option<T>, T)>,
expanded: FxHashSet<T>,
}
impl<T> Iterator for IntoBreadthFirstEdges<T>
where
T: Eq + std::hash::Hash + Clone,
{
type Item = (Option<T>, T);
fn next(&mut self) -> Option<Self::Item> {
let (parent, current) = self.queue.pop_front()?;
let Some(neighbors) = self.adjacency_map.get(¤t) else {
return Some((parent, current));
};
if self.expanded.insert(current.clone()) {
self.queue.extend(
neighbors
.iter()
.map(|neighbor| (Some(current.clone()), neighbor.clone())),
);
}
Some((parent, current))
}
}
/// An iterator over the nodes of a graph in postorder topological order, starting
/// from the roots.
pub struct PostorderTopologicalIter<'graph, T>
where
T: Eq + Hash + Clone,
{
adjacency_map: &'graph FxHashMap<T, Vec<T>>,
stack: Vec<(ReverseTopologicalPass, &'graph T)>,
visited: FxHashSet<&'graph T>,
}
impl<'graph, T> Iterator for PostorderTopologicalIter<'graph, T>
where
T: Eq + Hash + Clone,
{
type Item = &'graph T;
fn next(&mut self) -> Option<Self::Item> {
let current = loop {
let (pass, current) = self.stack.pop()?;
match pass {
ReverseTopologicalPass::Post => {
break current;
}
ReverseTopologicalPass::Pre => {
if self.visited.contains(current) {
continue;
}
self.visited.insert(current);
let Some(neighbors) = self.adjacency_map.get(current) else {
break current;
};
self.stack.push((ReverseTopologicalPass::Post, current));
self.stack.extend(
neighbors
.iter()
.rev()
.map(|neighbor| (ReverseTopologicalPass::Pre, neighbor)),
);
}
}
};
Some(current)
}
}
|