#include "object_forest.hpp" #include #include #include #include namespace object_forest { namespace { constexpr int BAD_HANDLE = -9; constexpr int INVALID = -22; constexpr int NO_ENTRY = -2; } std::size_t Forest::depth(Handle handle) const { std::size_t result = 0; Handle parent = nodes_[static_cast(locate(handle))].parent; while (parent != 0) { ++result; parent = nodes_[static_cast(locate(parent))].parent; } return result; } Record Forest::record(Handle handle) const { const Node &node = nodes_[static_cast(locate(handle))]; return Record{ handle, node.parent, depth(handle), node.name, node.properties }; } int Forest::get(Handle handle, Record &out) const { if (locate(handle) < 0) { return BAD_HANDLE; } out = record(handle); return 0; } int Forest::snapshot(Handle handle, std::vector &out) const { if (handle != 0 && locate(handle) < 0) { return BAD_HANDLE; } std::vector order; if (handle == 0) { for (Handle root : roots_) { preorder(root, order); } } else { preorder(handle, order); } std::vector result; result.reserve(order.size()); for (Handle selected : order) { result.push_back(record(selected)); } out.swap(result); return 0; } int Forest::path(Handle handle, std::string &out) const { if (handle == 0) { out = "/"; return 0; } if (locate(handle) < 0) { return BAD_HANDLE; } std::vector components; Handle current = handle; while (current != 0) { const Node &node = nodes_[static_cast(locate(current))]; components.push_back(node.name); current = node.parent; } std::string result; for (auto it = components.rbegin(); it != components.rend(); ++it) { result += '/'; result += *it; } out.swap(result); return 0; } int Forest::lookup(const std::string &path, Handle &out) const { if (path.empty() || path.front() != '/' || path.size() > 4096) { return INVALID; } std::vector normalized; std::size_t start = 1; while (start <= path.size()) { const std::size_t slash = path.find('/', start); const std::size_t end = slash == std::string::npos ? path.size() : slash; const std::string component = path.substr(start, end - start); if (component.empty() || component == ".") { // Empty and current-directory components do not name stored objects. } else if (component == "..") { if (normalized.empty()) { return INVALID; } normalized.pop_back(); } else { if (!valid_name(component)) { return INVALID; } normalized.push_back(component); } if (slash == std::string::npos) { break; } start = slash + 1; } Handle current = 0; for (const std::string &name : normalized) { const std::vector &children = siblings(current); const auto found = std::find_if(children.begin(), children.end(), [&](Handle child) { return nodes_[static_cast(locate(child))].name == name; }); if (found == children.end()) { return NO_ENTRY; } current = *found; } out = current; return 0; } }