Skip to main content

java_diff_utils_rs/patch/
delete_delta.rs

1use std::fmt;
2
3use super::chunk::Chunk;
4use super::delta::Delta;
5use super::delta_type::DeltaType;
6use super::error::PatchError;
7
8/// Describes a delete-delta representing removed content from an original sequence.
9#[derive(Debug, Clone, PartialEq, Eq, Hash)]
10pub struct DeleteDelta<T> {
11    inner: Delta<T>,
12}
13
14impl<T> DeleteDelta<T> {
15    /// Creates a new `DeleteDelta` with the given original (source) and revised (target) chunks.
16    pub fn new(original: Chunk<T>, revised: Chunk<T>) -> Self {
17        Self {
18            inner: Delta::new(DeltaType::Delete, original, revised),
19        }
20    }
21
22    /// Returns a reference to the underlying inner [`Delta`].
23    #[inline]
24    pub fn delta(&self) -> &Delta<T> {
25        &self.inner
26    }
27
28    /// Consumes `self` and returns the inner [`Delta`].
29    #[inline]
30    pub fn into_delta(self) -> Delta<T> {
31        self.inner
32    }
33
34    /// Returns a reference to the source (original) chunk.
35    #[inline]
36    pub fn source(&self) -> &Chunk<T> {
37        self.inner.source()
38    }
39
40    /// Returns a reference to the target (revised) chunk.
41    #[inline]
42    pub fn target(&self) -> &Chunk<T> {
43        self.inner.target()
44    }
45
46    /// Applies this delete delta to the target vector.
47    ///
48    /// Drains/removes the elements specified by the source chunk's range.
49    pub fn apply_to(&self, target: &mut Vec<T>) -> Result<(), PatchError> {
50        let position = self.source().position();
51        let size = self.source().len();
52
53        if position > target.len() || position + size > target.len() {
54            return Err(PatchError::PatchFailed(format!(
55                "DeleteDelta range [{}..{}] out of bounds for target length {}",
56                position,
57                position + size,
58                target.len()
59            )));
60        }
61
62        target.drain(position..position + size);
63        Ok(())
64    }
65
66    /// Restores (un-applies) this delete delta on the target vector.
67    ///
68    /// Re-inserts the removed original lines back into the target vector at the recorded position.
69    pub fn restore(&self, target: &mut Vec<T>) -> Result<(), PatchError>
70    where
71        T: Clone,
72    {
73        let position = self.target().position();
74
75        if position > target.len() {
76            return Err(PatchError::PatchFailed(format!(
77                "DeleteDelta restore position {} out of bounds for target length {}",
78                position,
79                target.len()
80            )));
81        }
82
83        target.splice(position..position, self.source().lines().iter().cloned());
84
85        Ok(())
86    }
87
88    /// Creates a new `DeleteDelta` with custom source and target chunks.
89    #[must_use]
90    pub fn with_chunks(&self, original: Chunk<T>, revised: Chunk<T>) -> Self {
91        Self::new(original, revised)
92    }
93}
94
95impl<T: fmt::Debug> fmt::Display for DeleteDelta<T> {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        write!(
98            f,
99            "[DeleteDelta, position: {}, lines: {:?}]",
100            self.source().position(),
101            self.source().lines()
102        )
103    }
104}
105
106impl<T> From<DeleteDelta<T>> for Delta<T> {
107    fn from(delete: DeleteDelta<T>) -> Self {
108        delete.inner
109    }
110}