363 lines
13 KiB
C++
363 lines
13 KiB
C++
#pragma once
|
|
|
|
#include <algorithm>
|
|
#include <cstddef>
|
|
#include <cstdint>
|
|
#include <expected>
|
|
#include <functional>
|
|
#include <limits>
|
|
#include <span>
|
|
#include <stdexcept>
|
|
#include <string>
|
|
#include <string_view>
|
|
#include <utility>
|
|
#include <vector>
|
|
|
|
namespace Void::Diff
|
|
{
|
|
|
|
// ── Edit operations ───────────────────────────────────────────────────────────
|
|
|
|
enum class Op { Equal, Insert, Delete };
|
|
|
|
template <typename T>
|
|
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<std::size_t>::max();
|
|
// Maximum number of input bytes for line_diff_bounded.
|
|
std::size_t max_input_bytes = std::numeric_limits<std::size_t>::max();
|
|
// Maximum bytes retained by the Myers trace (backtracking snapshots).
|
|
std::size_t max_trace_memory = std::numeric_limits<std::size_t>::max();
|
|
// Maximum number of edits in the produced script.
|
|
std::size_t max_output = std::numeric_limits<std::size_t>::max();
|
|
// Maximum work units (diagonal steps plus snake comparisons).
|
|
std::size_t max_work = std::numeric_limits<std::size_t>::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 <typename Cancel>
|
|
[[nodiscard]] inline bool cancellation_requested(const Cancel& cancel)
|
|
{
|
|
if constexpr (requires { static_cast<bool>(cancel); }) {
|
|
if (!static_cast<bool>(cancel)) return false;
|
|
}
|
|
return static_cast<bool>(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 T, typename Eq = std::equal_to<T>,
|
|
typename Cancel = std::function<bool()>>
|
|
[[nodiscard]] std::expected<std::vector<Edit<T>>, DiffFailure>
|
|
diff_bounded(std::span<const T> a, std::span<const T> b,
|
|
DiffLimits limits = {}, Eq eq = {}, Cancel&& cancelled = {})
|
|
{
|
|
using Diff = std::ptrdiff_t;
|
|
constexpr Diff kMaxDiff = std::numeric_limits<Diff>::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<std::size_t>(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<Diff>(n_size);
|
|
const Diff m = static_cast<Diff>(m_size);
|
|
const Diff max_d = n + m;
|
|
|
|
if (max_d == 0) return std::vector<Edit<T>>{};
|
|
|
|
// Unsigned index math keeps max_d + k from overflowing signed ptrdiff_t.
|
|
const auto index = [max_d](Diff k) {
|
|
return static_cast<std::size_t>(max_d) + static_cast<std::size_t>(k);
|
|
};
|
|
|
|
const std::size_t v_size = static_cast<std::size_t>(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<Diff> v(v_size, -1);
|
|
// trace[d] = snapshot of v at step d (for backtracking)
|
|
std::vector<std::vector<Diff>> 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<std::size_t>(x)],
|
|
b[static_cast<std::size_t>(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<Edit<T>> script;
|
|
const auto push = [&](Op op, const T& value) -> bool {
|
|
if (script.size() >= limits.max_output) return false;
|
|
script.push_back(Edit<T>{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<std::size_t>(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<std::size_t>(x)]))
|
|
return std::unexpected{DiffFailure::OutputTooLarge};
|
|
}
|
|
if (d > 0) {
|
|
if (x == prev_x) {
|
|
--y;
|
|
if (!push(Op::Insert, b[static_cast<std::size_t>(y)]))
|
|
return std::unexpected{DiffFailure::OutputTooLarge};
|
|
} else {
|
|
--x;
|
|
if (!push(Op::Delete, a[static_cast<std::size_t>(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<std::size_t>(x)]))
|
|
return std::unexpected{DiffFailure::OutputTooLarge};
|
|
}
|
|
|
|
std::reverse(script.begin(), script.end());
|
|
return script;
|
|
}
|
|
|
|
// Convenience overload for vectors
|
|
template <typename T, typename Eq = std::equal_to<T>,
|
|
typename Cancel = std::function<bool()>>
|
|
[[nodiscard]] std::expected<std::vector<Edit<T>>, DiffFailure>
|
|
diff_bounded(const std::vector<T>& a, const std::vector<T>& b,
|
|
DiffLimits limits = {}, Eq eq = {}, Cancel&& cancelled = {})
|
|
{
|
|
return diff_bounded<T, Eq>(std::span<const T>{a}, std::span<const T>{b},
|
|
limits, eq, std::forward<Cancel>(cancelled));
|
|
}
|
|
|
|
// Unbounded compatibility API. Default limits are effectively unlimited, so
|
|
// existing callers keep their behaviour.
|
|
template <typename T, typename Eq = std::equal_to<T>>
|
|
[[nodiscard]] std::vector<Edit<T>>
|
|
diff(std::span<const T> a, std::span<const T> b, Eq eq = {})
|
|
{
|
|
auto result = diff_bounded<T, Eq>(a, b, {}, eq);
|
|
if (!result) throw std::length_error("Void::Diff: diff input too large");
|
|
return *std::move(result);
|
|
}
|
|
|
|
// Convenience overload for vectors
|
|
template <typename T, typename Eq = std::equal_to<T>>
|
|
[[nodiscard]] std::vector<Edit<T>>
|
|
diff(const std::vector<T>& a, const std::vector<T>& b, Eq eq = {})
|
|
{
|
|
return diff<T, Eq>(std::span<const T>{a}, std::span<const T>{b}, eq);
|
|
}
|
|
|
|
// ── string diff ───────────────────────────────────────────────────────────────
|
|
// Line-level diff on strings split by newline.
|
|
// LineDiff is Edit<string> — count_op and apply work on it directly.
|
|
|
|
using LineDiff = Edit<std::string>;
|
|
|
|
namespace Detail
|
|
{
|
|
[[nodiscard]] inline std::expected<std::vector<std::string_view>, DiffFailure>
|
|
split_lines_bounded(std::string_view input, const DiffLimits& limits,
|
|
std::size_t& line_count)
|
|
{
|
|
std::vector<std::string_view> 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 <typename Cancel = std::function<bool()>>
|
|
[[nodiscard]] inline std::expected<std::vector<LineDiff>, 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<const std::string_view>{*a_lines},
|
|
std::span<const std::string_view>{*b_lines},
|
|
limits, std::equal_to<>{},
|
|
std::forward<Cancel>(cancelled));
|
|
if (!edits) return std::unexpected{edits.error()};
|
|
|
|
std::vector<LineDiff> 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<LineDiff>
|
|
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 <typename T>
|
|
[[nodiscard]] std::size_t count_op(const std::vector<Edit<T>>& edits, Op op)
|
|
{
|
|
return static_cast<std::size_t>(std::count_if(edits.begin(), edits.end(),
|
|
[op](const Edit<T>& e) { return e.op == op; }));
|
|
}
|
|
|
|
// Reconstruct the "b" sequence from an edit script applied to "a"
|
|
template <typename T>
|
|
[[nodiscard]] std::vector<T> apply(const std::vector<Edit<T>>& edits)
|
|
{
|
|
std::vector<T> 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<LineDiff>& 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
|