summaryrefslogtreecommitdiffstats
path: root/src/commute.rs
blob: 85a996e4d36e09eae961cde7aff080dc09984170 (plain)
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
extern crate failure;

use owned;
use std::iter;

/// Returns the unchanged lines around this hunk.
///
/// Any given hunk has four anchor points:
///
/// - the last unchanged line before it, on the removed side
/// - the first unchanged line after it, on the removed side
/// - the last unchanged line before it, on the added side
/// - the first unchanged line after it, on the added side
///
/// This function returns those four line numbers, in that order.
fn anchors(hunk: &owned::Hunk) -> (usize, usize, usize, usize) {
    match (hunk.removed.lines.len(), hunk.added.lines.len()) {
        (0, 0) => (0, 1, 0, 1),
        (removed_len, 0) => (
            hunk.removed.start - 1,
            hunk.removed.start + removed_len,
            hunk.removed.start - 1,
            hunk.removed.start,
        ),
        (0, added_len) => (
            hunk.added.start - 1,
            hunk.added.start,
            hunk.added.start - 1,
            hunk.added.start + added_len,
        ),
        (removed_len, added_len) => (
            hunk.removed.start - 1,
            hunk.removed.start + removed_len,
            hunk.added.start - 1,
            hunk.added.start + added_len,
        ),
    }
}

/// Tests if all elements of the iterator are equal to each other.
///
/// An empty iterator returns `true`.
///
/// `uniform()` is short-circuiting. It will stop processing as soon
/// as it finds two pairwise inequal elements.
fn uniform<I, E>(mut iter: I) -> bool
where
    I: iter::Iterator<Item = E>,
    E: ::std::cmp::Eq,
{
    match iter.next() {
        Some(first) => iter.all(|e| e == first),
        None => true,
    }
}

pub fn commute(first: &owned::Hunk, second: &owned::Hunk) -> Option<(owned::Hunk, owned::Hunk)> {
    let (_, _, first_upper, first_lower) = anchors(first);
    let (second_upper, second_lower, _, _) = anchors(second);

    // represent hunks in content order rather than application order
    let (first_above, above, below) = {
        if first_lower <= second_upper {
            (true, first, second)
        } else if second_lower <= first_upper {
            (false, second, first)
        } else {
            // if both hunks are exclusively adding or removing, and
            // both hunks are composed entirely of the same line being
            // repeated, then they commute no matter what their
            // offsets are, because they can be interleaved in any
            // order without changing the final result
            if first.added.lines.is_empty() && second.added.lines.is_empty()
                && uniform(first.removed.lines.iter().chain(&*second.removed.lines))
            {
                // TODO: removed start positions probably need to be
                // tweaked here
                return Some((second.clone(), first.clone()));
            } else if first.removed.lines.is_empty() && second.removed.lines.is_empty()
                && uniform(first.added.lines.iter().chain(&*second.added.lines))
            {
                // TODO: added start positions probably need to be
                // tweaked here
                return Some((second.clone(), first.clone()));
            }
            // these hunks overlap and cannot be interleaved, so they
            // do not commute
            return None;
        }
    };

    let above = above.clone();
    let mut below = below.clone();
    let above_change_offset = (above.added.lines.len() as i64 - above.removed.lines.len() as i64)
        * if first_above { -1 } else { 1 };
    below.added.start = (below.added.start as i64 + above_change_offset) as usize;
    below.removed.start = (below.removed.start as i64 + above_change_offset) as usize;

    Some(if first_above {
        (below, above)
    } else {
        (above, below)
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::rc::Rc;

    #[test]
    fn test_commute() {
        let hunk1 = owned::Hunk {
            added: owned::Block {
                start: 2,
                lines: Rc::new(vec![b"bar\n".to_vec()]),
                trailing_newline: true,
            },
            removed: owned::Block {
                start: 1,
                lines: Rc::new(vec![]),
                trailing_newline: true,
            },
        };

        let hunk2 = owned::Hunk {
            added: owned::Block {
                start: 1,
                lines: Rc::new(vec![b"bar\n".to_vec()]),
                trailing_newline: true,
            },
            removed: owned::Block {
                start: 0,
                lines: Rc::new(vec![]),
                trailing_newline: true,
            },
        };

        let (new1, new2) = commute(&hunk1, &hunk2).unwrap();
        assert_eq!(new1.added.start, 1);
        assert_eq!(new2.added.start, 3);
    }

    #[test]
    fn test_commute_interleave() {
        let mut line = iter::repeat(b"bar\n".to_vec());
        let hunk1 = owned::Hunk {
            added: owned::Block {
                start: 1,
                lines: Rc::new((&mut line).take(4).collect::<Vec<_>>()),
                trailing_newline: true,
            },
            removed: owned::Block {
                start: 0,
                lines: Rc::new(vec![]),
                trailing_newline: true,
            },
        };
        let hunk2 = owned::Hunk {
            added: owned::Block {
                start: 1,
                lines: Rc::new((&mut line).take(2).collect::<Vec<_>>()),
                trailing_newline: true,
            },
            removed: owned::Block {
                start: 0,
                lines: Rc::new(vec![]),
                trailing_newline: true,
            },
        };

        let (new1, new2) = commute(&hunk1, &hunk2).unwrap();
        assert_eq!(new1.added.lines.len(), 2);
        assert_eq!(new2.added.lines.len(), 4);
    }
}