Generator.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * Copyright (c) 2021, Mustafa Quraish <mustafa@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "Generator.h"
  7. namespace Diff {
  8. Vector<Hunk> from_text(StringView const& old_text, StringView const& new_text)
  9. {
  10. auto old_lines = old_text.lines();
  11. auto new_lines = new_text.lines();
  12. /**
  13. * This is a simple implementation of the Longest Common Subsequence algorithm (over
  14. * the lines of the text as opposed to the characters). A Dynamic programming approach
  15. * is used here.
  16. */
  17. enum class Direction {
  18. Down, // Added a new line
  19. Right, // Removed a line
  20. Diagonal, // Line remained the same
  21. };
  22. // A single cell in the DP-matrix. Cell (i, j) represents the longest common
  23. // sub-sequence of lines between old_lines[0 : i] and new_lines[0 : j].
  24. struct Cell {
  25. size_t length;
  26. Direction direction;
  27. };
  28. auto dp_matrix = Vector<Cell>();
  29. dp_matrix.resize((old_lines.size() + 1) * (new_lines.size() + 1));
  30. auto dp = [&dp_matrix, width = old_lines.size() + 1](size_t i, size_t j) -> Cell& {
  31. return dp_matrix[i + width * j];
  32. };
  33. // Initialize the first row and column
  34. for (size_t i = 0; i <= old_lines.size(); ++i)
  35. dp(i, new_lines.size()) = { 0, Direction::Right };
  36. for (size_t j = 0; j <= new_lines.size(); ++j)
  37. dp(old_lines.size(), 0) = { 0, Direction::Down };
  38. // Fill in the rest of the DP table
  39. for (int i = old_lines.size() - 1; i >= 0; --i) {
  40. for (int j = new_lines.size() - 1; j >= 0; --j) {
  41. if (old_lines[i] == new_lines[j]) {
  42. dp(i, j) = { dp(i + 1, j + 1).length + 1, Direction::Diagonal };
  43. } else {
  44. auto down = dp(i, j + 1).length;
  45. auto right = dp(i + 1, j).length;
  46. if (down > right)
  47. dp(i, j) = { down, Direction::Down };
  48. else
  49. dp(i, j) = { right, Direction::Right };
  50. }
  51. }
  52. }
  53. Vector<Hunk> hunks;
  54. size_t i = 0;
  55. size_t j = 0;
  56. // FIXME: This creates a hunk per line, very inefficient.
  57. while (i < old_lines.size() && j < new_lines.size()) {
  58. auto& cell = dp(i, j);
  59. if (cell.direction == Direction::Down) {
  60. hunks.append({ i, j, {}, { new_lines[j] } });
  61. ++j;
  62. } else if (cell.direction == Direction::Right) {
  63. hunks.append({ i, j, { old_lines[i] }, {} });
  64. ++i;
  65. } else {
  66. ++i;
  67. ++j;
  68. }
  69. }
  70. return hunks;
  71. }
  72. }