#pragma once #include #include #include #include #include #include #include #include #include #include #include #include namespace Void::Diff { // ── Edit operations ─────────────────────────────────────────────────────────── enum class Op { Equal, Insert, Delete }; template struct Edit { Op op; T value; }; // ── Bounded diff controls ───────────────────────────────────────────────────── struct DiffLimits { // Maximum number of elements across both inputs (a.size() + b.size()). std::size_t max_input_elements = std::numeric_limits::max(); // Maximum number of input bytes for line_diff_bounded. std::size_t max_input_bytes = std::numeric_limits::max(); // Maximum bytes retained by the Myers trace (backtracking snapshots). std::size_t max_trace_memory = std::numeric_limits::max(); // Maximum number of edits in the produced script. std::size_t max_output = std::numeric_limits::max(); // Maximum work units (diagonal steps plus snake comparisons). std::size_t max_work = std::numeric_limits::max(); }; enum class DiffFailure : std::uint8_t { InputTooLarge, TraceMemoryExhausted, OutputTooLarge, WorkExhausted, Cancelled, }; namespace Detail { // A cancellation checkpoint is any callable returning bool. An empty // std::function (the default) means "never cancelled". template [[nodiscard]] inline bool cancellation_requested(const Cancel& cancel) { if constexpr (requires { static_cast(cancel); }) { if (!static_cast(cancel)) return false; } return static_cast(cancel()); } } // namespace Detail // ── Myers diff ──────────────────────────────────────────────────────────────── // Returns the shortest edit script (SES) to transform `a` into `b`. // Uses Myers' O(ND) algorithm, with checked size arithmetic and optional // input/trace/output/work budgets plus cancellation checkpoints. template , typename Cancel = std::function> [[nodiscard]] std::expected>, DiffFailure> diff_bounded(std::span a, std::span b, DiffLimits limits = {}, Eq eq = {}, Cancel&& cancelled = {}) { using Diff = std::ptrdiff_t; constexpr Diff kMaxDiff = std::numeric_limits::max(); const std::size_t n_size = a.size(); const std::size_t m_size = b.size(); if (n_size > limits.max_input_elements || m_size > limits.max_input_elements || n_size > limits.max_input_elements - m_size) { return std::unexpected{DiffFailure::InputTooLarge}; } const std::size_t max_diff_size = static_cast(kMaxDiff); if (n_size > max_diff_size || m_size > max_diff_size || n_size > max_diff_size - m_size) { return std::unexpected{DiffFailure::InputTooLarge}; } const Diff n = static_cast(n_size); const Diff m = static_cast(m_size); const Diff max_d = n + m; if (max_d == 0) return std::vector>{}; // Unsigned index math keeps max_d + k from overflowing signed ptrdiff_t. const auto index = [max_d](Diff k) { return static_cast(max_d) + static_cast(k); }; const std::size_t v_size = static_cast(max_d) * 2 + 1; if (v_size > limits.max_trace_memory / sizeof(Diff)) { return std::unexpected{DiffFailure::TraceMemoryExhausted}; } const std::size_t snapshot_bytes = v_size * sizeof(Diff); // v[k + max_d] = furthest-reaching x in diagonal k std::vector v(v_size, -1); // trace[d] = snapshot of v at step d (for backtracking) std::vector> trace; std::size_t trace_bytes = 0; std::size_t work = 0; const auto spend = [&]() -> bool { if (work >= limits.max_work) return false; ++work; return true; }; v[index(1)] = 0; bool done = false; Diff final_d = 0; for (Diff d = 0; d <= max_d && !done; ++d) { if (Detail::cancellation_requested(cancelled)) return std::unexpected{DiffFailure::Cancelled}; if (snapshot_bytes > limits.max_trace_memory - trace_bytes) return std::unexpected{DiffFailure::TraceMemoryExhausted}; trace.push_back(v); trace_bytes += snapshot_bytes; for (Diff k = -d; k <= d; k += 2) { if (!spend()) return std::unexpected{DiffFailure::WorkExhausted}; if (Detail::cancellation_requested(cancelled)) return std::unexpected{DiffFailure::Cancelled}; Diff x; if (k == -d || (k != d && v[index(k - 1)] < v[index(k + 1)])) x = v[index(k + 1)]; else x = v[index(k - 1)] + 1; Diff y = x - k; while (x < n && y < m && eq(a[static_cast(x)], b[static_cast(y)])) { if (!spend()) return std::unexpected{DiffFailure::WorkExhausted}; if (Detail::cancellation_requested(cancelled)) return std::unexpected{DiffFailure::Cancelled}; ++x; ++y; } v[index(k)] = x; if (x == n && y == m) { final_d = d; done = true; break; } } } if (!done) return std::unexpected{DiffFailure::WorkExhausted}; // Backtrack to reconstruct the edit script. std::vector> script; const auto push = [&](Op op, const T& value) -> bool { if (script.size() >= limits.max_output) return false; script.push_back(Edit{op, value}); return true; }; Diff x = n; Diff y = m; for (Diff d = final_d; d > 0; --d) { if (!spend()) return std::unexpected{DiffFailure::WorkExhausted}; if (Detail::cancellation_requested(cancelled)) return std::unexpected{DiffFailure::Cancelled}; const auto& pv = trace[static_cast(d)]; const Diff k = x - y; Diff prev_k; if (k == -d || (k != d && pv[index(k - 1)] < pv[index(k + 1)])) prev_k = k + 1; else prev_k = k - 1; const Diff prev_x = pv[index(prev_k)]; const Diff prev_y = prev_x - prev_k; // snake (equal) while (x > prev_x && y > prev_y) { if (!spend()) return std::unexpected{DiffFailure::WorkExhausted}; if (Detail::cancellation_requested(cancelled)) return std::unexpected{DiffFailure::Cancelled}; --x; --y; if (!push(Op::Equal, a[static_cast(x)])) return std::unexpected{DiffFailure::OutputTooLarge}; } if (d > 0) { if (x == prev_x) { --y; if (!push(Op::Insert, b[static_cast(y)])) return std::unexpected{DiffFailure::OutputTooLarge}; } else { --x; if (!push(Op::Delete, a[static_cast(x)])) return std::unexpected{DiffFailure::OutputTooLarge}; } } x = prev_x; y = prev_y; } // Remaining snake at start while (x > 0 && y > 0) { if (!spend()) return std::unexpected{DiffFailure::WorkExhausted}; --x; --y; if (!push(Op::Equal, a[static_cast(x)])) return std::unexpected{DiffFailure::OutputTooLarge}; } std::reverse(script.begin(), script.end()); return script; } // Convenience overload for vectors template , typename Cancel = std::function> [[nodiscard]] std::expected>, DiffFailure> diff_bounded(const std::vector& a, const std::vector& b, DiffLimits limits = {}, Eq eq = {}, Cancel&& cancelled = {}) { return diff_bounded(std::span{a}, std::span{b}, limits, eq, std::forward(cancelled)); } // Unbounded compatibility API. Default limits are effectively unlimited, so // existing callers keep their behaviour. template > [[nodiscard]] std::vector> diff(std::span a, std::span b, Eq eq = {}) { auto result = diff_bounded(a, b, {}, eq); if (!result) throw std::length_error("Void::Diff: diff input too large"); return *std::move(result); } // Convenience overload for vectors template > [[nodiscard]] std::vector> diff(const std::vector& a, const std::vector& b, Eq eq = {}) { return diff(std::span{a}, std::span{b}, eq); } // ── string diff ─────────────────────────────────────────────────────────────── // Line-level diff on strings split by newline. // LineDiff is Edit — count_op and apply work on it directly. using LineDiff = Edit; namespace Detail { [[nodiscard]] inline std::expected, DiffFailure> split_lines_bounded(std::string_view input, const DiffLimits& limits, std::size_t& line_count) { std::vector lines; std::size_t pos = 0; while (pos <= input.size()) { if (line_count >= limits.max_input_elements) { return std::unexpected{DiffFailure::InputTooLarge}; } ++line_count; const std::size_t nl = input.find('\n', pos); lines.emplace_back( input.substr(pos, nl == std::string_view::npos ? nl : nl - pos)); if (nl == std::string_view::npos) break; pos = nl + 1; } return lines; } } // namespace Detail template > [[nodiscard]] inline std::expected, DiffFailure> line_diff_bounded(std::string_view a, std::string_view b, DiffLimits limits = {}, Cancel&& cancelled = {}) { if (a.size() > limits.max_input_bytes || b.size() > limits.max_input_bytes || a.size() > limits.max_input_bytes - b.size()) { return std::unexpected{DiffFailure::InputTooLarge}; } std::size_t line_count = 0; auto a_lines = Detail::split_lines_bounded(a, limits, line_count); if (!a_lines) return std::unexpected{a_lines.error()}; auto b_lines = Detail::split_lines_bounded(b, limits, line_count); if (!b_lines) return std::unexpected{b_lines.error()}; auto edits = diff_bounded(std::span{*a_lines}, std::span{*b_lines}, limits, std::equal_to<>{}, std::forward(cancelled)); if (!edits) return std::unexpected{edits.error()}; std::vector lines; lines.reserve(edits->size()); for (const auto& edit : *edits) { lines.push_back(LineDiff{edit.op, std::string{edit.value}}); } return lines; } [[nodiscard]] inline std::vector line_diff(std::string_view a, std::string_view b) { auto result = line_diff_bounded(a, b); if (!result) throw std::length_error("Void::Diff: line diff input too large"); return *std::move(result); } // ── helpers ─────────────────────────────────────────────────────────────────── // Count edits by type template [[nodiscard]] std::size_t count_op(const std::vector>& edits, Op op) { return static_cast(std::count_if(edits.begin(), edits.end(), [op](const Edit& e) { return e.op == op; })); } // Reconstruct the "b" sequence from an edit script applied to "a" template [[nodiscard]] std::vector apply(const std::vector>& edits) { std::vector out; for (const auto& e : edits) if (e.op != Op::Delete) out.push_back(e.value); return out; } // Format a unified-diff-style patch for string line diffs [[nodiscard]] inline std::string format_patch(const std::vector& edits) { std::string out; for (const auto& e : edits) { switch (e.op) { case Op::Equal: out += ' '; break; case Op::Insert: out += '+'; break; case Op::Delete: out += '-'; break; } out += e.value + '\n'; } return out; } } // namespace Void::Diff