#include "chrome/browser/devtools/serialize_host_descriptions.h"
#include <map>
#include <string_view>
#include <unordered_set>
#include <utility>
namespace {
base::Value Serialize(
std::string_view child_key,
base::Value* root,
const std::map<base::Value*, std::vector<base::Value*>>& children) {
base::Value::List children_list;
auto child_it = children.find(root);
if (child_it != children.end()) {
for (base::Value* child : child_it->second) {
children_list.Append(Serialize(child_key, child, children));
}
}
if (!children_list.empty())
root->GetDict().Set(child_key, std::move(children_list));
return std::move(*root);
}
void CreateDictionaryForest(
std::vector<HostDescriptionNode> hosts,
std::map<base::Value*, std::vector<base::Value*>>* children,
std::unordered_set<base::Value*>* roots,
base::Value::List* representations) {
representations->reserve(hosts.size());
std::map<std::string_view, base::Value*> name_to_representation;
for (HostDescriptionNode& node : hosts) {
representations->Append(std::move(node.representation));
name_to_representation.emplace(node.name, &representations->back());
}
for (HostDescriptionNode& node : hosts) {
base::Value* node_rep = name_to_representation[node.name];
std::string_view parent_name = node.parent_name;
if (parent_name.empty()) {
roots->insert(node_rep);
continue;
}
auto node_it = name_to_representation.find(parent_name);
if (node_it == name_to_representation.end()) {
roots->insert(node_rep);
continue;
}
(*children)[name_to_representation[parent_name]].push_back(node_rep);
}
}
}
base::Value::List SerializeHostDescriptions(
std::vector<HostDescriptionNode> hosts,
std::string_view child_key) {
base::Value::List representations;
std::map<base::Value*, std::vector<base::Value*>> children;
std::unordered_set<base::Value*> roots;
CreateDictionaryForest(std::move(hosts), &children, &roots, &representations);
base::Value::List result;
result.reserve(roots.size());
for (auto* root : roots) {
result.Append(Serialize(child_key, root, children));
}
return result;
}