OXYGENHUB

Coverage / crates/oxy-core/src/lines.rs 94.9%

148 of 156 lines run, 60 of 71 functions · run #322 on main · run missed

1
//! The lines of an insert (spec §7.4) held as one buffer and where each
2
//! line ends, shared by the change and the file graph it builds: a tree of
3
//! forty million lines is then a few allocations per insert, not one per
4
//! line, and a graph's atoms point into their insert's buffer rather than
5
//! copying it.
6
7
use std::sync::Arc;
8
9
#[derive(Default, PartialEq, Eq, Hash)]
10
struct Inner {
11
    /// Shared with the file it was read from, when there was one.
12
    buf: Arc<Vec<u8>>,
13
    /// The end offset of each line in `buf`.
14
    ends: Ends,
15
}
16
17
/// Line end offsets, four bytes each unless the buffer is over 4 GiB: a
18
/// first commit of the Linux tree holds 36 million of them at once. Which
19
/// form follows from the buffer's length alone, so equal lines compare
20
/// equal.
21
#[derive(PartialEq, Eq, Hash)]
22
enum Ends {
23
    Small(Vec<u32>),
24
    Large(Vec<u64>),
25
}
26
27
impl Default for Ends {
2851707×
    fn default() -> Self {
2951707×
        Ends::Small(Vec::new())
3051707×
    }
31
}
32
33
impl Ends {
3444136×
    fn from_u64(ends: Vec<u64>, buf_len: usize) -> Ends {
3544136×
        if u32::try_from(buf_len).is_ok() {
3689959×
            Ends::Small(ends.into_iter().map(|e| e as u32).collect())
37
        } else {
380×
            Ends::Large(ends)
39
        }
4044136×
    }
41
42364441×
    fn len(&self) -> usize {
43364441×
        match self {
44364441×
            Ends::Small(v) => v.len(),
450×
            Ends::Large(v) => v.len(),
46
        }
47364441×
    }
48
49135560×
    fn is_empty(&self) -> bool {
50135560×
        self.len() == 0
51135560×
    }
52
53940108×
    fn get(&self, i: usize) -> Option<usize> {
54940108×
        match self {
55940108×
            Ends::Small(v) => v.get(i).map(|&e| e as usize),
560×
            Ends::Large(v) => v.get(i).map(|&e| e as usize),
57
        }
58940108×
    }
59
}
60
61
/// An insert's lines. Cloning is cheap: the buffer is shared.
62
#[derive(Clone, Default, PartialEq, Eq, Hash)]
63
pub struct Lines(Arc<Inner>);
64
65
impl Lines {
66
    /// Lines from their bytes, each keeping its terminator; a final
67
    /// unterminated line is its own line (the rule of
68
    /// [`crate::diff::split_lines`]).
69141×
    pub fn split(content: &[u8]) -> Lines {
70141×
        Lines::split_shared(Arc::new(content.to_vec()))
71141×
    }
72
73
    /// [`Lines::split`] of a buffer held elsewhere too (a file's content),
74
    /// shared rather than copied.
756033×
    pub fn split_shared(buf: Arc<Vec<u8>>) -> Lines {
766033×
        let content = &buf[..];
77
        // Counted first, so the offsets take exactly their room.
786033×
        let newlines = memchr::memchr_iter(b'\n', content).count();
796033×
        let unterminated = content.last().is_some_and(|&c| c != b'\n');
806033×
        let n = newlines + usize::from(unterminated);
816033×
        let ends_at = memchr::memchr_iter(b'\n', content)
82198340×
            .map(|i| i + 1)
836033×
            .chain(unterminated.then_some(content.len()));
846033×
        let ends = if u32::try_from(content.len()).is_ok() {
856033×
            let mut v = Vec::with_capacity(n);
86198474×
            v.extend(ends_at.map(|e| e as u32));
876033×
            Ends::Small(v)
88
        } else {
890×
            let mut v = Vec::with_capacity(n);
900×
            v.extend(ends_at.map(|e| e as u64));
910×
            Ends::Large(v)
92
        };
936033×
        Lines(Arc::new(Inner { buf, ends }))
946033×
    }
95
96194241×
    pub fn len(&self) -> usize {
97194241×
        self.0.ends.len()
98194241×
    }
99
100135560×
    pub fn is_empty(&self) -> bool {
101135560×
        self.0.ends.is_empty()
102135560×
    }
103
104
    /// Line `i`, with its terminator.
105488706×
    pub fn get(&self, i: usize) -> Option<&[u8]> {
106488706×
        let end = self.0.ends.get(i)?;
107488706×
        let start = if i == 0 { 0 } else { self.0.ends.get(i - 1)? };
108488706×
        Some(&self.0.buf[start..end])
109488706×
    }
110
11139948×
    pub fn iter(&self) -> impl ExactSizeIterator<Item = &[u8]> + Clone + '_ {
112312401×
        (0..self.len()).map(move |i| self.get(i).unwrap())
11339948×
    }
114
115
    /// Every line, joined: the bytes they were split from.
1165694×
    pub fn bytes(&self) -> &[u8] {
1175694×
        &self.0.buf
1185694×
    }
119
120
    /// Whether splitting [`Lines::bytes`] by the line rule gives these lines
121
    /// back: every line but the last ends in a newline and none holds
122
    /// another. Every insert oxy makes is so, and such lines are stored as
123
    /// their bytes alone (spec §7.4).
12479×
    pub fn is_split_form(&self) -> bool {
12579×
        let buf = &self.0.buf;
12679×
        let mut start = 0usize;
12734562×
        for i in 0..self.0.ends.len() {
12834562×
            let end = self.0.ends.get(i).unwrap_or(start);
12934562×
            let line = &buf[start..end];
13034562×
            if line.is_empty() {
1311×
                return false;
13234561×
            }
13334561×
            let last = i + 1 == self.0.ends.len();
13434561×
            let body = if last && !line.ends_with(b"\n") {
13553×
                line
13634508×
            } else if line.ends_with(b"\n") {
13734505×
                &line[..line.len() - 1]
138
            } else {
1393×
                return false;
140
            };
14134558×
            if body.contains(&b'\n') {
1421×
                return false;
14334557×
            }
14434557×
            start = end;
145
        }
14674×
        true
14779×
    }
148
149
    /// Lines `range` as lines of their own.
1501×
    pub fn slice(&self, range: std::ops::Range<usize>) -> Lines {
1511×
        self.iter().skip(range.start).take(range.len()).collect()
1521×
    }
153
154
    /// The lines as owned vectors, for code that edits them one by one.
15516×
    pub fn to_vec(&self) -> Vec<Vec<u8>> {
15616×
        self.iter().map(<[u8]>::to_vec).collect()
15716×
    }
158
}
159
160
impl std::ops::Index<usize> for Lines {
161
    type Output = [u8];
162176305×
    fn index(&self, i: usize) -> &[u8] {
163176305×
        self.get(i).expect("line index out of range")
164176305×
    }
165
}
166
167
impl<'a> FromIterator<&'a [u8]> for Lines {
16844072×
    fn from_iter<I: IntoIterator<Item = &'a [u8]>>(iter: I) -> Lines {
16944072×
        let (mut buf, mut ends) = (Vec::new(), Vec::new());
17081679×
        for l in iter {
17181679×
            buf.extend_from_slice(l);
17281679×
            ends.push(buf.len() as u64);
17381679×
        }
17444072×
        let ends = Ends::from_u64(ends, buf.len());
17544072×
        Lines(Arc::new(Inner {
17644072×
            buf: Arc::new(buf),
17744072×
            ends,
17844072×
        }))
17944072×
    }
180
}
181
182
impl FromIterator<Vec<u8>> for Lines {
18364×
    fn from_iter<I: IntoIterator<Item = Vec<u8>>>(iter: I) -> Lines {
18464×
        let (mut buf, mut ends) = (Vec::new(), Vec::new());
1858280×
        for l in iter {
1868280×
            buf.extend_from_slice(&l);
1878280×
            ends.push(buf.len() as u64);
1888280×
        }
18964×
        let ends = Ends::from_u64(ends, buf.len());
19064×
        Lines(Arc::new(Inner {
19164×
            buf: Arc::new(buf),
19264×
            ends,
19364×
        }))
19464×
    }
195
}
196
197
impl From<Vec<Vec<u8>>> for Lines {
19853×
    fn from(v: Vec<Vec<u8>>) -> Lines {
19953×
        v.into_iter().collect()
20053×
    }
201
}
202
203
impl std::fmt::Debug for Lines {
2046636×
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2056636×
        f.debug_list()
2066636×
            .entries(self.iter().map(String::from_utf8_lossy))
2076636×
            .finish()
2086636×
    }
209
}
210
211
/// One line of a [`Lines`], held by a file graph's atom.
212
#[derive(Clone, Debug, PartialEq, Eq)]
213
pub struct LineRef {
214
    lines: Lines,
215
    index: u32,
216
}
217
218
impl LineRef {
219181622×
    pub fn new(lines: Lines, index: u32) -> LineRef {
220181622×
        LineRef { lines, index }
221181622×
    }
222
223176304×
    pub fn bytes(&self) -> &[u8] {
224176304×
        &self.lines[self.index as usize]
225176304×
    }
226
}
227
228
#[cfg(test)]
229
mod tests {
230
    use super::*;
231
232
    #[test]
2331×
    fn lines_split_index_and_join_as_the_line_rule_says() {
2346×
        for text in [&b""[..], b"a\n", b"a\nb", b"a\n\nb\n", b"\n", b"no end"] {
2356×
            let l = Lines::split(text);
2366×
            let want = crate::diff::split_lines(text);
2376×
            assert_eq!(l.len(), want.len(), "{text:?}");
2386×
            assert_eq!(l.iter().collect::<Vec<_>>(), want);
2396×
            assert_eq!(l.bytes(), text);
2406×
            let v: Lines = want.iter().copied().collect();
2416×
            assert_eq!(v, l);
2426×
            assert_eq!(Lines::from(l.to_vec()), l);
243
        }
2441×
        let l = Lines::split(b"a\nb\nc\n");
2451×
        assert!(l.is_split_form());
2461×
        assert!(!Lines::from(vec![b"a".to_vec(), b"b\n".to_vec()]).is_split_form());
2471×
        assert!(!Lines::from(vec![b"a\nb\n".to_vec()]).is_split_form());
2481×
        assert!(!Lines::from(vec![Vec::new()]).is_split_form());
2491×
        assert!(Lines::from(vec![b"a\n".to_vec(), b"end".to_vec()]).is_split_form());
2501×
        assert_eq!(&l[1], b"b\n");
2511×
        assert_eq!(
2521×
            l.slice(1..3).to_vec(),
2531×
            vec![b"b\n".to_vec(), b"c\n".to_vec()]
254
        );
2551×
        assert_eq!(LineRef::new(l.clone(), 2).bytes(), b"c\n");
2561×
    }
257
}