main2.rs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. #[derive(PartialEq, Debug, Clone)]
  2. enum DiffOp {
  3. Insert,
  4. Delete,
  5. Equal,
  6. }
  7. #[derive(Clone, Debug)]
  8. struct Diff {
  9. operation: DiffOp,
  10. data: String,
  11. }
  12. struct DiffMatchPatch {
  13. diff_timeout: f64,
  14. diff_edit_cost: isize,
  15. match_threshold: f64,
  16. match_distance: isize,
  17. patch_delete_threshold: f64,
  18. patch_margin: isize,
  19. }
  20. impl DiffMatchPatch {
  21. fn new() -> DiffMatchPatch {
  22. DiffMatchPatch {
  23. diff_timeout: 1.0,
  24. diff_edit_cost: 4,
  25. match_threshold: 0.5,
  26. match_distance: 1000,
  27. patch_delete_threshold: 0.5,
  28. patch_margin: 4,
  29. }
  30. }
  31. fn diff_main(&self, text1: &str, text2: &str) -> Vec<Diff> {
  32. self.diff_compute(text1, text2)
  33. }
  34. fn diff_compute(&self, text1: &str, text2: &str) -> Vec<Diff> {
  35. if text1.is_empty() {
  36. return vec![Diff {
  37. operation: DiffOp::Insert,
  38. data: text2.to_string(),
  39. }];
  40. }
  41. if text2.is_empty() {
  42. return vec![Diff {
  43. operation: DiffOp::Delete,
  44. data: text1.to_string(),
  45. }];
  46. }
  47. let mut diffs = Vec::new();
  48. let mut i = 0;
  49. let mut j = 0;
  50. let text1_chars: Vec<char> = text1.chars().collect();
  51. let text2_chars: Vec<char> = text2.chars().collect();
  52. while i < text1_chars.len() && j < text2_chars.len() {
  53. if text1_chars[i] == text2_chars[j] {
  54. diffs.push(Diff {
  55. operation: DiffOp::Equal,
  56. data: text1_chars[i].to_string(),
  57. });
  58. i += 1;
  59. j += 1;
  60. } else {
  61. // Simple case handling: deletion from text1
  62. diffs.push(Diff {
  63. operation: DiffOp::Delete,
  64. data: text1_chars[i].to_string(),
  65. });
  66. i += 1;
  67. // Simple case handling: insertion to text2
  68. diffs.push(Diff {
  69. operation: DiffOp::Insert,
  70. data: text2_chars[j].to_string(),
  71. });
  72. j += 1;
  73. }
  74. }
  75. // Handle any remaining characters in text1
  76. while i < text1_chars.len() {
  77. diffs.push(Diff {
  78. operation: DiffOp::Delete,
  79. data: text1_chars[i].to_string(),
  80. });
  81. i += 1;
  82. }
  83. // Handle any remaining characters in text2
  84. while j < text2_chars.len() {
  85. diffs.push(Diff {
  86. operation: DiffOp::Insert,
  87. data: text2_chars[j].to_string(),
  88. });
  89. j += 1;
  90. }
  91. diffs
  92. }
  93. }
  94. fn main() {
  95. let dmp = DiffMatchPatch::new();
  96. let text1 = "能不能说一下你们现在的负债情况";
  97. let text2 = "能哎能说按蓝你们现在的负债情况";
  98. let diffs = dmp.diff_main(text1, text2);
  99. println!("Diffs: {:?}", diffs);
  100. }