1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
use crate::alive::{output_graph, Graph};
use crate::changestore::*;
use crate::pristine::*;
use crate::record::Recorded;
use crate::text_encoding::Encoding;

mod bin;

mod diff;
mod split;
mod vertex_buffer;
pub use diff::Algorithm;
mod delete;
mod replace;

lazy_static! {
    pub static ref DEFAULT_SEPARATOR: regex::bytes::Regex = regex::bytes::Regex::new("\n").unwrap();
}

#[derive(Hash, Clone, Copy)]
struct Line<'a> {
    l: &'a [u8],
    cyclic: bool,
    before_end_marker: bool,
    last: bool,
    ptr: *const u8,
}

impl<'a> std::fmt::Debug for Line<'a> {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(fmt, "Line {{ l: {:?} }}", std::str::from_utf8(self.l))
    }
}

impl<'a> Default for Line<'a> {
    fn default() -> Self {
        Line {
            l: &[],
            cyclic: false,
            before_end_marker: false,
            last: false,
            ptr: std::ptr::null(),
        }
    }
}

impl<'a> PartialEq for Line<'a> {
    fn eq(&self, b: &Self) -> bool {
        if self.before_end_marker && !b.last && b.l.last() == Some(&b'\n') {
            return &b.l[..b.l.len() - 1] == self.l;
        }
        if b.before_end_marker && !self.last && self.l.last() == Some(&b'\n') {
            return &self.l[..self.l.len() - 1] == b.l;
        }
        ((self.ptr == b.ptr && self.l.len() == b.l.len()) || self.l == b.l)
            && self.cyclic == b.cyclic
    }
}
impl<'a> Eq for Line<'a> {}

#[derive(Debug, Error)]
pub enum DiffError<P: std::error::Error + 'static, T: std::error::Error + 'static> {
    #[error(transparent)]
    Output(#[from] crate::output::FileError<P, T>),
    #[error(transparent)]
    Txn(T),
}

impl<T: std::error::Error + 'static, C: std::error::Error + 'static> std::convert::From<TxnErr<T>>
    for DiffError<C, T>
{
    fn from(e: TxnErr<T>) -> Self {
        DiffError::Txn(e.0)
    }
}

fn make_old_lines<'a>(d: &'a vertex_buffer::Diff, r: &'a regex::bytes::Regex) -> Vec<Line<'a>> {
    d.lines(r)
        .map(|l| {
            let old_bytes = l.as_ptr() as usize - d.contents_a.as_ptr() as usize;
            let cyclic = if let Err(n) = d
                .cyclic_conflict_bytes
                .binary_search(&(old_bytes, std::usize::MAX))
            {
                n > 0 && {
                    let (a, b) = d.cyclic_conflict_bytes[n - 1];
                    a <= old_bytes && old_bytes < b
                }
            } else {
                false
            };
            let before_end_marker = if l.last() != Some(&b'\n') {
                let next_index = l.as_ptr() as usize + l.len() - d.contents_a.as_ptr() as usize + 1;
                d.marker.get(&next_index) == Some(&vertex_buffer::ConflictMarker::End)
            } else {
                false
            };
            debug!("old = {:?}", l);
            Line {
                l,
                cyclic,
                before_end_marker,
                last: l.as_ptr() as usize + l.len() - d.contents_a.as_ptr() as usize
                    >= d.contents_a.len(),
                ptr: l.as_ptr(),
            }
        })
        .collect()
}

fn make_new_lines<'a>(b: &'a [u8], sep: &'a regex::bytes::Regex) -> Vec<Line<'a>> {
    split::LineSplit::from_bytes_with_sep(b, sep)
        .map(|l| {
            debug!("new: {:?}", l);
            let next_index = l.as_ptr() as usize + l.len() - b.as_ptr() as usize;
            Line {
                l,
                cyclic: false,
                before_end_marker: false,
                last: next_index >= b.len(),
                ptr: l.as_ptr(),
            }
        })
        .collect()
}

impl Recorded {
    pub(crate) fn diff<T: ChannelTxnT, P: ChangeStore>(
        &mut self,
        changes: &P,
        txn: &T,
        channel: &T::Channel,
        algorithm: Algorithm,
        path: String,
        inode_: Inode,
        inode: Position<Option<ChangeId>>,
        a: &mut Graph,
        b: &[u8],
        encoding: &Option<Encoding>,
        separator: &regex::bytes::Regex,
    ) -> Result<(), DiffError<P::Error, T::GraphError>> {
        self.largest_file = self.largest_file.max(b.len() as u64);
        let mut d = vertex_buffer::Diff::new(inode, path.clone(), a);
        output_graph(changes, txn, channel, &mut d, a, &mut self.redundant)?;
        // TODO pass through both encodings and use that to decide
        debug!("encoding = {:?}", encoding);
        let (lines_a, lines_b) = if encoding.is_none() {
            const ROLLING_SIZE: usize = 8192;
            debug!("contents_a: {:?}", d.contents_a.len());
            let (ah, old) = bin::make_old_chunks(ROLLING_SIZE, &d.contents_a);
            let (bb, new) = bin::make_new_chunks(ROLLING_SIZE, &ah, &b);
            debug!("bb = {:?}", bb);
            (old, new)
        } else {
            (make_old_lines(&d, separator), make_new_lines(&b, separator))
        };

        trace!("pos = {:?}", d.pos_a);
        if log::log_enabled!(log::Level::Trace) {
            for l in lines_a.iter() {
                trace!("a: {:?}", l)
            }
            for l in lines_b.iter() {
                trace!("b: {:?}", l)
            }
        }
        let dd = diff::diff(&lines_a, &lines_b, algorithm);
        let mut conflict_contexts = replace::ConflictContexts::new();
        for r in 0..dd.len() {
            if dd[r].old_len > 0 {
                self.delete(
                    txn,
                    txn.graph(channel),
                    &d,
                    &dd,
                    &mut conflict_contexts,
                    &lines_a,
                    &lines_b,
                    inode_,
                    r,
                    encoding,
                )?;
            }
            if dd[r].new_len > 0 {
                self.replace(
                    &d,
                    &mut conflict_contexts,
                    &lines_a,
                    &lines_b,
                    inode_,
                    &dd,
                    r,
                    encoding,
                );
            }
        }
        debug!("Diff ended");
        Ok(())
    }
}
fn bytes_pos(chunks: &[Line], old: usize) -> usize {
    if old < chunks.len() {
        chunks[old].l.as_ptr() as usize - chunks[0].l.as_ptr() as usize
    } else if old > 0 {
        chunks[old - 1].l.as_ptr() as usize - chunks[0].l.as_ptr() as usize
            + chunks[old - 1].l.len()
    } else {
        0
    }
}
fn bytes_len(chunks: &[Line], old: usize, len: usize) -> usize {
    if let Some(p) = chunks.get(old + len) {
        p.l.as_ptr() as usize - chunks[old].l.as_ptr() as usize
    } else if old + len > 0 {
        chunks[old + len - 1].l.as_ptr() as usize + chunks[old + len - 1].l.len()
            - chunks[old].l.as_ptr() as usize
    } else {
        chunks[old + len].l.as_ptr() as usize - chunks[old].l.as_ptr() as usize
    }
}