Text: add bounded diff APIs (#42)

This commit is contained in:
faumaray committed 2026-12-03 15:46:30 +03:00
1 parent b3c566ed4d
commit 4ad13ce94f
2 files changed
+553 -69

No files matched your search

+271 -69
View File
@@ -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 ───────────────────────────────────────────────────────────────────
+282
View File
@@ -0,0 +1,282 @@
#include <Void/Text/Diff.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <cstddef>
#include <functional>
#include <limits>
#include <string>
#include <string_view>
#include <vector>
using namespace Void::Diff;
namespace
{
std::string join_lines(const std::vector<std::string>& lines)
{
std::string out;
for (std::size_t i = 0; i < lines.size(); ++i) {
if (i != 0) out += '\n';
out += lines[i];
}
return out;
}
std::string reconstruct_lines(const std::vector<LineDiff>& edits)
{
return join_lines(apply(edits));
}
} // namespace
// ── empty / equal inputs ──────────────────────────────────────────────────────
Void::Testing::Test bounded_diff_empty_and_equal_inputs()
{
const std::vector<int> empty;
const auto both_empty = diff_bounded(empty, empty);
Void::Testing::require(both_empty.has_value());
Void::Testing::expect(both_empty->empty());
const std::vector<int> same{1, 2, 3, 4};
const auto equal = diff_bounded(same, same);
Void::Testing::require(equal.has_value());
Void::Testing::expect_eq(count_op(*equal, Op::Insert), std::size_t{0});
Void::Testing::expect_eq(count_op(*equal, Op::Delete), std::size_t{0});
Void::Testing::expect_eq(count_op(*equal, Op::Equal), std::size_t{4});
Void::Testing::expect_eq(apply(*equal), same);
// Zero elements are allowed when the budget is exactly zero.
const auto zero_budget =
diff_bounded(empty, empty, DiffLimits{.max_input_elements = 0});
Void::Testing::require(zero_budget.has_value());
Void::Testing::expect(zero_budget->empty());
}
// ── unrelated sequences ──────────────────────────────────────────────────────
Void::Testing::Test bounded_diff_unrelated_sequences()
{
const std::vector<int> a{1, 2, 3};
const std::vector<int> b{4, 5, 6};
const auto edits = diff_bounded(a, b);
Void::Testing::require(edits.has_value());
Void::Testing::expect_eq(count_op(*edits, Op::Equal), std::size_t{0});
Void::Testing::expect_eq(count_op(*edits, Op::Delete), std::size_t{3});
Void::Testing::expect_eq(count_op(*edits, Op::Insert), std::size_t{3});
Void::Testing::expect_eq(apply(*edits), b);
}
// ── repetitive lines ─────────────────────────────────────────────────────────
Void::Testing::Test bounded_diff_repetitive_lines()
{
std::string a;
for (int i = 0; i < 64; ++i) a += "repeat\n";
std::string b = a;
b.replace(0, 7, "changed\n");
b += "tail\n";
const auto edits = line_diff_bounded(a, b);
Void::Testing::require(edits.has_value());
Void::Testing::expect_eq(reconstruct_lines(*edits), b);
// A limit that still fits the line count succeeds.
const std::size_t lines = 65 + 66;
const auto limited = line_diff_bounded(
a, b, DiffLimits{.max_input_elements = lines,
.max_trace_memory = std::numeric_limits<std::size_t>::max(),
.max_work = std::numeric_limits<std::size_t>::max()});
Void::Testing::require(limited.has_value());
Void::Testing::expect_eq(reconstruct_lines(*limited), b);
}
// ── input and arithmetic boundaries ─────────────────────────────────────────
Void::Testing::Test bounded_diff_input_and_arithmetic_boundaries()
{
const std::vector<int> one{1};
const std::vector<int> two{2};
const auto too_many = diff_bounded(one, two, DiffLimits{.max_input_elements = 1});
Void::Testing::expect(!too_many.has_value());
Void::Testing::expect(too_many.error() == DiffFailure::InputTooLarge);
const auto exact = diff_bounded(one, two, DiffLimits{.max_input_elements = 2});
Void::Testing::require(exact.has_value());
Void::Testing::expect_eq(apply(*exact), two);
const auto maximum =
diff_bounded(one, two,
DiffLimits{.max_input_elements = std::numeric_limits<std::size_t>::max(),
.max_input_bytes = std::numeric_limits<std::size_t>::max(),
.max_trace_memory = std::numeric_limits<std::size_t>::max(),
.max_output = std::numeric_limits<std::size_t>::max(),
.max_work = std::numeric_limits<std::size_t>::max()});
Void::Testing::require(maximum.has_value());
Void::Testing::expect_eq(apply(*maximum), two);
// Line diff checks the combined byte count with checked arithmetic.
const auto bytes = line_diff_bounded("abc", "abc",
DiffLimits{.max_input_bytes = 5});
Void::Testing::expect(!bytes.has_value());
Void::Testing::expect(bytes.error() == DiffFailure::InputTooLarge);
const auto bytes_exact = line_diff_bounded("abc", "abc",
DiffLimits{.max_input_bytes = 6});
Void::Testing::require(bytes_exact.has_value());
Void::Testing::expect_eq(reconstruct_lines(*bytes_exact), std::string{"abc"});
}
// ── trace memory budget ─────────────────────────────────────────────────────
Void::Testing::Test bounded_diff_trace_memory_budget()
{
const std::vector<int> a{1, 2};
const std::vector<int> b{3, 4};
// max_d = 4, v_size = 9, one snapshot = 9 * sizeof(ptrdiff_t) = 72 bytes.
constexpr std::size_t kSnapshot = 9 * sizeof(std::ptrdiff_t);
const auto none = diff_bounded(a, b, DiffLimits{.max_trace_memory = 0});
Void::Testing::expect(!none.has_value());
Void::Testing::expect(none.error() == DiffFailure::TraceMemoryExhausted);
const auto short_by_one =
diff_bounded(a, b, DiffLimits{.max_trace_memory = kSnapshot - 1});
Void::Testing::expect(!short_by_one.has_value());
Void::Testing::expect(short_by_one.error() == DiffFailure::TraceMemoryExhausted);
// Unrelated sequences need d = 4, i.e. five snapshots.
const auto exact = diff_bounded(a, b, DiffLimits{.max_trace_memory = 5 * kSnapshot});
Void::Testing::require(exact.has_value());
Void::Testing::expect_eq(apply(*exact), b);
}
// ── output budget ──────────────────────────────────────────────────────────
Void::Testing::Test bounded_diff_output_budget()
{
const std::vector<int> a{1, 2, 3};
const std::vector<int> b{4, 5, 6};
const auto too_small = diff_bounded(a, b, DiffLimits{.max_output = 5});
Void::Testing::expect(!too_small.has_value());
Void::Testing::expect(too_small.error() == DiffFailure::OutputTooLarge);
const auto exact = diff_bounded(a, b, DiffLimits{.max_output = 6});
Void::Testing::require(exact.has_value());
Void::Testing::expect_eq(exact->size(), std::size_t{6});
Void::Testing::expect_eq(apply(*exact), b);
}
// ── work budget ────────────────────────────────────────────────────────────
Void::Testing::Test bounded_diff_work_budget()
{
const std::vector<int> a{1, 2, 3};
const std::vector<int> b{1, 2, 3};
const auto no_work = diff_bounded(a, b, DiffLimits{.max_work = 0});
Void::Testing::expect(!no_work.has_value());
Void::Testing::expect(no_work.error() == DiffFailure::WorkExhausted);
const auto one_unit = diff_bounded(a, b, DiffLimits{.max_work = 1});
Void::Testing::expect(!one_unit.has_value());
Void::Testing::expect(one_unit.error() == DiffFailure::WorkExhausted);
const auto enough =
diff_bounded(a, b, DiffLimits{.max_work = std::numeric_limits<std::size_t>::max()});
Void::Testing::require(enough.has_value());
Void::Testing::expect_eq(apply(*enough), b);
}
// ── cancellation ───────────────────────────────────────────────────────────
Void::Testing::Test bounded_diff_cancellation()
{
const std::vector<int> a{1, 2, 3, 4};
const std::vector<int> b{1, 3, 4, 5};
const auto immediate =
diff_bounded(a, b, {}, std::equal_to<int>{}, [] { return true; });
Void::Testing::expect(!immediate.has_value());
Void::Testing::expect(immediate.error() == DiffFailure::Cancelled);
int calls = 0;
const auto after_one = diff_bounded(a, b, {}, std::equal_to<int>{}, [&calls] {
return ++calls > 1;
});
Void::Testing::expect(!after_one.has_value());
Void::Testing::expect(after_one.error() == DiffFailure::Cancelled);
Void::Testing::expect(calls >= 2);
bool cancelled = false;
const auto not_cancelled =
diff_bounded(a, b, {}, std::equal_to<int>{}, [&cancelled] { return cancelled; });
Void::Testing::require(not_cancelled.has_value());
Void::Testing::expect_eq(apply(*not_cancelled), b);
}
// ── reconstruction properties ──────────────────────────────────────────────
Void::Testing::Test bounded_diff_reconstruction_properties()
{
const std::vector<std::vector<int>> int_cases{
{},
{1},
{1, 2, 3},
{1, 2, 3, 4, 5},
{2, 1, 2, 1, 2},
{9, 8, 7, 6},
};
for (const auto& a : int_cases) {
for (const auto& b : int_cases) {
const auto edits = diff_bounded(a, b);
Void::Testing::require(edits.has_value());
Void::Testing::expect_eq(apply(*edits), b);
Void::Testing::expect(edits->size() <= a.size() + b.size());
}
}
const std::vector<std::pair<std::string, std::string>> line_cases{
{"", ""},
{"a", ""},
{"", "a"},
{"a\nb\nc", "a\nb\nc"},
{"a\nb\nc", "a\nx\nc"},
{"x\ny\nx\ny", "y\nx\ny\nx"},
{"same\nsame\nsame", "same\nsame"},
};
for (const auto& [a, b] : line_cases) {
const auto edits = line_diff_bounded(a, b);
Void::Testing::require(edits.has_value());
Void::Testing::expect_eq(reconstruct_lines(*edits), b);
}
}
// ── line diff budgets ──────────────────────────────────────────────────────
Void::Testing::Test bounded_line_diff_budgets()
{
const auto line_limit = line_diff_bounded(
"a\nb", "a\nb", DiffLimits{.max_input_elements = 3});
Void::Testing::expect(!line_limit.has_value());
Void::Testing::expect(line_limit.error() == DiffFailure::InputTooLarge);
const auto work_limit = line_diff_bounded(
"a\nb\nc", "x\ny\nz", DiffLimits{.max_work = 0});
Void::Testing::expect(!work_limit.has_value());
Void::Testing::expect(work_limit.error() == DiffFailure::WorkExhausted);
const auto output_limit = line_diff_bounded(
"a\nb\nc", "x\ny\nz", DiffLimits{.max_output = 5});
Void::Testing::expect(!output_limit.has_value());
Void::Testing::expect(output_limit.error() == DiffFailure::OutputTooLarge);
const auto cancelled = line_diff_bounded(
"a\nb", "a\nb", {}, [] { return true; });
Void::Testing::expect(!cancelled.has_value());
Void::Testing::expect(cancelled.error() == DiffFailure::Cancelled);
}