Skip to main content

java_diff_utils_rs/text/
diff_row.rs

1//! Represents a single row in a side-by-side or line-by-line diff table.
2
3use std::fmt;
4
5/// Describes the operation tag associated with a diff row.
6#[derive(Clone, Copy, PartialEq, Eq, Hash)]
7pub enum Tag {
8    Insert,
9    Delete,
10    Change,
11    Equal,
12}
13
14impl fmt::Debug for Tag {
15    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
16        match self {
17            Tag::Insert => write!(f, "Insert"),
18            Tag::Delete => write!(f, "Delete"),
19            Tag::Change => write!(f, "Change"),
20            Tag::Equal => write!(f, "Equal"),
21        }
22    }
23}
24
25impl fmt::Display for Tag {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        match self {
28            Tag::Insert => write!(f, "INSERT"),
29            Tag::Delete => write!(f, "DELETE"),
30            Tag::Change => write!(f, "CHANGE"),
31            Tag::Equal => write!(f, "EQUAL"),
32        }
33    }
34}
35
36/// Describes a diff row in the form `[tag, old_line, new_line]`
37/// for showing differences between two texts side-by-side.
38#[derive(Clone, PartialEq, Eq, Hash)]
39pub struct DiffRow {
40    tag: Tag,
41    old_line: String,
42    new_line: String,
43}
44
45impl fmt::Debug for DiffRow {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        write!(f, "[{},{},{}]", self.tag, self.old_line, self.new_line)
48    }
49}
50
51impl DiffRow {
52    /// Creates a new `DiffRow`.
53    pub fn new(tag: Tag, old_line: impl Into<String>, new_line: impl Into<String>) -> Self {
54        Self {
55            tag,
56            old_line: old_line.into(),
57            new_line: new_line.into(),
58        }
59    }
60
61    /// Returns the tag.
62    #[inline]
63    pub fn tag(&self) -> Tag {
64        self.tag
65    }
66
67    /// Sets the tag.
68    #[inline]
69    pub fn set_tag(&mut self, tag: Tag) {
70        self.tag = tag;
71    }
72
73    /// Returns a reference to the old line.
74    #[inline]
75    pub fn old_line(&self) -> &str {
76        &self.old_line
77    }
78
79    /// Returns a reference to the new line.
80    #[inline]
81    pub fn new_line(&self) -> &str {
82        &self.new_line
83    }
84}
85
86impl fmt::Display for DiffRow {
87    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88        write!(f, "[{},{},{}]", self.tag, self.old_line, self.new_line)
89    }
90}