main.rs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. if text1 == text2 {
  33. if text1.is_empty() {
  34. Vec::new()
  35. } else {
  36. vec![Diff {
  37. operation: DiffOp::Equal,
  38. data: text1.to_string(),
  39. }]
  40. }
  41. } else {
  42. let mut diffs = Vec::new();
  43. if text1.is_empty() {
  44. diffs.push(Diff {
  45. operation: DiffOp::Insert,
  46. data: text2.to_string(),
  47. });
  48. } else if text2.is_empty() {
  49. diffs.push(Diff {
  50. operation: DiffOp::Delete,
  51. data: text1.to_string(),
  52. });
  53. } else {
  54. // Here, a real diff algorithm would be implemented
  55. diffs.push(Diff {
  56. operation: DiffOp::Delete,
  57. data: text1.to_string(),
  58. });
  59. diffs.push(Diff {
  60. operation: DiffOp::Insert,
  61. data: text2.to_string(),
  62. });
  63. }
  64. diffs
  65. }
  66. }
  67. }
  68. fn main() {
  69. let dmp = DiffMatchPatch::new();
  70. let text1 = "Hello World";
  71. let text2 = "Hello Rust!";
  72. let diffs = dmp.diff_main(text1, text2);
  73. println!("Diffs: {:?}", diffs);
  74. }