libutil: add topoSortAsync
Change-Id: Icad14f3e168f9577e7b99ac5f3f552f8625aebcd
This commit is contained in:
@@ -2,6 +2,8 @@
|
||||
///@file
|
||||
|
||||
#include "lix/libutil/error.hh"
|
||||
#include "lix/libutil/result.hh"
|
||||
#include <kj/async.h>
|
||||
|
||||
namespace nix {
|
||||
|
||||
@@ -40,4 +42,47 @@ std::vector<T> topoSort(std::set<T> items,
|
||||
return sorted;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
kj::Promise<Result<std::vector<T>>> topoSortAsync(std::set<T> items,
|
||||
std::function<kj::Promise<Result<std::set<T>>>(const T &)> getChildren,
|
||||
std::function<Error(const T &, const T &)> makeCycleError)
|
||||
try {
|
||||
std::vector<T> sorted;
|
||||
std::set<T> visited, parents;
|
||||
|
||||
std::function<kj::Promise<Result<void>>(const T & path, const T * parent)> dfsVisit;
|
||||
|
||||
// NOLINTNEXTLINE(cppcoreguidelines-avoid-capturing-lambda-coroutines)
|
||||
dfsVisit = [&](const T & path, const T * parent) -> kj::Promise<Result<void>> {
|
||||
try {
|
||||
if (parents.count(path)) throw makeCycleError(path, *parent);
|
||||
|
||||
if (!visited.insert(path).second) co_return result::success();
|
||||
parents.insert(path);
|
||||
|
||||
std::set<T> references = TRY_AWAIT(getChildren(path));
|
||||
|
||||
for (auto & i : references)
|
||||
/* Don't traverse into items that don't exist in our starting set. */
|
||||
if (i != path && items.count(i))
|
||||
TRY_AWAIT(dfsVisit(i, &path));
|
||||
|
||||
sorted.push_back(path);
|
||||
parents.erase(path);
|
||||
co_return result::success();
|
||||
} catch (...) {
|
||||
co_return result::current_exception();
|
||||
}
|
||||
};
|
||||
|
||||
for (auto & i : items)
|
||||
TRY_AWAIT(dfsVisit(i, nullptr));
|
||||
|
||||
std::reverse(sorted.begin(), sorted.end());
|
||||
|
||||
co_return sorted;
|
||||
} catch (...) {
|
||||
co_return result::current_exception();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user