navid/veins / 20d450df87bd0aaa912e365df1bf63afaf9a58ee0d14370879e8dae8f8ba5750 / xveins/src/object/object.cpp

object.cpp

← xveins/src/object · 33609 bytes · raw · download

#include "object/object.h"

#include <algorithm>
#include <cstring>

namespace vn {

std::string_view type_name(std::uint8_t type) {
    switch (type) {
    case TYPE_CHUNK:
        return "chunk";
    case TYPE_BLOB:
        return "blob";
    case TYPE_TREE:
        return "tree";
    case TYPE_COMMIT:
        return "commit";
    case TYPE_CONFLICT:
        return "conflict";
    case TYPE_OPERATION:
        return "operation";
    case TYPE_VIEW:
        return "view";
    default:
        return "unknown";
    }
}

bool type_valid(std::uint8_t type) {
    return type >= TYPE_CHUNK && type <= TYPE_VIEW;
}

// ---------------------------------------------------------------------------
// Names
// ---------------------------------------------------------------------------

static bool is_dot_name(std::string_view s) {
    return s == "." || s == "..";
}

bool valid_name(std::string_view name) {
    if (name.empty() || name.size() > MAX_NAME_LEN)
        return false;
    for (char c : name) {
        if (c == '\0' || c == '/')
            return false;
    }
    if (is_dot_name(name))
        return false;
    if (ascii_iequals(bytes_of(name), bytes_of(".veins")))
        return false;
    return true;
}

static bool valid_component(std::string_view component) {
    if (component.empty() || component.size() > MAX_NAME_LEN)
        return false;
    if (is_dot_name(component))
        return false;
    for (char c : component) {
        if (c == '\0' || c == '/')
            return false;
    }
    return true;
}

bool valid_path(std::string_view path) {
    if (path.empty() || path.size() > MAX_PATH_LEN)
        return false;
    if (path.front() == '/')
        return false;
    std::size_t start = 0;
    for (std::size_t i = 0; i <= path.size(); ++i) {
        const bool at_end = i == path.size();
        const bool sep = !at_end && path[i] == '/';
        if (at_end || sep) {
            if (!valid_component(path.substr(start, i - start)))
                return false;
            start = i + 1;
        }
    }
    return true;
}

// ---------------------------------------------------------------------------
// FastCDC
// ---------------------------------------------------------------------------

static std::array<std::uint64_t, 256> make_gear_table() {
    static constexpr std::uint8_t prefix[] = {'v', 'e', 'i', 'n', 's', '/', 'f', 'a', 's', 't', 'c',
                                              'd', 'c', '/', 'g', 'e', 'a', 'r', '/', 'v', '1'};
    std::array<std::uint64_t, 256> table{};
    for (std::size_t i = 0; i < table.size(); ++i) {
        blake3_hasher hasher;
        blake3_hasher_init(&hasher);
        blake3_hasher_update(&hasher, prefix, sizeof(prefix));
        const auto byte = static_cast<std::uint8_t>(i);
        blake3_hasher_update(&hasher, &byte, 1);
        std::array<std::uint8_t, 32> digest{};
        blake3_hasher_finalize(&hasher, digest.data(), digest.size());
        std::uint64_t value = 0;
        for (int j = 0; j < 8; ++j)
            value |= static_cast<std::uint64_t>(digest[static_cast<std::size_t>(j)]) << (j * 8);
        table[i] = value;
    }
    return table;
}

const std::array<std::uint64_t, 256>& fastcdc_gear() {
    static const auto table = make_gear_table();
    return table;
}

std::size_t fastcdc_next(Bytes data) {
    constexpr std::size_t min_size = 16384;
    constexpr std::size_t avg_size = 65536;
    constexpr std::size_t max_size = 262144;
    constexpr std::uint64_t mask_s = 0x3ffffull;
    constexpr std::uint64_t mask_l = 0x3fffull;
    const std::size_t len = data.size();
    if (len <= min_size)
        return len;
    const std::size_t limit = std::min(len, max_size);
    const std::size_t normal = std::min(avg_size, limit);
    const auto& gear = fastcdc_gear();
    std::uint64_t fp = 0;
    for (std::size_t i = min_size; i < normal; ++i) {
        fp = (fp >> 1) + gear[data[i]];
        if ((fp & mask_s) == 0)
            return i + 1;
    }
    for (std::size_t i = normal; i < limit; ++i) {
        fp = (fp >> 1) + gear[data[i]];
        if ((fp & mask_l) == 0)
            return i + 1;
    }
    return limit;
}

// ---------------------------------------------------------------------------
// Blobs
// ---------------------------------------------------------------------------

Result<std::vector<std::uint8_t>> encode_inline_blob(Bytes data) {
    ByteWriter w(data.size() + 8);
    w.u8(static_cast<std::uint8_t>(BlobForm::Inline));
    w.varint(data.size());
    w.raw(data);
    return w.take();
}

Result<Blob> decode_blob(Bytes body) {
    Reader r(body);
    const auto form = r.u8();
    if (!form)
        return unexpected(form.error());
    if (*form > 2)
        return fail(ErrorKind::InvalidValue, 0);
    Blob blob;
    blob.form = static_cast<BlobForm>(*form);
    if (blob.form == BlobForm::Inline) {
        const auto data = r.bytes(INLINE_THRESHOLD);
        if (!data)
            return unexpected(data.error());
        blob.data.assign(data->begin(), data->end());
        const auto fin = r.finish();
        if (!fin)
            return unexpected(fin.error());
        return blob;
    }
    const auto count = r.list_len(MAX_MANIFEST_ENTRIES);
    if (!count)
        return unexpected(count.error());
    if (*count == 0)
        return fail(ErrorKind::InvalidValue, 1);
    std::uint64_t total = 0;
    blob.entries.reserve(*count);
    for (std::size_t i = 0; i < *count; ++i) {
        const std::size_t at = r.offset();
        const auto cid = r.id();
        if (!cid)
            return unexpected(cid.error());
        const auto length = r.varint();
        if (!length)
            return unexpected(length.error());
        if (*length == 0)
            return fail(ErrorKind::InvalidValue, at);
        if (blob.form == BlobForm::Leaf && *length > MAX_CHUNK_LEN)
            return fail(ErrorKind::LimitExceeded, at);
        const std::uint64_t next = total + *length;
        if (next < total)
            return fail(ErrorKind::InvalidValue, at);
        total = next;
        blob.entries.push_back(BlobEntry{*cid, *length});
    }
    const auto fin = r.finish();
    if (!fin)
        return unexpected(fin.error());
    return blob;
}

struct NodeRef {
    Id id{};
    std::uint64_t length = 0;
};

struct Group {
    std::size_t start = 0;
    std::size_t count = 0;
};

static bool manifest_cut_after(const Id& id, std::size_t current_len) {
    if (current_len >= MAX_MANIFEST_ENTRIES)
        return true;
    if (current_len < 16)
        return false;
    return id[0] == 0;
}

BlobBuild build_blob(Bytes data) {
    BlobBuild build;
    if (data.size() <= INLINE_THRESHOLD) {
        auto body = encode_inline_blob(data);
        if (!body)
            return build;
        build.root = object_id(TYPE_BLOB, bytes_of(*body));
        RawObject object{TYPE_BLOB, std::move(*body), std::nullopt};
        object.id = build.root;
        build.objects.push_back(std::move(object));
        return build;
    }

    std::vector<NodeRef> level;
    std::size_t off = 0;
    while (off < data.size()) {
        const std::size_t n = fastcdc_next(data.subspan(off));
        const Bytes chunk = data.subspan(off, n);
        const Id cid = object_id(TYPE_CHUNK, chunk);
        RawObject object{TYPE_CHUNK, std::vector<std::uint8_t>(chunk.begin(), chunk.end()),
                         std::nullopt};
        object.id = cid;
        build.objects.push_back(std::move(object));
        level.push_back(NodeRef{cid, static_cast<std::uint64_t>(n)});
        off += n;
    }

    bool leaf_level = true;
    for (;;) {
        std::vector<Group> groups;
        std::size_t start = 0;
        for (std::size_t i = 0; i < level.size(); ++i) {
            const std::size_t current = i - start + 1;
            if (manifest_cut_after(level[i].id, current) || i + 1 == level.size()) {
                groups.push_back(Group{start, current});
                start = i + 1;
            }
        }

        std::vector<NodeRef> next;
        for (const Group& group : groups) {
            ByteWriter w(group.count * 40 + 8);
            w.u8(static_cast<std::uint8_t>(leaf_level ? BlobForm::Leaf : BlobForm::Interior));
            w.varint(group.count);
            std::uint64_t total = 0;
            for (std::size_t i = 0; i < group.count; ++i) {
                const NodeRef& node = level[group.start + i];
                w.id(node.id);
                w.varint(node.length);
                total += node.length;
            }
            auto body = w.take();
            const Id node_id = object_id(TYPE_BLOB, bytes_of(body));
            RawObject object{TYPE_BLOB, std::move(body), std::nullopt};
            object.id = node_id;
            build.objects.push_back(std::move(object));
            next.push_back(NodeRef{node_id, total});
        }

        if (next.size() == 1) {
            build.root = next.front().id;
            break;
        }
        level = std::move(next);
        leaf_level = false;
    }
    return build;
}

// ---------------------------------------------------------------------------
// Trees
// ---------------------------------------------------------------------------

static bool valid_tree_kind(std::uint8_t kind) {
    return kind >= KIND_FILE && kind <= KIND_CONFLICT;
}

static bool valid_submodule_target(const Id& id) {
    for (std::size_t i = 20; i < ID_LEN; ++i) {
        if (id[i] != 0)
            return false;
    }
    return true;
}

Result<Tree> decode_tree(Bytes body) {
    Reader r(body);
    const auto count = r.list_len(MAX_TREE_ENTRIES);
    if (!count)
        return unexpected(count.error());
    Tree tree;
    tree.entries.reserve(*count);
    std::optional<std::string> prev;
    for (std::size_t i = 0; i < *count; ++i) {
        const std::size_t at = r.offset();
        auto name = r.string_bytes(MAX_NAME_LEN);
        if (!name)
            return unexpected(name.error());
        if (!valid_name(*name))
            return fail(ErrorKind::InvalidName, at);
        if (prev) {
            const int c = compare(bytes_of(*prev), bytes_of(*name));
            if (c == 0)
                return fail(ErrorKind::Duplicate, at);
            if (c > 0)
                return fail(ErrorKind::Unsorted, at);
        }
        const auto kind = r.u8();
        if (!kind)
            return unexpected(kind.error());
        if (!valid_tree_kind(*kind))
            return fail(ErrorKind::InvalidValue, at);
        const auto target = r.id();
        if (!target)
            return unexpected(target.error());
        if (*kind == KIND_SUBMODULE && !valid_submodule_target(*target))
            return fail(ErrorKind::InvalidValue, at);
        tree.entries.push_back(TreeEntry{std::move(*name), *kind, *target});
        prev = tree.entries.back().name;
    }
    const auto fin = r.finish();
    if (!fin)
        return unexpected(fin.error());
    tree.body.assign(body.begin(), body.end());
    return tree;
}

Result<std::vector<std::uint8_t>> encode_tree(const std::vector<TreeEntry>& entries) {
    ByteWriter w(entries.size() * 48 + 8);
    w.varint(entries.size());
    std::optional<std::string> prev;
    for (std::size_t i = 0; i < entries.size(); ++i) {
        const auto& e = entries[i];
        if (!valid_name(e.name))
            return fail(ErrorKind::InvalidName, i);
        if (prev && compare(bytes_of(*prev), bytes_of(e.name)) >= 0)
            return fail(ErrorKind::Unsorted, i);
        if (!valid_tree_kind(e.kind))
            return fail(ErrorKind::InvalidValue, i);
        w.length_prefixed(e.name);
        w.u8(e.kind);
        w.id(e.target);
        prev = e.name;
    }
    return w.take();
}

// ---------------------------------------------------------------------------
// Commits
// ---------------------------------------------------------------------------

static Result<std::vector<Id>> read_parents(Reader& r) {
    const auto n = r.list_len(1024);
    if (!n)
        return unexpected(n.error());
    std::vector<Id> out;
    out.reserve(*n);
    for (std::size_t i = 0; i < *n; ++i) {
        const auto id = r.id();
        if (!id)
            return unexpected(id.error());
        out.push_back(*id);
    }
    return out;
}

static Result<std::vector<Rename>> read_renames(Reader& r, std::size_t parent_count,
                                                std::uint8_t state) {
    const auto n = r.list_len(1'000'000);
    if (!n)
        return unexpected(n.error());
    std::vector<Rename> out;
    if (state == RENAMES_UNKNOWN) {
        if (*n != 0)
            return fail(ErrorKind::InvalidValue, r.offset());
        return out;
    }
    out.reserve(*n);
    std::uint64_t prev_parent = 0;
    std::string prev_path;
    bool have_prev = false;
    for (std::size_t i = 0; i < *n; ++i) {
        const std::size_t at = r.offset();
        const auto parent = r.varint();
        if (!parent)
            return unexpected(parent.error());
        const auto kind = r.u8();
        if (!kind)
            return unexpected(kind.error());
        auto from = r.string_bytes(MAX_PATH_LEN);
        if (!from)
            return unexpected(from.error());
        auto to = r.string_bytes(MAX_PATH_LEN);
        if (!to)
            return unexpected(to.error());
        if (*parent >= parent_count)
            return fail(ErrorKind::InvalidValue, at);
        if (*kind > 1)
            return fail(ErrorKind::InvalidValue, at);
        if (!valid_path(*from) || !valid_path(*to))
            return fail(ErrorKind::InvalidName, at);
        if (have_prev) {
            if (*parent < prev_parent)
                return fail(ErrorKind::Unsorted, at);
            if (*parent == prev_parent && compare(bytes_of(prev_path), bytes_of(*to)) >= 0)
                return fail(ErrorKind::Unsorted, at);
        }
        out.push_back(Rename{*parent, *kind, std::move(*from), std::move(*to)});
        prev_parent = *parent;
        prev_path = out.back().to_path;
        have_prev = true;
    }
    return out;
}

static Result<std::vector<KeyValue>> read_extra(Reader& r) {
    const auto n = r.list_len(1024);
    if (!n)
        return unexpected(n.error());
    std::vector<KeyValue> out;
    out.reserve(*n);
    for (std::size_t i = 0; i < *n; ++i) {
        const std::size_t at = r.offset();
        auto key = r.string_bytes(MAX_NAME_LEN);
        if (!key)
            return unexpected(key.error());
        auto value = r.string_bytes(MAX_MESSAGE_LEN);
        if (!value)
            return unexpected(value.error());
        if (key->empty())
            return fail(ErrorKind::InvalidValue, at);
        out.push_back(KeyValue{std::move(*key), std::move(*value)});
    }
    return out;
}

Result<Commit> decode_commit(Bytes body) {
    Reader r(body);
    const auto version = r.u8();
    if (!version)
        return unexpected(version.error());
    if (*version != 1)
        return fail(ErrorKind::UnsupportedVersion, 0);
    Commit commit;
    commit.version = *version;
    auto parents = read_parents(r);
    if (!parents)
        return unexpected(parents.error());
    commit.parents = std::move(*parents);
    const auto root = r.id();
    if (!root)
        return unexpected(root.error());
    commit.root_tree = *root;
    const auto change = r.raw(CHANGE_ID_LEN);
    if (!change)
        return unexpected(change.error());
    std::memcpy(commit.change_id.data(), change->data(), CHANGE_ID_LEN);
    auto author = r.sig(MAX_NAME_LEN, MAX_NAME_LEN);
    if (!author)
        return unexpected(author.error());
    commit.author = Sig{author->name, author->email, author->seconds, author->tz_min};
    auto committer = r.sig(MAX_NAME_LEN, MAX_NAME_LEN);
    if (!committer)
        return unexpected(committer.error());
    commit.committer =
        Sig{committer->name, committer->email, committer->seconds, committer->tz_min};
    auto message = r.string_bytes(MAX_MESSAGE_LEN);
    if (!message)
        return unexpected(message.error());
    commit.message = std::move(*message);
    const auto state = r.u8();
    if (!state)
        return unexpected(state.error());
    if (*state > 1)
        return fail(ErrorKind::InvalidValue, r.offset() - 1);
    commit.renames_state = *state;
    auto renames = read_renames(r, commit.parents.size(), commit.renames_state);
    if (!renames)
        return unexpected(renames.error());
    commit.renames = std::move(*renames);
    auto extra = read_extra(r);
    if (!extra)
        return unexpected(extra.error());
    commit.extra = std::move(*extra);
    const auto fin = r.finish();
    if (!fin)
        return unexpected(fin.error());
    return commit;
}

std::vector<std::uint8_t> encode_commit(const Commit& commit) {
    ByteWriter w(256);
    w.u8(commit.version);
    w.varint(commit.parents.size());
    for (const auto& p : commit.parents)
        w.id(p);
    w.id(commit.root_tree);
    w.raw(Bytes(commit.change_id.data(), commit.change_id.size()));
    w.sig(Reader::Sig{commit.author.name, commit.author.email, commit.author.seconds,
                      commit.author.tz_min});
    w.sig(Reader::Sig{commit.committer.name, commit.committer.email, commit.committer.seconds,
                      commit.committer.tz_min});
    w.length_prefixed(commit.message);
    w.u8(commit.renames_state);
    w.varint(commit.renames.size());
    for (const auto& r : commit.renames) {
        w.varint(r.parent_index);
        w.u8(r.kind);
        w.length_prefixed(r.from_path);
        w.length_prefixed(r.to_path);
    }
    w.varint(commit.extra.size());
    for (const auto& kv : commit.extra) {
        w.length_prefixed(kv.key);
        w.length_prefixed(kv.value);
    }
    return w.take();
}

// ---------------------------------------------------------------------------
// Conflicts
// ---------------------------------------------------------------------------

static bool conflict_kind_valid(std::uint8_t kind) {
    return kind == 0 || (kind >= KIND_FILE && kind <= KIND_CONFLICT);
}

static Result<ConflictValue> read_conflict_value(Reader& r) {
    const std::size_t at = r.offset();
    const auto kind = r.u8();
    if (!kind)
        return unexpected(kind.error());
    if (!conflict_kind_valid(*kind))
        return fail(ErrorKind::InvalidValue, at);
    if (*kind == 0)
        return ConflictValue{0, std::nullopt};
    const auto target = r.id();
    if (!target)
        return unexpected(target.error());
    return ConflictValue{*kind, *target};
}

static Result<std::vector<ConflictValue>> read_conflict_values(Reader& r) {
    const auto n = r.list_len(MAX_CONFLICT_TERMS);
    if (!n)
        return unexpected(n.error());
    std::vector<ConflictValue> out;
    out.reserve(*n);
    for (std::size_t i = 0; i < *n; ++i) {
        auto value = read_conflict_value(r);
        if (!value)
            return unexpected(value.error());
        out.push_back(*value);
    }
    return out;
}

static bool conflict_value_equal(const ConflictValue& a, const ConflictValue& b) {
    if (a.kind != b.kind)
        return false;
    if (a.kind == 0)
        return true;
    return a.target == b.target;
}

Result<Conflict> decode_conflict(Bytes body) {
    Reader r(body);
    Conflict conflict;
    auto adds = read_conflict_values(r);
    if (!adds)
        return unexpected(adds.error());
    conflict.adds = std::move(*adds);
    auto removes = read_conflict_values(r);
    if (!removes)
        return unexpected(removes.error());
    conflict.removes = std::move(*removes);
    const std::size_t at = r.offset();
    const auto fin = r.finish();
    if (!fin)
        return unexpected(fin.error());
    if (conflict.removes.empty())
        return fail(ErrorKind::InvalidValue, at);
    if (conflict.adds.size() != conflict.removes.size() + 1)
        return fail(ErrorKind::InvalidValue, at);
    if (conflict.adds.size() + conflict.removes.size() > MAX_CONFLICT_TERMS)
        return fail(ErrorKind::LimitExceeded, at);
    for (const auto& a : conflict.adds) {
        for (const auto& rem : conflict.removes) {
            if (conflict_value_equal(a, rem))
                return fail(ErrorKind::InvalidValue, at);
        }
    }
    bool all_same = true;
    for (std::size_t i = 1; i < conflict.adds.size(); ++i) {
        if (!conflict_value_equal(conflict.adds[0], conflict.adds[i])) {
            all_same = false;
            break;
        }
    }
    if (all_same)
        return fail(ErrorKind::InvalidValue, at);
    return conflict;
}

std::vector<std::uint8_t> encode_conflict(const Conflict& conflict) {
    ByteWriter w((conflict.adds.size() + conflict.removes.size()) * 40 + 16);
    w.varint(conflict.adds.size());
    for (const auto& v : conflict.adds) {
        w.u8(v.kind);
        if (v.kind != 0 && v.target)
            w.id(*v.target);
    }
    w.varint(conflict.removes.size());
    for (const auto& v : conflict.removes) {
        w.u8(v.kind);
        if (v.kind != 0 && v.target)
            w.id(*v.target);
    }
    return w.take();
}

// ---------------------------------------------------------------------------
// Views
// ---------------------------------------------------------------------------

static bool view_name_valid(std::string_view name) {
    if (name.empty() || name.size() > MAX_NAME_LEN)
        return false;
    return name.find('\0') == std::string_view::npos;
}

static Result<std::vector<Id>> read_view_heads(Reader& r) {
    const auto n = r.list_len(1'000'000);
    if (!n)
        return unexpected(n.error());
    std::vector<Id> out;
    out.reserve(*n);
    std::optional<Id> prev;
    for (std::size_t i = 0; i < *n; ++i) {
        const std::size_t at = r.offset();
        const auto id = r.id();
        if (!id)
            return unexpected(id.error());
        if (prev) {
            const int c = std::memcmp(prev->data(), id->data(), ID_LEN);
            if (c == 0)
                return fail(ErrorKind::Duplicate, at);
            if (c > 0)
                return fail(ErrorKind::Unsorted, at);
        }
        out.push_back(*id);
        prev = *id;
    }
    return out;
}

static Result<std::vector<std::optional<Id>>> read_opt_id_list(Reader& r, std::size_t max) {
    const auto n = r.list_len(max);
    if (!n)
        return unexpected(n.error());
    std::vector<std::optional<Id>> out;
    out.reserve(*n);
    for (std::size_t i = 0; i < *n; ++i) {
        const auto id = r.opt_id();
        if (!id)
            return unexpected(id.error());
        out.push_back(*id);
    }
    return out;
}

static bool opt_id_contains(const std::vector<std::optional<Id>>& ids,
                            const std::optional<Id>& id) {
    for (const auto& x : ids) {
        if (x.has_value() == id.has_value()) {
            if (!x || std::memcmp(x->data(), id->data(), ID_LEN) == 0)
                return true;
        }
    }
    return false;
}

static Result<TargetSet> read_target_set(Reader& r) {
    const std::size_t at = r.offset();
    TargetSet set;
    auto adds = read_opt_id_list(r, 64);
    if (!adds)
        return unexpected(adds.error());
    set.adds = std::move(*adds);
    auto removes = read_opt_id_list(r, 64);
    if (!removes)
        return unexpected(removes.error());
    set.removes = std::move(*removes);
    if (set.adds.empty())
        return fail(ErrorKind::InvalidValue, at);
    if (set.adds.size() != set.removes.size() + 1)
        return fail(ErrorKind::InvalidValue, at);
    if (set.adds.size() + set.removes.size() > MAX_CONFLICT_TERMS)
        return fail(ErrorKind::LimitExceeded, at);
    for (const auto& a : set.adds) {
        if (opt_id_contains(set.removes, a))
            return fail(ErrorKind::InvalidValue, at);
    }
    bool all_same = true;
    for (std::size_t i = 1; i < set.adds.size(); ++i) {
        const bool same =
            set.adds[0].has_value() == set.adds[i].has_value() &&
            (!set.adds[0] || std::memcmp(set.adds[0]->data(), set.adds[i]->data(), ID_LEN) == 0);
        if (!same) {
            all_same = false;
            break;
        }
    }
    if (all_same && set.adds.size() > 1)
        return fail(ErrorKind::InvalidValue, at);
    return set;
}

static Result<std::vector<Bookmark>> read_bookmarks(Reader& r) {
    const auto n = r.list_len(1'000'000);
    if (!n)
        return unexpected(n.error());
    std::vector<Bookmark> out;
    out.reserve(*n);
    std::optional<std::string> prev;
    for (std::size_t i = 0; i < *n; ++i) {
        const std::size_t at = r.offset();
        auto name = r.string_bytes(MAX_NAME_LEN);
        if (!name)
            return unexpected(name.error());
        if (!view_name_valid(*name))
            return fail(ErrorKind::InvalidName, at);
        if (prev) {
            const int c = compare(bytes_of(*prev), bytes_of(*name));
            if (c == 0)
                return fail(ErrorKind::Duplicate, at);
            if (c > 0)
                return fail(ErrorKind::Unsorted, at);
        }
        auto targets = read_target_set(r);
        if (!targets)
            return unexpected(targets.error());
        out.push_back(Bookmark{std::move(*name), std::move(*targets)});
        prev = out.back().name;
    }
    return out;
}

static Result<std::vector<TagRef>> read_tags(Reader& r) {
    const auto n = r.list_len(1'000'000);
    if (!n)
        return unexpected(n.error());
    std::vector<TagRef> out;
    out.reserve(*n);
    std::optional<std::string> prev;
    for (std::size_t i = 0; i < *n; ++i) {
        const std::size_t at = r.offset();
        auto name = r.string_bytes(MAX_NAME_LEN);
        if (!name)
            return unexpected(name.error());
        if (!view_name_valid(*name))
            return fail(ErrorKind::InvalidName, at);
        if (prev) {
            const int c = compare(bytes_of(*prev), bytes_of(*name));
            if (c == 0)
                return fail(ErrorKind::Duplicate, at);
            if (c > 0)
                return fail(ErrorKind::Unsorted, at);
        }
        const auto id = r.id();
        if (!id)
            return unexpected(id.error());
        out.push_back(TagRef{std::move(*name), *id});
        prev = out.back().name;
    }
    return out;
}

static Result<std::vector<RemoteRef>> read_remote_refs(Reader& r) {
    const auto n = r.list_len(1'000'000);
    if (!n)
        return unexpected(n.error());
    std::vector<RemoteRef> out;
    out.reserve(*n);
    std::optional<std::pair<std::string, std::string>> prev;
    for (std::size_t i = 0; i < *n; ++i) {
        const std::size_t at = r.offset();
        auto remote = r.string_bytes(MAX_NAME_LEN);
        if (!remote)
            return unexpected(remote.error());
        auto name = r.string_bytes(MAX_NAME_LEN);
        if (!name)
            return unexpected(name.error());
        if (!view_name_valid(*remote) || !view_name_valid(*name))
            return fail(ErrorKind::InvalidName, at);
        if (prev) {
            const int c1 = compare(bytes_of(prev->first), bytes_of(*remote));
            const int c2 = c1 != 0 ? 0 : compare(bytes_of(prev->second), bytes_of(*name));
            if (c1 == 0 && c2 == 0)
                return fail(ErrorKind::Duplicate, at);
            if (c1 > 0 || (c1 == 0 && c2 > 0))
                return fail(ErrorKind::Unsorted, at);
        }
        const auto id = r.id();
        if (!id)
            return unexpected(id.error());
        out.push_back(RemoteRef{std::move(*remote), std::move(*name), *id});
        prev = std::make_pair(out.back().remote, out.back().name);
    }
    return out;
}

static Result<std::vector<WorkspaceRef>> read_workspaces(Reader& r) {
    const auto n = r.list_len(1'000'000);
    if (!n)
        return unexpected(n.error());
    std::vector<WorkspaceRef> out;
    out.reserve(*n);
    std::optional<std::string> prev;
    for (std::size_t i = 0; i < *n; ++i) {
        const std::size_t at = r.offset();
        auto workspace = r.string_bytes(MAX_NAME_LEN);
        if (!workspace)
            return unexpected(workspace.error());
        if (!view_name_valid(*workspace))
            return fail(ErrorKind::InvalidName, at);
        if (prev) {
            const int c = compare(bytes_of(*prev), bytes_of(*workspace));
            if (c == 0)
                return fail(ErrorKind::Duplicate, at);
            if (c > 0)
                return fail(ErrorKind::Unsorted, at);
        }
        const auto id = r.id();
        if (!id)
            return unexpected(id.error());
        out.push_back(WorkspaceRef{std::move(*workspace), *id});
        prev = out.back().workspace;
    }
    return out;
}

Result<View> decode_view(Bytes body) {
    Reader r(body);
    View view;
    auto heads = read_view_heads(r);
    if (!heads)
        return unexpected(heads.error());
    view.heads = std::move(*heads);
    auto bookmarks = read_bookmarks(r);
    if (!bookmarks)
        return unexpected(bookmarks.error());
    view.bookmarks = std::move(*bookmarks);
    auto tags = read_tags(r);
    if (!tags)
        return unexpected(tags.error());
    view.tags = std::move(*tags);
    auto remote_refs = read_remote_refs(r);
    if (!remote_refs)
        return unexpected(remote_refs.error());
    view.remote_refs = std::move(*remote_refs);
    auto workspaces = read_workspaces(r);
    if (!workspaces)
        return unexpected(workspaces.error());
    view.working_copies = std::move(*workspaces);
    const auto fin = r.finish();
    if (!fin)
        return unexpected(fin.error());
    return view;
}

static void put_target_set(ByteWriter& w, const TargetSet& set) {
    w.varint(set.adds.size());
    for (const auto& id : set.adds)
        w.opt_id(id);
    w.varint(set.removes.size());
    for (const auto& id : set.removes)
        w.opt_id(id);
}

std::vector<std::uint8_t> encode_view(const View& view) {
    ByteWriter w(256);
    w.varint(view.heads.size());
    for (const auto& id : view.heads)
        w.id(id);
    w.varint(view.bookmarks.size());
    for (const auto& bookmark : view.bookmarks) {
        w.length_prefixed(bookmark.name);
        put_target_set(w, bookmark.targets);
    }
    w.varint(view.tags.size());
    for (const auto& tag : view.tags) {
        w.length_prefixed(tag.name);
        w.id(tag.target);
    }
    w.varint(view.remote_refs.size());
    for (const auto& ref : view.remote_refs) {
        w.length_prefixed(ref.remote);
        w.length_prefixed(ref.name);
        w.id(ref.target);
    }
    w.varint(view.working_copies.size());
    for (const auto& workspace : view.working_copies) {
        w.length_prefixed(workspace.workspace);
        w.id(workspace.target);
    }
    return w.take();
}

// ---------------------------------------------------------------------------
// Operations
// ---------------------------------------------------------------------------

Result<Operation> decode_operation(Bytes body) {
    Reader r(body);
    Operation op;
    const auto parent_count = r.list_len(1024);
    if (!parent_count)
        return unexpected(parent_count.error());
    op.parents.reserve(*parent_count);
    for (std::size_t i = 0; i < *parent_count; ++i) {
        const auto id = r.id();
        if (!id)
            return unexpected(id.error());
        op.parents.push_back(*id);
    }
    const auto view = r.id();
    if (!view)
        return unexpected(view.error());
    op.view = *view;
    auto start = r.time_ms();
    if (!start)
        return unexpected(start.error());
    op.start = *start;
    auto end = r.time_ms();
    if (!end)
        return unexpected(end.error());
    op.end = *end;
    auto hostname = r.string_bytes(MAX_NAME_LEN);
    if (!hostname)
        return unexpected(hostname.error());
    op.hostname = std::move(*hostname);
    auto username = r.string_bytes(MAX_NAME_LEN);
    if (!username)
        return unexpected(username.error());
    op.username = std::move(*username);
    auto description = r.string_bytes(MAX_MESSAGE_LEN);
    if (!description)
        return unexpected(description.error());
    op.description = std::move(*description);
    const auto tag_count = r.list_len(1024);
    if (!tag_count)
        return unexpected(tag_count.error());
    op.tags.reserve(*tag_count);
    for (std::size_t i = 0; i < *tag_count; ++i) {
        const std::size_t at = r.offset();
        auto key = r.string_bytes(MAX_NAME_LEN);
        if (!key)
            return unexpected(key.error());
        auto value = r.string_bytes(MAX_MESSAGE_LEN);
        if (!value)
            return unexpected(value.error());
        if (key->empty())
            return fail(ErrorKind::InvalidValue, at);
        op.tags.push_back(KeyValue{std::move(*key), std::move(*value)});
    }
    const auto fin = r.finish();
    if (!fin)
        return unexpected(fin.error());
    return op;
}

std::vector<std::uint8_t> encode_operation(const Operation& op) {
    ByteWriter w(256);
    w.varint(op.parents.size());
    for (const auto& p : op.parents)
        w.id(p);
    w.id(op.view);
    w.time_ms(op.start);
    w.time_ms(op.end);
    w.length_prefixed(op.hostname);
    w.length_prefixed(op.username);
    w.length_prefixed(op.description);
    w.varint(op.tags.size());
    for (const auto& kv : op.tags) {
        w.length_prefixed(kv.key);
        w.length_prefixed(kv.value);
    }
    return w.take();
}

bool is_lazy_blob(const Id& id) {
    static constexpr std::uint8_t prefix[] = {'v', 'e', 'i', 'n', 's', '-',
                                              'g', 'i', 't', 'o', 'i', 'd'};
    return std::memcmp(id.data(), prefix, sizeof(prefix)) == 0;
}

} // namespace vn