navid/veins / ea3ea6b96e721105660cd9ea15ce43ea04777600d6e64c04753f3d38768cfea1 / xveins/src/core/common.h

common.h

← xveins/src/core · 14771 bytes · raw · download

#pragma once

#include <array>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <filesystem>
#include <map>
#include <mutex>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <system_error>
#include <variant>
#include <vector>

#if __has_include(<expected>)
#include <expected>
#endif

#include <blake3.h>

namespace vn {

namespace fs = std::filesystem;

using Bytes = std::span<const std::uint8_t>;
using MutBytes = std::span<std::uint8_t>;
using Id = std::array<std::uint8_t, 32>;
using ChangeId = std::array<std::uint8_t, 16>;

constexpr std::size_t ID_LEN = 32;
constexpr std::size_t CHANGE_ID_LEN = 16;
constexpr std::size_t MAX_NAME_LEN = 4096;
constexpr std::size_t MAX_PATH_LEN = 65536;
constexpr std::size_t MAX_MESSAGE_LEN = 16u * 1024u * 1024u;
constexpr std::size_t MAX_OBJECT_BODY = 64u * 1024u * 1024u;
constexpr std::size_t MAX_CHUNK_LEN = 256u * 1024u;
constexpr std::size_t MAX_MANIFEST_ENTRIES = 1024;
constexpr std::size_t MAX_TREE_ENTRIES = 1'000'000;
constexpr std::size_t MAX_CONFLICT_TERMS = 64;
constexpr std::size_t INLINE_THRESHOLD = 16u * 1024u;
// Bound recursive tree walks so a hostile tree cannot exhaust the stack.
constexpr std::size_t MAX_TREE_DEPTH = 512;
// Packs are read into memory; refuse absurdly large ones instead of relying on
// an allocation failure.
constexpr std::uint64_t MAX_STORE_PACK_BYTES = 8ull * 1024ull * 1024ull * 1024ull;

enum class ErrorKind {
    None,
    UnexpectedEnd,
    VarintOverflow,
    NonMinimalVarint,
    InvalidValue,
    LimitExceeded,
    InvalidName,
    Duplicate,
    Unsorted,
    TrailingBytes,
    UnsupportedVersion,
    InvalidMagic,
    HashMismatch,
    Corrupt,
    Io,
    Usage,
};

std::string_view error_kind_name(ErrorKind kind);

struct Error {
    ErrorKind kind = ErrorKind::None;
    std::size_t offset = 0;
    std::string message;

    Error() = default;
    Error(ErrorKind k, std::size_t off, std::string msg)
        : kind(k), offset(off), message(std::move(msg)) {}

    static Error decode(ErrorKind kind, std::size_t offset);
    static Error io(std::string message);
    static Error usage(std::string message);
};

#if defined(__cpp_lib_expected) && __cpp_lib_expected >= 202202L
template <typename T> using Result = std::expected<T, Error>;
template <typename E> using Unexpected = std::unexpected<E>;
#else
template <typename E> struct Unexpected {
    E err;
    explicit Unexpected(E value) : err(std::move(value)) {}
};

template <typename T, typename E> class Expected {
public:
    Expected(T&& value) : data_(std::in_place_index<0>, std::move(value)) {}
    Expected(const T& value) : data_(std::in_place_index<0>, value) {}
    Expected(Unexpected<E> value) : data_(std::in_place_index<1>, std::move(value.err)) {}

    [[nodiscard]] bool has_value() const {
        return data_.index() == 0;
    }
    explicit operator bool() const {
        return has_value();
    }
    T& operator*() {
        return std::get<0>(data_);
    }
    const T& operator*() const {
        return std::get<0>(data_);
    }
    T* operator->() {
        return &std::get<0>(data_);
    }
    const T* operator->() const {
        return &std::get<0>(data_);
    }
    T& value() {
        return std::get<0>(data_);
    }
    const T& value() const {
        return std::get<0>(data_);
    }
    E& error() {
        return std::get<1>(data_);
    }
    const E& error() const {
        return std::get<1>(data_);
    }

private:
    std::variant<T, E> data_;
};

template <typename E> class Expected<void, E> {
public:
    Expected() = default;
    Expected(Unexpected<E> value) : error_(std::move(value.err)) {}
    [[nodiscard]] bool has_value() const {
        return !error_.has_value();
    }
    explicit operator bool() const {
        return has_value();
    }
    E& error() {
        return *error_;
    }
    const E& error() const {
        return *error_;
    }

private:
    std::optional<E> error_;
};

template <typename T> using Result = Expected<T, Error>;
#endif

using Status = Result<void>;

inline Unexpected<Error> unexpected(Error error) {
    return Unexpected<Error>(std::move(error));
}
inline Status ok() {
    return {};
}
inline Unexpected<Error> fail(ErrorKind kind, std::size_t offset = 0) {
    return unexpected(Error::decode(kind, offset));
}
inline Unexpected<Error> fail_io(std::string message) {
    return unexpected(Error::io(std::move(message)));
}
inline Unexpected<Error> fail_usage(std::string message) {
    return unexpected(Error::usage(std::move(message)));
}


inline Bytes bytes_of(std::string_view s) {
    return Bytes(reinterpret_cast<const std::uint8_t*>(s.data()), s.size());
}
inline Bytes bytes_of(const std::vector<std::uint8_t>& v) {
    return Bytes(v.data(), v.size());
}
inline std::string_view str_of(Bytes b) {
    return std::string_view(reinterpret_cast<const char*>(b.data()), b.size());
}
inline std::string to_string(Bytes b) {
    return std::string(str_of(b));
}
inline bool equals(Bytes a, Bytes b) {
    return a.size() == b.size() && (a.empty() || std::memcmp(a.data(), b.data(), a.size()) == 0);
}
inline int compare(Bytes a, Bytes b) {
    const std::size_t n = std::min(a.size(), b.size());
    if (n != 0) {
        const int c = std::memcmp(a.data(), b.data(), n);
        if (c != 0)
            return c < 0 ? -1 : 1;
    }
    if (a.size() < b.size())
        return -1;
    if (a.size() > b.size())
        return 1;
    return 0;
}
inline bool ascii_iequals(Bytes a, Bytes b) {
    if (a.size() != b.size())
        return false;
    for (std::size_t i = 0; i < a.size(); ++i) {
        auto lower = [](std::uint8_t c) -> std::uint8_t {
            return (c >= 'A' && c <= 'Z') ? static_cast<std::uint8_t>(c + 32) : c;
        };
        if (lower(a[i]) != lower(b[i]))
            return false;
    }
    return true;
}
inline bool starts_with(Bytes value, Bytes prefix) {
    return value.size() >= prefix.size() && equals(value.first(prefix.size()), prefix);
}

std::string hex_encode(Bytes data);
std::string hex_encode(const Id& id);
bool hex_decode(std::string_view text, MutBytes out);
std::optional<Id> parse_id(std::string_view hex);
std::string base32_encode(const ChangeId& id);
bool base32_prefix_matches(std::string_view full, std::string_view prefix);


std::array<std::uint8_t, 32> blake3_hash(Bytes data);
Id object_id(std::uint8_t type_byte, Bytes body);
std::array<std::uint8_t, 16> random_change_id();
std::uint64_t random_u64();


class Reader {
public:
    explicit Reader(Bytes data) : data_(data) {}

    [[nodiscard]] std::size_t offset() const {
        return pos_;
    }
    [[nodiscard]] std::size_t remaining() const {
        return data_.size() - pos_;
    }
    [[nodiscard]] bool at_end() const {
        return pos_ >= data_.size();
    }

    Result<std::uint8_t> u8();
    Result<std::uint16_t> u16le();
    Result<std::uint32_t> u32le();
    Result<std::uint64_t> u64le();
    Result<std::int16_t> i16le();
    Result<std::int64_t> i64le();
    Result<std::uint64_t> varint();
    Result<Bytes> raw(std::size_t n);
    Result<Bytes> bytes(std::size_t max_len);
    Result<std::string> string_bytes(std::size_t max_len);
    Result<std::size_t> list_len(std::size_t max);
    Result<Id> id();
    Result<std::optional<Id>> opt_id();
    Result<void> finish();

    struct Sig {
        std::string name;
        std::string email;
        std::int64_t seconds = 0;
        std::int16_t tz_min = 0;
    };
    struct TimeMs {
        std::int64_t ms = 0;
        std::int16_t tz_min = 0;
    };

    Result<Sig> sig(std::size_t max_name, std::size_t max_email);
    Result<TimeMs> time_ms();

    static std::uint64_t read_u64le_at(Bytes data, std::size_t off);

private:
    Bytes data_;
    std::size_t pos_ = 0;
};

class ByteWriter {
public:
    explicit ByteWriter(std::size_t reserve = 64) {
        buf_.reserve(reserve);
    }

    void u8(std::uint8_t v);
    void u16le(std::uint16_t v);
    void u32le(std::uint32_t v);
    void u64le(std::uint64_t v);
    void i16le(std::int16_t v);
    void i64le(std::int64_t v);
    void varint(std::uint64_t v);
    void raw(Bytes data);
    void raw(std::string_view s) {
        raw(bytes_of(s));
    }
    void bytes(std::string_view s) {
        raw(s);
    }
    void length_prefixed(std::string_view s);
    void length_prefixed(Bytes b);
    void id(const Id& id);
    void opt_id(const std::optional<Id>& id);
    void sig(const Reader::Sig& s);
    void time_ms(const Reader::TimeMs& t);

    [[nodiscard]] Bytes view() const {
        return Bytes(buf_.data(), buf_.size());
    }
    [[nodiscard]] const std::vector<std::uint8_t>& data() const {
        return buf_;
    }
    [[nodiscard]] std::vector<std::uint8_t> take() {
        return std::move(buf_);
    }
    [[nodiscard]] std::size_t size() const {
        return buf_.size();
    }
    void clear() {
        buf_.clear();
    }
    void append(Bytes b) {
        raw(b);
    }
    void reserve(std::size_t n) {
        buf_.reserve(n);
    }

private:
    std::vector<std::uint8_t> buf_;
};


std::string format_utc(std::int64_t seconds);
std::int64_t unix_now_seconds();
std::int64_t unix_now_millis();
std::size_t available_cpu_count();

enum class Color {
    Default,
    Black,
    Red,
    Green,
    Yellow,
    Blue,
    Magenta,
    Cyan,
    BrightBlack,
    BrightRed,
    BrightGreen,
    BrightYellow,
    BrightBlue,
    BrightMagenta,
    BrightCyan,
    BrightWhite,
};

bool colors_enabled();
void print_colored(std::string_view text, Color color, bool dim = false, bool to_stderr = false);
void print_styled(std::string_view text, Color fg, bool dim, bool to_stderr = false);
void print_bold(std::string_view text, Color fg, bool to_stderr = false);
void error_prefix();
void warning_prefix();
void info_prefix();

// A lightweight, throttled progress bar drawn on stderr. It stays silent when
// stderr is not a terminal, so piped output is unchanged.
class Progress {
public:
    explicit Progress(std::string label, std::size_t total = 0);
    Progress(const Progress&) = delete;
    Progress& operator=(const Progress&) = delete;
    ~Progress();

    void set_total(std::size_t total);
    void update(std::size_t done, bool force = false);
    void advance(std::size_t amount = 1);
    void finish();
    void clear();

private:
    void refresh_locked(bool force);
    void draw_locked();

    std::mutex mutex_;
    std::string label_;
    std::size_t total_ = 0;
    std::size_t done_ = 0;
    std::size_t last_done_ = 0;
    std::size_t last_total_ = 0;
    bool enabled_ = false;
    bool drawn_ = false;
    bool finished_ = false;
    std::chrono::steady_clock::time_point last_draw_{};
};


fs::path path_from_bytes(std::string_view bytes);
std::string path_to_bytes(const fs::path& p);
std::string path_display(const fs::path& p);

Result<std::vector<std::uint8_t>> read_file(const fs::path& p, std::uint64_t max_size = 0);
std::optional<std::vector<std::uint8_t>> read_file_opt(const fs::path& p,
                                                       std::uint64_t max_size = 0);
std::optional<std::vector<std::uint8_t>> read_file_range(const fs::path& p, std::uint64_t offset,
                                                         std::size_t length);
bool write_file(const fs::path& p, Bytes data);
bool append_file(const fs::path& p, Bytes data);
bool write_atomic(const fs::path& final_path, Bytes data);
bool write_atomic(const fs::path& tmp_path, const fs::path& final_path, Bytes data);
bool ensure_directory(const fs::path& p);
bool remove_file(const fs::path& p);
bool remove_tree(const fs::path& p);
bool path_exists(const fs::path& p);
bool path_is_dir(const fs::path& p);
bool path_is_file(const fs::path& p);
bool path_is_symlink(const fs::path& p);
std::optional<std::uint64_t> path_file_size(const fs::path& p);
std::optional<std::uint64_t> file_mtime_ns(const fs::path& p);
std::optional<std::uint64_t> file_inode(const fs::path& p);
bool is_executable(const fs::path& p);
std::optional<std::string> path_read_symlink(const fs::path& p);
std::vector<std::string> list_directory(const fs::path& p);
bool same_or_under(const fs::path& child, const fs::path& parent);
std::string basename_string(const fs::path& p);

struct StatInfo {
    std::uint8_t kind = 0; // 0 missing, 1 file, 2 directory, 3 symlink
    bool executable = false;
    std::uint64_t size = 0;
    std::uint64_t mtime_ns = 0;
    std::uint64_t inode = 0;
};
std::optional<StatInfo> stat_path(const fs::path& p);


std::optional<std::string> repo_config_value(const fs::path& repo_root, std::string_view key);
bool repo_config_set(const fs::path& repo_root, std::string_view key, std::string_view value);
bool repo_config_remove(const fs::path& repo_root, std::string_view key);
bool repo_config_bool(const fs::path& repo_root, std::string_view key, bool fallback);

struct Sig {
    std::string name;
    std::string email;
    std::int64_t seconds = 0;
    std::int16_t tz_min = 0;
};

Sig identity_signature(const fs::path& repo_root);
std::optional<std::string> user_config_author_name();
std::optional<std::string> user_config_author_email();
std::optional<std::string> user_config_value(std::string_view key);
std::map<std::string, std::string> user_config_entries();
bool user_config_set(std::string_view key, std::string_view value);
bool user_config_remove(std::string_view key);

std::string editor_command(const fs::path& repo_root);
bool run_editor(const fs::path& repo_root, const std::vector<std::string>& paths,
                const std::optional<fs::path>& message_file = std::nullopt);
bool stdin_is_terminal();
bool stdout_is_terminal();
bool stderr_is_terminal();
std::string pager_command(const fs::path& repo_root);
bool run_pager(const fs::path& repo_root, std::string_view text);

std::optional<std::string> current_bookmark_name(const fs::path& repo_root);
bool set_current_bookmark(const fs::path& repo_root, std::string_view name);
bool clear_current_bookmark(const fs::path& repo_root);


struct IgnoreRule {
    std::string pattern;
    bool negated = false;
    bool dir_only = false;
    bool anchored = false;
    bool has_slash = false;
    std::string base;
};

struct IgnoreRules {
    std::vector<IgnoreRule> items;
};

IgnoreRules ignore_empty();
void ignore_load_file(IgnoreRules& rules, const fs::path& repo_root, std::string_view base,
                      std::string_view name);
void ignore_load_root(IgnoreRules& rules, const fs::path& repo_root);
bool ignore_ignored(const IgnoreRules& rules, std::string_view path, bool is_dir);
bool ignore_path_ignored(const fs::path& repo_root, std::string_view path);
bool glob_match(std::string_view pattern, std::string_view text);

} // namespace vn