Merge issue-42-bounded-diff: bounded diff APIs (#42)
This commit is contained in:
commit
be8dd73607
2 files changed
+553
-69
No files matched your search
+271
-69
@@ -2,10 +2,15 @@
|
||||
|
||||
#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
|
||||
@@ -21,73 +26,226 @@ struct Edit {
|
||||
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.
|
||||
// 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 = {})
|
||||
{
|
||||
const int n = static_cast<int>(a.size());
|
||||
const int m = static_cast<int>(b.size());
|
||||
const int max_d = n + m;
|
||||
|
||||
if (max_d == 0) return {};
|
||||
|
||||
// v[k + max_d] = furthest-reaching x in diagonal k
|
||||
std::vector<int> v(2 * max_d + 1, -1);
|
||||
// trace[d] = snapshot of v at step d (for backtracking)
|
||||
std::vector<std::vector<int>> trace;
|
||||
|
||||
v[max_d + 1] = 0;
|
||||
bool done = false;
|
||||
int final_d = 0;
|
||||
|
||||
for (int d = 0; d <= max_d && !done; ++d) {
|
||||
trace.push_back(v);
|
||||
for (int k = -d; k <= d; k += 2) {
|
||||
int x;
|
||||
if (k == -d || (k != d && v[max_d + k - 1] < v[max_d + k + 1]))
|
||||
x = v[max_d + k + 1];
|
||||
else
|
||||
x = v[max_d + k - 1] + 1;
|
||||
int y = x - k;
|
||||
while (x < n && y < m && eq(a[x], b[y])) { ++x; ++y; }
|
||||
v[max_d + k] = x;
|
||||
if (x == n && y == m) { final_d = d; done = true; break; }
|
||||
}
|
||||
}
|
||||
|
||||
// Backtrack to reconstruct the edit script
|
||||
std::vector<Edit<T>> script;
|
||||
int x = n, y = m;
|
||||
for (int d = final_d; d > 0; --d) {
|
||||
const auto& pv = trace[d];
|
||||
const int k = x - y;
|
||||
int prev_k;
|
||||
if (k == -d || (k != d && pv[max_d + k - 1] < pv[max_d + k + 1]))
|
||||
prev_k = k + 1;
|
||||
else
|
||||
prev_k = k - 1;
|
||||
const int prev_x = pv[max_d + prev_k];
|
||||
const int prev_y = prev_x - prev_k;
|
||||
// snake (equal)
|
||||
while (x > prev_x && y > prev_y) {
|
||||
--x; --y;
|
||||
script.push_back({Op::Equal, a[x]});
|
||||
}
|
||||
if (d > 0) {
|
||||
if (x == prev_x) { --y; script.push_back({Op::Insert, b[y]}); }
|
||||
else { --x; script.push_back({Op::Delete, a[x]}); }
|
||||
}
|
||||
x = prev_x; y = prev_y;
|
||||
}
|
||||
// Remaining snake at start
|
||||
while (x > 0 && y > 0) { --x; --y; script.push_back({Op::Equal, a[x]}); }
|
||||
|
||||
std::reverse(script.begin(), script.end());
|
||||
return script;
|
||||
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
|
||||
@@ -104,22 +262,66 @@ diff(const std::vector<T>& a, const std::vector<T>& b, Eq eq = {})
|
||||
|
||||
using LineDiff = Edit<std::string>;
|
||||
|
||||
[[nodiscard]] inline std::vector<LineDiff>
|
||||
line_diff(std::string_view a, std::string_view b)
|
||||
namespace Detail
|
||||
{
|
||||
auto split = [](std::string_view s) {
|
||||
std::vector<std::string> lines;
|
||||
[[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 <= s.size()) {
|
||||
const auto nl = s.find('\n', pos);
|
||||
lines.emplace_back(s.substr(pos, nl == std::string_view::npos ? nl : nl - pos));
|
||||
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
|
||||
|
||||
return diff(split(a), split(b));
|
||||
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 ───────────────────────────────────────────────────────────────────
|
||||
|
||||
Reference in new issue
Block a user