navid/veins / 9d43af5809a4086fe4899784b3f2c54d2b901ca262a85d903cebc534b826ed2d / xveins/src/common.cpp

common.cpp

← xveins/src · 44505 bytes · raw · download

#include "common.h"

#include <algorithm>
#include <cerrno>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iostream>
#include <random>
#include <sstream>
#include <thread>

#if defined(_WIN32)
#include <bcrypt.h>
#include <fcntl.h>
#include <io.h>
#include <windows.h>
#else
#include <dirent.h>
#include <fcntl.h>
#include <sys/random.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#if defined(__linux__)
#include <sched.h>
#endif
#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) ||      \
    defined(__NetBSD__) || defined(__DragonFly__)
#include <stdlib.h>
#endif
#endif

namespace vn {

std::string_view error_kind_name(ErrorKind kind) {
  switch (kind) {
  case ErrorKind::None:
    return "none";
  case ErrorKind::UnexpectedEnd:
    return "unexpected end of input";
  case ErrorKind::VarintOverflow:
    return "varint overflow";
  case ErrorKind::NonMinimalVarint:
    return "non-minimal varint";
  case ErrorKind::InvalidValue:
    return "invalid value";
  case ErrorKind::LimitExceeded:
    return "format limit exceeded";
  case ErrorKind::InvalidName:
    return "invalid name";
  case ErrorKind::Duplicate:
    return "duplicate entry";
  case ErrorKind::Unsorted:
    return "entries are not sorted";
  case ErrorKind::TrailingBytes:
    return "trailing bytes";
  case ErrorKind::UnsupportedVersion:
    return "unsupported format version";
  case ErrorKind::InvalidMagic:
    return "bad file magic";
  case ErrorKind::HashMismatch:
    return "hash mismatch";
  case ErrorKind::Corrupt:
    return "corrupt data";
  case ErrorKind::Io:
    return "I/O error";
  case ErrorKind::Usage:
    return "usage error";
  }
  return "unknown error";
}

Error Error::decode(ErrorKind kind, std::size_t offset) {
  return Error{kind, offset, std::string(error_kind_name(kind))};
}
Error Error::io(std::string message) {
  return Error{ErrorKind::Io, 0, std::move(message)};
}
Error Error::usage(std::string message) {
  return Error{ErrorKind::Usage, 0, std::move(message)};
}

// ---------------------------------------------------------------------------
// Hex / base32
// ---------------------------------------------------------------------------

static char hex_digit(std::uint8_t v) {
  return static_cast<char>(v < 10 ? '0' + v : 'a' + (v - 10));
}

std::string hex_encode(Bytes data) {
  std::string out(data.size() * 2, '0');
  for (std::size_t i = 0; i < data.size(); ++i) {
    out[i * 2] = hex_digit(static_cast<std::uint8_t>(data[i] >> 4));
    out[i * 2 + 1] = hex_digit(static_cast<std::uint8_t>(data[i] & 15));
  }
  return out;
}

std::string hex_encode(const Id &id) {
  return hex_encode(Bytes(id.data(), id.size()));
}

static int hex_value(char c) {
  if (c >= '0' && c <= '9')
    return c - '0';
  if (c >= 'a' && c <= 'f')
    return c - 'a' + 10;
  if (c >= 'A' && c <= 'F')
    return c - 'A' + 10;
  return -1;
}

bool hex_decode(std::string_view text, MutBytes out) {
  if (text.size() != out.size() * 2)
    return false;
  for (std::size_t i = 0; i < out.size(); ++i) {
    const int hi = hex_value(text[i * 2]);
    const int lo = hex_value(text[i * 2 + 1]);
    if (hi < 0 || lo < 0)
      return false;
    out[i] = static_cast<std::uint8_t>((hi << 4) | lo);
  }
  return true;
}

std::optional<Id> parse_id(std::string_view hex) {
  if (hex.size() != ID_LEN * 2)
    return std::nullopt;
  Id id{};
  if (!hex_decode(hex, MutBytes(id.data(), id.size())))
    return std::nullopt;
  return id;
}

std::string base32_encode(const ChangeId &id) {
  static constexpr char alphabet[] = "abcdefghijklmnopqrstuvwxyz234567";
  std::string out;
  out.reserve(26);
  std::uint64_t buffer = 0;
  std::size_t bits = 0;
  for (std::uint8_t c : id) {
    buffer = (buffer << 8) | c;
    bits += 8;
    while (bits >= 5) {
      const std::size_t shift = bits - 5;
      const std::size_t index = (buffer >> shift) & 31u;
      out.push_back(alphabet[index]);
      bits = shift;
    }
    if (bits == 0) {
      buffer = 0;
    } else {
      buffer &= (std::uint64_t{1} << bits) - 1;
    }
  }
  if (bits > 0) {
    out.push_back(alphabet[(buffer << (5 - bits)) & 31u]);
  }
  return out;
}

bool base32_prefix_matches(std::string_view full, std::string_view prefix) {
  if (prefix.empty() || prefix.size() > full.size())
    return false;
  for (std::size_t i = 0; i < prefix.size(); ++i) {
    char c = prefix[i];
    if (c >= 'A' && c <= 'Z')
      c = static_cast<char>(c + 32);
    if (full[i] != c)
      return false;
  }
  return true;
}

// ---------------------------------------------------------------------------
// Hashing and randomness
// ---------------------------------------------------------------------------

std::array<std::uint8_t, 32> blake3_hash(Bytes data) {
  std::array<std::uint8_t, 32> out{};
  blake3_hasher hasher;
  blake3_hasher_init(&hasher);
  if (!data.empty())
    blake3_hasher_update(&hasher, data.data(), data.size());
  blake3_hasher_finalize(&hasher, out.data(), out.size());
  return out;
}

Id object_id(std::uint8_t type_byte, Bytes body) {
  static constexpr std::uint8_t prefix[] = {'v', 'e', 'i', 'n',
                                            's', '/', '1', 0};
  blake3_hasher hasher;
  blake3_hasher_init(&hasher);
  blake3_hasher_update(&hasher, prefix, sizeof(prefix));
  blake3_hasher_update(&hasher, &type_byte, 1);
  if (!body.empty())
    blake3_hasher_update(&hasher, body.data(), body.size());
  Id out{};
  blake3_hasher_finalize(&hasher, out.data(), out.size());
  return out;
}

static void os_random_bytes(MutBytes out) {
#if defined(_WIN32)
  if (BCryptGenRandom(nullptr, out.data(), static_cast<ULONG>(out.size()),
                      BCRYPT_USE_SYSTEM_PREFERRED_RNG) == 0) {
    return;
  }
#elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) ||    \
    defined(__NetBSD__) || defined(__DragonFly__)
  arc4random_buf(out.data(), out.size());
  return;
#else
  std::size_t done = 0;
  while (done < out.size()) {
    const ssize_t n = ::getrandom(out.data() + done, out.size() - done, 0);
    if (n > 0) {
      done += static_cast<std::size_t>(n);
      continue;
    }
    if (n < 0 && errno == EINTR)
      continue;
    break;
  }
  if (done == out.size())
    return;
#endif
  std::random_device rd;
  for (std::size_t i = 0; i < out.size(); ++i) {
    out[i] = static_cast<std::uint8_t>(rd());
  }
}

std::array<std::uint8_t, 16> random_change_id() {
  std::array<std::uint8_t, 16> out{};
  os_random_bytes(MutBytes(out.data(), out.size()));
  return out;
}

std::uint64_t random_u64() {
  std::uint64_t value = 0;
  os_random_bytes(
      MutBytes(reinterpret_cast<std::uint8_t *>(&value), sizeof(value)));
  return value;
}

// ---------------------------------------------------------------------------
// Reader / writer
// ---------------------------------------------------------------------------

Result<std::uint8_t> Reader::u8() {
  if (pos_ >= data_.size())
    return fail(ErrorKind::UnexpectedEnd, pos_);
  return data_[pos_++];
}

Result<std::uint16_t> Reader::u16le() {
  if (remaining() < 2)
    return fail(ErrorKind::UnexpectedEnd, pos_);
  const auto v = static_cast<std::uint16_t>(
      static_cast<std::uint16_t>(data_[pos_]) |
      static_cast<std::uint16_t>(static_cast<std::uint16_t>(data_[pos_ + 1])
                                 << 8));
  pos_ += 2;
  return v;
}

Result<std::uint32_t> Reader::u32le() {
  if (remaining() < 4)
    return fail(ErrorKind::UnexpectedEnd, pos_);
  std::uint32_t v = 0;
  for (std::size_t i = 0; i < 4; ++i) {
    v |= static_cast<std::uint32_t>(data_[pos_ + i]) << (i * 8);
  }
  pos_ += 4;
  return v;
}

Result<std::uint64_t> Reader::u64le() {
  if (remaining() < 8)
    return fail(ErrorKind::UnexpectedEnd, pos_);
  std::uint64_t v = 0;
  for (int i = 0; i < 8; ++i) {
    v |= static_cast<std::uint64_t>(data_[pos_ + static_cast<std::size_t>(i)])
         << (i * 8);
  }
  pos_ += 8;
  return v;
}

Result<std::int16_t> Reader::i16le() {
  const auto v = u16le();
  if (!v)
    return unexpected(v.error());
  return static_cast<std::int16_t>(*v);
}

Result<std::int64_t> Reader::i64le() {
  const auto v = u64le();
  if (!v)
    return unexpected(v.error());
  return static_cast<std::int64_t>(*v);
}

Result<std::uint64_t> Reader::varint() {
  const std::size_t start = pos_;
  std::uint64_t value = 0;
  unsigned shift = 0;
  for (unsigned i = 0; i < 10; ++i) {
    const auto b = u8();
    if (!b)
      return unexpected(b.error());
    const std::uint64_t low = static_cast<std::uint64_t>(*b & 127u);
    if (shift == 63 && low > 1)
      return fail(ErrorKind::VarintOverflow, start);
    value |= low << shift;
    if ((*b & 128u) == 0) {
      if (i > 0 && low == 0)
        return fail(ErrorKind::NonMinimalVarint, start);
      return value;
    }
    shift += 7;
  }
  return fail(ErrorKind::VarintOverflow, start);
}

Result<Bytes> Reader::raw(std::size_t n) {
  if (n > remaining())
    return fail(ErrorKind::UnexpectedEnd, pos_);
  const Bytes out = data_.subspan(pos_, n);
  pos_ += n;
  return out;
}

Result<Bytes> Reader::bytes(std::size_t max_len) {
  const std::size_t at = pos_;
  const auto n = varint();
  if (!n)
    return unexpected(n.error());
  if (*n > max_len)
    return fail(ErrorKind::LimitExceeded, at);
  if (*n > remaining())
    return fail(ErrorKind::UnexpectedEnd, at);
  return raw(static_cast<std::size_t>(*n));
}

Result<std::string> Reader::string_bytes(std::size_t max_len) {
  const auto b = bytes(max_len);
  if (!b)
    return unexpected(b.error());
  return std::string(str_of(*b));
}

Result<std::size_t> Reader::list_len(std::size_t max) {
  const std::size_t at = pos_;
  const auto n = varint();
  if (!n)
    return unexpected(n.error());
  if (*n > max)
    return fail(ErrorKind::LimitExceeded, at);
  return static_cast<std::size_t>(*n);
}

Result<Id> Reader::id() {
  const auto b = raw(ID_LEN);
  if (!b)
    return unexpected(b.error());
  Id out{};
  std::memcpy(out.data(), b->data(), ID_LEN);
  return out;
}

Result<std::optional<Id>> Reader::opt_id() {
  const std::size_t at = pos_;
  const auto tag = u8();
  if (!tag)
    return unexpected(tag.error());
  if (*tag == 0)
    return std::optional<Id>{};
  if (*tag != 1)
    return fail(ErrorKind::InvalidValue, at);
  const auto value = id();
  if (!value)
    return unexpected(value.error());
  return std::optional<Id>(*value);
}

Result<void> Reader::finish() {
  if (pos_ != data_.size())
    return fail(ErrorKind::TrailingBytes, pos_);
  return {};
}

Result<Reader::Sig> Reader::sig(std::size_t max_name, std::size_t max_email) {
  Sig out;
  const auto name = string_bytes(max_name);
  if (!name)
    return unexpected(name.error());
  const auto email = string_bytes(max_email);
  if (!email)
    return unexpected(email.error());
  const auto secs = i64le();
  if (!secs)
    return unexpected(secs.error());
  const auto tz = i16le();
  if (!tz)
    return unexpected(tz.error());
  out.name = *name;
  out.email = *email;
  out.seconds = *secs;
  out.tz_min = *tz;
  return out;
}

Result<Reader::TimeMs> Reader::time_ms() {
  TimeMs out;
  const auto ms = i64le();
  if (!ms)
    return unexpected(ms.error());
  const auto tz = i16le();
  if (!tz)
    return unexpected(tz.error());
  out.ms = *ms;
  out.tz_min = *tz;
  return out;
}

std::uint64_t Reader::read_u64le_at(Bytes data, std::size_t off) {
  std::uint64_t v = 0;
  for (std::size_t i = 0; i < 8; ++i)
    v |= static_cast<std::uint64_t>(data[off + i]) << (i * 8);
  return v;
}

void ByteWriter::u8(std::uint8_t v) { buf_.push_back(v); }

void ByteWriter::u16le(std::uint16_t v) {
  buf_.push_back(static_cast<std::uint8_t>(v & 255u));
  buf_.push_back(static_cast<std::uint8_t>((v >> 8) & 255u));
}

void ByteWriter::u32le(std::uint32_t v) {
  for (int i = 0; i < 4; ++i)
    buf_.push_back(static_cast<std::uint8_t>((v >> (i * 8)) & 255u));
}

void ByteWriter::u64le(std::uint64_t v) {
  for (int i = 0; i < 8; ++i)
    buf_.push_back(static_cast<std::uint8_t>((v >> (i * 8)) & 255u));
}

void ByteWriter::i16le(std::int16_t v) { u16le(static_cast<std::uint16_t>(v)); }
void ByteWriter::i64le(std::int64_t v) { u64le(static_cast<std::uint64_t>(v)); }

void ByteWriter::varint(std::uint64_t v) {
  for (;;) {
    const std::uint8_t low = static_cast<std::uint8_t>(v & 127u);
    v >>= 7;
    if (v == 0) {
      buf_.push_back(low);
      return;
    }
    buf_.push_back(static_cast<std::uint8_t>(low | 128u));
  }
}

void ByteWriter::raw(Bytes data) {
  if (!data.empty()) {
    buf_.insert(buf_.end(), data.begin(), data.end());
  }
}

void ByteWriter::length_prefixed(std::string_view s) {
  length_prefixed(bytes_of(s));
}
void ByteWriter::length_prefixed(Bytes b) {
  varint(b.size());
  raw(b);
}

void ByteWriter::id(const Id &id) { raw(Bytes(id.data(), id.size())); }

void ByteWriter::opt_id(const std::optional<Id> &id) {
  if (!id) {
    u8(0);
    return;
  }
  u8(1);
  this->id(*id);
}

void ByteWriter::sig(const Reader::Sig &s) {
  length_prefixed(s.name);
  length_prefixed(s.email);
  i64le(s.seconds);
  i16le(s.tz_min);
}

void ByteWriter::time_ms(const Reader::TimeMs &t) {
  i64le(t.ms);
  i16le(t.tz_min);
}

// ---------------------------------------------------------------------------
// Time / terminal
// ---------------------------------------------------------------------------

std::size_t available_cpu_count() {
#if defined(_WIN32)
  const DWORD count = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
  return count == 0 ? 1 : static_cast<std::size_t>(count);
#elif defined(__linux__)
  cpu_set_t set;
  CPU_ZERO(&set);
  if (sched_getaffinity(0, sizeof(set), &set) == 0) {
    const auto *bytes = reinterpret_cast<const unsigned char *>(&set);
    std::size_t count = 0;
    for (std::size_t i = 0; i < sizeof(set); ++i) {
      unsigned char value = bytes[i];
      while (value != 0) {
        count += value & 1u;
        value >>= 1;
      }
    }
    if (count != 0)
      return count;
  }
  const long n = sysconf(_SC_NPROCESSORS_ONLN);
  return n > 0 ? static_cast<std::size_t>(n) : 1;
#else
  const long n = sysconf(_SC_NPROCESSORS_ONLN);
  return n > 0 ? static_cast<std::size_t>(n) : 1;
#endif
}

std::int64_t unix_now_seconds() {
  return std::chrono::duration_cast<std::chrono::seconds>(
             std::chrono::system_clock::now().time_since_epoch())
      .count();
}

std::int64_t unix_now_millis() {
  return std::chrono::duration_cast<std::chrono::milliseconds>(
             std::chrono::system_clock::now().time_since_epoch())
      .count();
}

static std::int64_t floor_div(std::int64_t a, std::int64_t b) {
  std::int64_t q = a / b;
  const std::int64_t r = a % b;
  if (r != 0 && ((r < 0) != (b < 0)))
    --q;
  return q;
}

static void append_pad(std::string &out, std::int64_t value, int width) {
  if (value < 0)
    value = 0;
  std::string digits;
  do {
    digits.push_back(static_cast<char>('0' + (value % 10)));
    value /= 10;
  } while (value > 0);
  for (int i = static_cast<int>(digits.size()); i < width; ++i)
    out.push_back('0');
  for (auto it = digits.rbegin(); it != digits.rend(); ++it)
    out.push_back(*it);
}

std::string format_utc(std::int64_t seconds) {
  const std::int64_t days = floor_div(seconds, 86400);
  const std::int64_t rem = seconds - days * 86400;
  const std::int64_t hour = rem / 3600;
  const std::int64_t minute = (rem % 3600) / 60;
  const std::int64_t second = rem % 60;

  const std::int64_t z = days + 719468;
  const std::int64_t era = floor_div(z, 146097);
  const std::int64_t doe = z - era * 146097;
  const std::int64_t yoe =
      (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
  const std::int64_t y0 = yoe + era * 400;
  const std::int64_t doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
  const std::int64_t mp = (5 * doy + 2) / 153;
  const std::int64_t d = doy - (153 * mp + 2) / 5 + 1;
  const std::int64_t m0 = mp + 3;
  const std::int64_t m = mp >= 10 ? mp - 9 : m0;
  const std::int64_t y = m <= 2 ? y0 + 1 : y0;

  std::string out;
  out.reserve(19);
  append_pad(out, y, 4);
  out.push_back('-');
  append_pad(out, m, 2);
  out.push_back('-');
  append_pad(out, d, 2);
  out.push_back(' ');
  append_pad(out, hour, 2);
  out.push_back(':');
  append_pad(out, minute, 2);
  out.push_back(':');
  append_pad(out, second, 2);
  return out;
}

static bool g_colors = false;
static bool g_colors_checked = false;

bool colors_enabled() {
  if (g_colors_checked)
    return g_colors;
  g_colors_checked = true;
  if (std::getenv("NO_COLOR") != nullptr)
    return false;
#if defined(_WIN32)
  const bool tty = _isatty(_fileno(stdout)) != 0;
  bool ansi = false;
  if (tty) {
    HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
    DWORD mode = 0;
    if (h != INVALID_HANDLE_VALUE && GetConsoleMode(h, &mode)) {
      ansi = SetConsoleMode(h, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING) != 0;
    }
  }
  if (!ansi)
    return false;
#else
  const bool tty = ::isatty(STDOUT_FILENO) != 0;
#endif
  const char *forced = std::getenv("FORCE_COLOR");
  if (forced != nullptr && *forced != '\0' && std::strcmp(forced, "0") != 0) {
    g_colors = true;
    return true;
  }
  if (!tty)
    return false;
  const char *term = std::getenv("TERM");
  if (term != nullptr && std::strcmp(term, "dumb") == 0)
    return false;
  g_colors = true;
  return true;
}

static std::string_view color_code(Color c) {
  switch (c) {
  case Color::Default:
    return "\x1b[39m";
  case Color::Black:
    return "\x1b[30m";
  case Color::Red:
    return "\x1b[31m";
  case Color::Green:
    return "\x1b[32m";
  case Color::Yellow:
    return "\x1b[33m";
  case Color::Blue:
    return "\x1b[34m";
  case Color::Magenta:
    return "\x1b[35m";
  case Color::Cyan:
    return "\x1b[36m";
  case Color::BrightBlack:
    return "\x1b[90m";
  case Color::BrightRed:
    return "\x1b[91m";
  case Color::BrightGreen:
    return "\x1b[92m";
  case Color::BrightYellow:
    return "\x1b[93m";
  case Color::BrightBlue:
    return "\x1b[94m";
  case Color::BrightMagenta:
    return "\x1b[95m";
  case Color::BrightCyan:
    return "\x1b[96m";
  case Color::BrightWhite:
    return "\x1b[97m";
  }
  return "\x1b[39m";
}

void print_styled(std::string_view text, Color fg, bool dim, bool to_stderr) {
  (void)to_stderr;
  auto &stream = std::cout;
  if (!colors_enabled()) {
    stream << text;
    return;
  }
  if (dim)
    stream << "\x1b[2m";
  if (fg != Color::Default)
    stream << color_code(fg);
  stream << text;
  stream << "\x1b[0m";
}

void print_colored(std::string_view text, Color color, bool dim,
                   bool to_stderr) {
  print_styled(text, color, dim, to_stderr);
}

void print_bold(std::string_view text, Color fg, bool to_stderr) {
  (void)to_stderr;
  auto &stream = std::cout;
  if (!colors_enabled()) {
    stream << text;
    return;
  }
  stream << "\x1b[1m";
  if (fg != Color::Default)
    stream << color_code(fg);
  stream << text << "\x1b[0m";
}

void error_prefix() {
  print_bold("error", Color::Red, false);
  std::cout << ": ";
}
void warning_prefix() {
  print_bold("warning", Color::Yellow, false);
  std::cout << ": ";
}
void info_prefix() {
  print_styled("info", Color::Cyan, false, false);
  std::cout << ": ";
}

// ---------------------------------------------------------------------------
// Filesystem
// ---------------------------------------------------------------------------

fs::path path_from_bytes(std::string_view bytes) {
#if defined(_WIN32)
  std::u8string u;
  u.reserve(bytes.size());
  for (char c : bytes)
    u.push_back(static_cast<char8_t>(c));
  return fs::path(u);
#else
  return fs::path(std::string(bytes));
#endif
}

std::string path_to_bytes(const fs::path &p) {
#if defined(_WIN32)
  const std::u8string u = p.u8string();
  return std::string(reinterpret_cast<const char *>(u.data()), u.size());
#else
  return p.native();
#endif
}

std::string path_display(const fs::path &p) { return path_to_bytes(p); }

bool path_exists(const fs::path &p) {
  std::error_code ec;
  return fs::exists(p, ec);
}

bool path_is_dir(const fs::path &p) {
  std::error_code ec;
  return fs::is_directory(p, ec);
}

bool path_is_file(const fs::path &p) {
  std::error_code ec;
  return fs::is_regular_file(p, ec);
}

bool path_is_symlink(const fs::path &p) {
  std::error_code ec;
  return fs::is_symlink(fs::symlink_status(p, ec));
}

std::optional<std::uint64_t> path_file_size(const fs::path &p) {
  std::error_code ec;
  const auto n = fs::file_size(p, ec);
  if (ec)
    return std::nullopt;
  return static_cast<std::uint64_t>(n);
}

std::string basename_string(const fs::path &p) {
  return path_to_bytes(p.filename());
}

std::optional<std::vector<std::uint8_t>> read_file_opt(const fs::path &p) {
#if defined(_WIN32)
  std::ifstream in(p, std::ios::binary);
  if (!in)
    return std::nullopt;
  in.seekg(0, std::ios::end);
  const std::streamoff n = in.tellg();
  if (n < 0)
    return std::nullopt;
  in.seekg(0, std::ios::beg);
  std::vector<std::uint8_t> data(static_cast<std::size_t>(n));
  if (n > 0 && !in.read(reinterpret_cast<char *>(data.data()), n)) {
    return std::nullopt;
  }
  return data;
#else
  const int fd = ::open(p.c_str(), O_RDONLY);
  if (fd < 0)
    return std::nullopt;
  struct stat st {};
  if (::fstat(fd, &st) != 0 || st.st_size < 0) {
    ::close(fd);
    return std::nullopt;
  }
  std::vector<std::uint8_t> data(static_cast<std::size_t>(st.st_size));
  std::size_t done = 0;
  while (done < data.size()) {
    const ssize_t n = ::read(fd, data.data() + done, data.size() - done);
    if (n > 0) {
      done += static_cast<std::size_t>(n);
    } else if (n < 0 && errno == EINTR) {
      continue;
    } else {
      ::close(fd);
      return std::nullopt;
    }
  }
  ::close(fd);
  return data;
#endif
}

Result<std::vector<std::uint8_t>> read_file(const fs::path &p) {
  auto data = read_file_opt(p);
  if (!data)
    return fail_io("cannot read " + path_display(p));
  return *data;
}

static bool sync_file_path(const fs::path &p) {
#if defined(_WIN32)
  const int fd = _wopen(p.c_str(), _O_RDWR | _O_BINARY);
  if (fd < 0)
    return false;
  const bool ok = _commit(fd) == 0;
  _close(fd);
  return ok;
#else
  const int fd = ::open(p.c_str(), O_RDONLY);
  if (fd < 0)
    return false;
  const bool ok = ::fsync(fd) == 0;
  ::close(fd);
  return ok;
#endif
}

static void sync_parent_directory(const fs::path &p) {
#if defined(_WIN32)
  (void)p;
#else
  const fs::path parent = p.parent_path();
  if (parent.empty())
    return;
#if defined(__linux__)
  const int fd = ::open(parent.c_str(), O_RDONLY | O_DIRECTORY);
#else
  const int fd = ::open(parent.c_str(), O_RDONLY);
#endif
  if (fd >= 0) {
    (void)::fsync(fd);
    ::close(fd);
  }
#endif
}

static bool replace_file(const fs::path &from, const fs::path &to) {
#if defined(_WIN32)
  return MoveFileExW(from.c_str(), to.c_str(),
                     MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != 0;
#else
  return std::rename(from.c_str(), to.c_str()) == 0;
#endif
}

bool write_file(const fs::path &p, Bytes data) {
  std::error_code ec;
  if (!p.parent_path().empty())
    fs::create_directories(p.parent_path(), ec);
#if defined(_WIN32)
  std::ofstream out(p, std::ios::binary | std::ios::trunc);
  if (!out)
    return false;
  if (!data.empty()) {
    out.write(reinterpret_cast<const char *>(data.data()),
              static_cast<std::streamsize>(data.size()));
  }
  out.flush();
  return static_cast<bool>(out);
#else
  const int fd = ::open(p.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
  if (fd < 0)
    return false;
  std::size_t done = 0;
  while (done < data.size()) {
    const ssize_t n = ::write(fd, data.data() + done, data.size() - done);
    if (n > 0) {
      done += static_cast<std::size_t>(n);
    } else if (n < 0 && errno == EINTR) {
      continue;
    } else {
      ::close(fd);
      return false;
    }
  }
  if (::close(fd) != 0)
    return false;
  return true;
#endif
}

bool append_file(const fs::path &p, Bytes data) {
  std::error_code ec;
  if (!p.parent_path().empty())
    fs::create_directories(p.parent_path(), ec);
#if defined(_WIN32)
  std::ofstream out(p, std::ios::binary | std::ios::app);
  if (!out)
    return false;
  if (!data.empty()) {
    out.write(reinterpret_cast<const char *>(data.data()),
              static_cast<std::streamsize>(data.size()));
  }
  out.flush();
  return static_cast<bool>(out);
#else
  const int fd = ::open(p.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0644);
  if (fd < 0)
    return false;
  std::size_t done = 0;
  while (done < data.size()) {
    const ssize_t n = ::write(fd, data.data() + done, data.size() - done);
    if (n > 0) {
      done += static_cast<std::size_t>(n);
    } else if (n < 0 && errno == EINTR) {
      continue;
    } else {
      ::close(fd);
      return false;
    }
  }
  if (::close(fd) != 0)
    return false;
  return true;
#endif
}

bool write_atomic(const fs::path &tmp_path, const fs::path &final_path,
                  Bytes data) {
  std::error_code ec;
  if (!tmp_path.parent_path().empty())
    fs::create_directories(tmp_path.parent_path(), ec);
  if (!final_path.parent_path().empty())
    fs::create_directories(final_path.parent_path(), ec);
  if (!write_file(tmp_path, data))
    return false;
  if (!sync_file_path(tmp_path)) {
    remove_file(tmp_path);
    return false;
  }
  if (!replace_file(tmp_path, final_path)) {
    remove_file(tmp_path);
    return false;
  }
  sync_parent_directory(final_path);
  return true;
}

bool write_atomic(const fs::path &final_path, Bytes data) {
  const fs::path dir = final_path.parent_path();
  const std::string name = basename_string(final_path);
  const std::string tmp_name =
      "." + name + ".tmp." +
      std::to_string(static_cast<unsigned long>(random_u64()));
  return write_atomic(dir / tmp_name, final_path, data);
}

bool ensure_directory(const fs::path &p) {
  std::error_code ec;
  fs::create_directories(p, ec);
  return !ec;
}

bool remove_file(const fs::path &p) {
  std::error_code ec;
  return fs::remove(p, ec);
}

bool remove_tree(const fs::path &p) {
  std::error_code ec;
  fs::remove_all(p, ec);
  return !ec;
}

std::vector<std::string> list_directory(const fs::path &p) {
  std::vector<std::string> out;
#if defined(_WIN32)
  std::error_code ec;
  fs::directory_iterator it(p, ec);
  if (ec)
    return out;
  for (const auto &entry : it)
    out.push_back(path_to_bytes(entry.path().filename()));
#else
  DIR *dir = ::opendir(p.c_str());
  if (dir == nullptr)
    return out;
  while (dirent *entry = ::readdir(dir)) {
    const char *name = entry->d_name;
    if (std::strcmp(name, ".") == 0 || std::strcmp(name, "..") == 0)
      continue;
    out.emplace_back(name);
  }
  ::closedir(dir);
#endif
  return out;
}

bool same_or_under(const fs::path &child, const fs::path &parent) {
  std::error_code ec;
  const fs::path c = fs::weakly_canonical(child, ec);
  if (ec)
    return false;
  const fs::path p = fs::weakly_canonical(parent, ec);
  if (ec)
    return false;
  auto ci = c.begin();
  auto pi = p.begin();
  for (; pi != p.end(); ++pi, ++ci) {
    if (ci == c.end() || *ci != *pi)
      return false;
  }
  return true;
}

std::optional<std::string> path_read_symlink(const fs::path &p) {
  std::error_code ec;
  const fs::path target = fs::read_symlink(p, ec);
  if (ec)
    return std::nullopt;
  return path_to_bytes(target);
}

#if defined(_WIN32)
static std::optional<std::uint64_t> mtime_from_file_time(const fs::path &p) {
  std::error_code ec;
  const auto ft = fs::last_write_time(p, ec);
  if (ec)
    return std::nullopt;
  // Convert the filesystem clock value to Unix nanoseconds without assuming
  // a particular epoch offset: compare against a known reference point.
  const auto now_file = fs::file_time_type::clock::now();
  const auto now_sys = std::chrono::system_clock::now();
  const auto delta =
      std::chrono::duration_cast<std::chrono::nanoseconds>(ft - now_file);
  const auto sys = now_sys + delta;
  return static_cast<std::uint64_t>(
      std::chrono::duration_cast<std::chrono::nanoseconds>(
          sys.time_since_epoch())
          .count());
}
#endif

std::optional<StatInfo> stat_path(const fs::path &p) {
#if defined(_WIN32)
  std::error_code ec;
  const auto status = fs::symlink_status(p, ec);
  if (ec || status.type() == fs::file_type::not_found)
    return std::nullopt;
  StatInfo info;
  if (fs::is_symlink(status)) {
    info.kind = 3;
  } else if (fs::is_directory(status)) {
    info.kind = 2;
  } else if (fs::is_regular_file(status)) {
    info.kind = 1;
  } else {
    return std::nullopt;
  }
  if (info.kind == 1) {
    info.size = path_file_size(p).value_or(0);
  }
  info.mtime_ns = mtime_from_file_time(p).value_or(0);
  return info;
#else
  struct stat st {};
  if (::lstat(p.c_str(), &st) != 0)
    return std::nullopt;
  StatInfo info;
  if (S_ISLNK(st.st_mode)) {
    info.kind = 3;
  } else if (S_ISDIR(st.st_mode)) {
    info.kind = 2;
  } else if (S_ISREG(st.st_mode)) {
    info.kind = 1;
  } else {
    return std::nullopt;
  }
  info.executable = (st.st_mode & 0111) != 0;
  info.size = static_cast<std::uint64_t>(st.st_size);
  info.inode = static_cast<std::uint64_t>(st.st_ino);
#if defined(__APPLE__)
  info.mtime_ns =
      static_cast<std::uint64_t>(st.st_mtimespec.tv_sec) * 1'000'000'000ull +
      static_cast<std::uint64_t>(st.st_mtimespec.tv_nsec);
#else
  info.mtime_ns =
      static_cast<std::uint64_t>(st.st_mtim.tv_sec) * 1'000'000'000ull +
      static_cast<std::uint64_t>(st.st_mtim.tv_nsec);
#endif
  return info;
#endif
}

std::optional<std::uint64_t> file_mtime_ns(const fs::path &p) {
  const auto info = stat_path(p);
  if (!info)
    return std::nullopt;
  return info->mtime_ns;
}

std::optional<std::uint64_t> file_inode(const fs::path &p) {
  const auto info = stat_path(p);
  if (!info)
    return std::nullopt;
  return info->inode;
}

bool is_executable(const fs::path &p) {
  const auto info = stat_path(p);
  return info && info->executable;
}

// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------

static std::string_view trim_view(std::string_view s) {
  std::size_t start = 0;
  std::size_t end = s.size();
  while (start < end) {
    const char c = s[start];
    if (c != ' ' && c != '\t' && c != '\r' && c != '\n')
      break;
    ++start;
  }
  while (end > start) {
    const char c = s[end - 1];
    if (c != ' ' && c != '\t' && c != '\r' && c != '\n')
      break;
    --end;
  }
  return s.substr(start, end - start);
}

static std::string trim_copy(std::string_view s) {
  return std::string(trim_view(s));
}

std::optional<std::string> repo_config_value(const fs::path &repo_root,
                                             std::string_view key) {
  const auto data = read_file_opt(repo_root / ".veins" / "config");
  if (!data)
    return std::nullopt;
  std::string_view text(reinterpret_cast<const char *>(data->data()),
                        data->size());
  std::size_t start = 0;
  while (start <= text.size()) {
    std::size_t end = text.find('\n', start);
    if (end == std::string_view::npos)
      end = text.size();
    const std::string_view line = trim_view(text.substr(start, end - start));
    if (!line.empty() && line.front() != '#') {
      const std::size_t eq = line.find('=');
      if (eq != std::string_view::npos) {
        const std::string_view k = trim_view(line.substr(0, eq));
        if (k == key)
          return trim_copy(line.substr(eq + 1));
      }
    }
    if (end == text.size())
      break;
    start = end + 1;
  }
  return std::nullopt;
}

static std::string strip_comment(std::string_view v) {
  const std::size_t hash = v.find('#');
  if (hash != std::string_view::npos)
    v = v.substr(0, hash);
  return trim_copy(v);
}

bool repo_config_bool(const fs::path &repo_root, std::string_view key,
                      bool fallback) {
  const auto v = repo_config_value(repo_root, key);
  if (!v)
    return fallback;
  const std::string value = strip_comment(*v);
  return value == "true" || value == "1" || value == "yes" || value == "on";
}

bool repo_config_set(const fs::path &repo_root, std::string_view key,
                     std::string_view value) {
  const fs::path path = repo_root / ".veins" / "config";
  const auto data = read_file_opt(path);
  std::string out;
  if (data) {
    std::string_view text(reinterpret_cast<const char *>(data->data()),
                          data->size());
    std::size_t start = 0;
    while (start <= text.size()) {
      std::size_t end = text.find('\n', start);
      if (end == std::string_view::npos)
        end = text.size();
      const std::string_view line = text.substr(start, end - start);
      const std::string_view t = trim_view(line);
      const std::size_t eq = t.find('=');
      const bool is_key =
          eq != std::string_view::npos && trim_view(t.substr(0, eq)) == key;
      if (!is_key) {
        out.append(line);
        if (end < text.size())
          out.push_back('\n');
      }
      if (end == text.size())
        break;
      start = end + 1;
    }
  }
  out.append(key);
  out.append(" = ");
  out.append(value);
  out.push_back('\n');
  return write_file(path, bytes_of(out));
}

bool repo_config_remove(const fs::path &repo_root, std::string_view key) {
  const fs::path path = repo_root / ".veins" / "config";
  const auto data = read_file_opt(path);
  std::string out;
  if (data) {
    std::string_view text(reinterpret_cast<const char *>(data->data()),
                          data->size());
    std::size_t start = 0;
    while (start <= text.size()) {
      std::size_t end = text.find('\n', start);
      if (end == std::string_view::npos)
        end = text.size();
      const std::string_view line = text.substr(start, end - start);
      const std::string_view t = trim_view(line);
      const std::size_t eq = t.find('=');
      const bool is_key =
          eq != std::string_view::npos && trim_view(t.substr(0, eq)) == key;
      if (!is_key) {
        out.append(line);
        if (end < text.size())
          out.push_back('\n');
      }
      if (end == text.size())
        break;
      start = end + 1;
    }
  }
  return write_file(path, bytes_of(out));
}

static fs::path user_config_path() {
#if defined(_WIN32)
  const char *home = std::getenv("USERPROFILE");
#else
  const char *home = std::getenv("HOME");
#endif
  if (home == nullptr || *home == '\0')
    return {};
  return path_from_bytes(home) / ".local" / "config" / "veins" / "veins.toml";
}

static std::optional<std::string> unquote_toml(std::string_view raw) {
  raw = trim_view(raw);
  if (raw.size() >= 2) {
    if ((raw.front() == '\'' && raw.back() == '\'') ||
        (raw.front() == '"' && raw.back() == '"')) {
      const char quote = raw.front();
      std::string out;
      for (std::size_t i = 1; i + 1 < raw.size(); ++i) {
        const char c = raw[i];
        if (quote == '"' && c == '\\' && i + 2 < raw.size()) {
          const char next = raw[i + 1];
          if (next == '"')
            out.push_back('"');
          else if (next == '\\')
            out.push_back('\\');
          else if (next == 'n')
            out.push_back('\n');
          else if (next == 'r')
            out.push_back('\r');
          else if (next == 't')
            out.push_back('\t');
          else {
            out.push_back('\\');
            out.push_back(next);
          }
          ++i;
        } else {
          out.push_back(c);
        }
      }
      return out;
    }
  }
  if (raw.empty())
    return std::nullopt;
  return std::string(raw);
}

static std::optional<std::string> user_config_value(bool want_name) {
  const fs::path path = user_config_path();
  if (path.empty())
    return std::nullopt;
  const auto data = read_file_opt(path);
  if (!data)
    return std::nullopt;
  std::string_view text(reinterpret_cast<const char *>(data->data()),
                        data->size());
  bool in_user = false;
  std::size_t start = 0;
  while (start <= text.size()) {
    std::size_t end = text.find('\n', start);
    if (end == std::string_view::npos)
      end = text.size();
    const std::string_view line = trim_view(text.substr(start, end - start));
    if (!line.empty() && line.front() != '#') {
      if (line.front() == '[') {
        const std::size_t close = line.find(']');
        if (close != std::string_view::npos) {
          in_user = trim_view(line.substr(1, close - 1)) == "user";
        }
      } else {
        const std::size_t eq = line.find('=');
        if (eq != std::string_view::npos) {
          const std::string_view key = trim_view(line.substr(0, eq));
          const bool matches =
              (in_user && key == (want_name ? "name" : "email")) ||
              (!in_user && key == (want_name ? "user.name" : "user.email"));
          if (matches) {
            std::string_view value = line.substr(eq + 1);
            std::string value_copy = strip_comment(value);
            auto decoded = unquote_toml(value_copy);
            if (decoded && !decoded->empty())
              return decoded;
          }
        }
      }
    }
    if (end == text.size())
      break;
    start = end + 1;
  }
  return std::nullopt;
}

std::optional<std::string> user_config_author_name() {
  return user_config_value(true);
}
std::optional<std::string> user_config_author_email() {
  return user_config_value(false);
}

static std::optional<std::string> env_value(const char *name) {
  const char *v = std::getenv(name);
  if (v == nullptr)
    return std::nullopt;
  return std::string(v);
}

static std::string first_config(const fs::path &repo_root, std::string_view key,
                                bool want_name, const char *env1,
                                const char *env2) {
  if (auto v = repo_config_value(repo_root, key))
    return *v;
  auto user =
      want_name ? user_config_author_name() : user_config_author_email();
  if (user)
    return *user;
  if (auto v = env_value(env1))
    return *v;
  if (auto v = env_value(env2))
    return *v;
  return "unknown";
}

Sig identity_signature(const fs::path &repo_root) {
  Sig sig;
  sig.name =
      first_config(repo_root, "user.name", true, "GIT_AUTHOR_NAME", "USER");
  sig.email =
      first_config(repo_root, "user.email", false, "GIT_AUTHOR_EMAIL", "EMAIL");
#if defined(_WIN32)
  if (sig.name == "unknown") {
    if (auto v = env_value("USERNAME"))
      sig.name = *v;
  }
#endif
  sig.seconds = unix_now_seconds();
  sig.tz_min = 0;
  return sig;
}

// ---------------------------------------------------------------------------
// Ignore rules
// ---------------------------------------------------------------------------

IgnoreRules ignore_empty() { return {}; }

static std::optional<std::string_view> relative_to(std::string_view base,
                                                   std::string_view path) {
  if (base.empty())
    return path;
  if (path.size() <= base.size())
    return std::nullopt;
  if (path.substr(0, base.size()) != base)
    return std::nullopt;
  if (path[base.size()] != '/')
    return std::nullopt;
  return path.substr(base.size() + 1);
}

static void add_ignore_line(IgnoreRules &rules, std::string_view base,
                            std::string_view input) {
  std::string_view line = trim_view(input);
  if (line.empty() || line.front() == '#')
    return;
  bool negated = false;
  std::size_t start = 0;
  if (line.front() == '!') {
    negated = true;
    start = 1;
  }
  if (start >= line.size())
    return;
  std::size_t end = line.size();
  bool dir_only = false;
  if (line[end - 1] == '/') {
    dir_only = true;
    --end;
  }
  if (start >= end)
    return;
  bool anchored = false;
  if (line[start] == '/') {
    anchored = true;
    ++start;
  }
  if (start >= end)
    return;
  const std::string_view pattern = line.substr(start, end - start);
  const bool has_slash = pattern.find('/') != std::string_view::npos;
  rules.items.push_back(IgnoreRule{std::string(pattern), negated, dir_only,
                                   anchored, has_slash, std::string(base)});
}

void ignore_load_file(IgnoreRules &rules, const fs::path &repo_root,
                      std::string_view base, std::string_view name) {
  const fs::path dir =
      base.empty() ? repo_root : repo_root / path_from_bytes(base);
  const auto data = read_file_opt(dir / path_from_bytes(name));
  if (!data)
    return;
  std::string_view text(reinterpret_cast<const char *>(data->data()),
                        data->size());
  std::size_t start = 0;
  while (start <= text.size()) {
    std::size_t end = text.find('\n', start);
    if (end == std::string_view::npos)
      end = text.size();
    add_ignore_line(rules, base, text.substr(start, end - start));
    if (end == text.size())
      break;
    start = end + 1;
  }
}

void ignore_load_root(IgnoreRules &rules, const fs::path &repo_root) {
  ignore_load_file(rules, repo_root, "", ".vnexclude");
  ignore_load_file(rules, repo_root, "", ".gitignore");
}

static bool glob_here(std::string_view pattern, std::size_t pi,
                      std::string_view text, std::size_t ti) {
  if (pi >= pattern.size())
    return ti >= text.size();
  const char pc = pattern[pi];
  if (pc == '*') {
    const bool dbl = pi + 1 < pattern.size() && pattern[pi + 1] == '*';
    if (dbl) {
      const std::size_t next = pi + 2;
      if (next < pattern.size() && pattern[next] == '/') {
        const std::size_t after = next + 1;
        std::size_t j = ti;
        for (;;) {
          if (glob_here(pattern, after, text, j))
            return true;
          if (j >= text.size())
            break;
          if (text[j] == '/') {
            ++j;
            continue;
          }
          ++j;
          while (j < text.size() && text[j] != '/')
            ++j;
        }
        return false;
      }
      std::size_t j = ti;
      for (;;) {
        if (glob_here(pattern, next, text, j))
          return true;
        if (j >= text.size())
          break;
        ++j;
      }
      return false;
    }
    std::size_t j = ti;
    for (;;) {
      if (glob_here(pattern, pi + 1, text, j))
        return true;
      if (j >= text.size() || text[j] == '/')
        break;
      ++j;
    }
    return false;
  }
  if (ti >= text.size())
    return false;
  if (pc == '?') {
    if (text[ti] == '/')
      return false;
    return glob_here(pattern, pi + 1, text, ti + 1);
  }
  if (pc != text[ti])
    return false;
  return glob_here(pattern, pi + 1, text, ti + 1);
}

bool glob_match(std::string_view pattern, std::string_view text) {
  return glob_here(pattern, 0, text, 0);
}

static bool rule_matches(const IgnoreRule &rule, std::string_view path,
                         bool is_dir) {
  const auto rel_opt = relative_to(rule.base, path);
  if (!rel_opt)
    return false;
  const std::string_view rel = *rel_opt;
  if (rel.empty())
    return false;
  if (rule.dir_only && !is_dir)
    return false;
  if (!rule.has_slash && !rule.anchored) {
    std::size_t start = 0;
    for (;;) {
      std::size_t end = rel.find('/', start);
      if (end == std::string_view::npos)
        end = rel.size();
      if (glob_here(rule.pattern, 0, rel.substr(start, end - start), 0))
        return true;
      if (end >= rel.size())
        break;
      start = end + 1;
    }
    return false;
  }
  return glob_here(rule.pattern, 0, rel, 0);
}

bool ignore_ignored(const IgnoreRules &rules, std::string_view path,
                    bool is_dir) {
  bool ignored = false;
  for (const auto &rule : rules.items) {
    if (rule_matches(rule, path, is_dir))
      ignored = !rule.negated;
  }
  return ignored;
}

bool ignore_path_ignored(const fs::path &repo_root, std::string_view path) {
  IgnoreRules rules = ignore_empty();
  ignore_load_root(rules, repo_root);
  for (std::size_t i = 0; i < path.size(); ++i) {
    if (path[i] == '/') {
      const std::string_view base = path.substr(0, i);
      ignore_load_file(rules, repo_root, base, ".vnexclude");
      ignore_load_file(rules, repo_root, base, ".gitignore");
    }
  }
  bool result = false;
  for (std::size_t j = 0; j < path.size(); ++j) {
    if (path[j] == '/') {
      if (ignore_ignored(rules, path.substr(0, j), true)) {
        result = true;
        break;
      }
    }
  }
  if (!result)
    result = ignore_ignored(rules, path, false);
  return result;
}

} // namespace vn