Files
scylladb/utils/sorting.hh
Kefu Chai 7b10cc8079 treewide: include seastar headers with brackets
this change was created in the same spirit of ebff5f5d.

despite that we include Seastar as a submodule, Seastar is not a
part of scylla project. so we'd better include its headers using
brackets.

ebff5f5d addressed this cosmetic issue a while back. but probably
clangd's header-insertion helped some of contributor to insert
the missing headers with `"`. so this style of `include` returned
to the tree with these new changes.

unfortunately, clangd does not allow us to configure the style
of `include` at the time of writing.

Signed-off-by: Kefu Chai <kefu.chai@scylladb.com>

Closes scylladb/scylladb#19406
2024-06-21 19:20:27 +03:00

68 lines
2.0 KiB
C++

/*
* Copyright (C) 2024-present ScyllaDB
*/
/*
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
#include <stdexcept>
#include <vector>
#include <map>
#include <seastar/core/future.hh>
#include <seastar/coroutine/maybe_yield.hh>
#include "utils/stall_free.hh"
namespace utils {
/**
* Topological sort a DAG using Kahn's algorithm.
*
* @param vertices Contains all vertices of the graph
* @param adjacency_map Entry {k, v} means there is an k->v edge in the graph
* @return a vector of topologically sorted vertices.
If there is an edge k->v, then vertex k will be before vertex v.
* @throws std::runtime_error when a graph has any cycle.
*/
template<typename T, typename Compare = std::less<T>>
seastar::future<std::vector<T>> topological_sort(const std::vector<T>& vertices, const std::multimap<T, T, Compare>& adjacency_map) {
std::map<T, size_t, Compare> ref_count_map; // Contains counters how many edges point (reference) to a vertex
std::vector<T> sorted;
sorted.reserve(vertices.size());
for (auto& edge: adjacency_map) {
ref_count_map[edge.second]++;
}
// Push to result vertices which reference counter == 0
for (auto& v: vertices) {
if (!ref_count_map.contains(v)) {
sorted.emplace_back(v);
}
}
// Iterate over already sorted vertices,
// decrease counter of vertices to which sorted vertices points,
// push to the end of `sorted` vector vertices which counter == 0.
for (size_t i = 0; i < sorted.size(); i++) {
auto [it_begin, it_end] = adjacency_map.equal_range(sorted[i]);
while (it_begin != it_end) {
auto d = it_begin->second;
if (--ref_count_map[d] == 0) {
sorted.push_back(d);
}
++it_begin;
}
co_await seastar::coroutine::maybe_yield();
}
co_await utils::clear_gently(ref_count_map);
if (sorted.size() != vertices.size()) {
throw std::runtime_error("Detected cycle in the graph.");
}
co_return sorted;
}
}