OXYGENHUB

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

148 of 156 lines run, 60 of 71 functions · run #381 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 {
2852724×
    fn default() -> Self {
2952724×
        Ends::Small(Vec::new())
3052724×
    }
31
}
32
33
impl Ends {
3445591×
    fn from_u64(ends: Vec<u64>, buf_len: usize) -> Ends {
3545591×
        if u32::try_from(buf_len).is_ok() {
3692172×
            Ends::Small(ends.into_iter().map(|e| e as u32).collect())
37
        } else {
380×
            Ends::Large(ends)
39
        }
4045591×
    }
41
42380930×
    fn len(&self) -> usize {
43380930×
        match self {
44380930×
            Ends::Small(v) => v.len(),
450×
            Ends::Large(v) => v.len(),
46
        }
47380930×
    }
48
49139072×
    fn is_empty(&self) -> bool {
50139072×
        self.len() == 0
51139072×
    }
52
53960595×
    fn get(&self, i: usize) -> Option<usize> {
54960595×
        match self {
55960595×
            Ends::Small(v) => v.get(i).map(|&e| e as usize),
560×
            Ends::Large(v) => v.get(i).map(|&e| e as usize),
57
        }
58960595×
    }
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.
756162×
    pub fn split_shared(buf: Arc<Vec<u8>>) -> Lines {
766162×
        let content = &buf[..];
77
        // Counted first, so the offsets take exactly their room.
786162×
        let newlines = memchr::memchr_iter(b'\n', content).count();
796162×
        let unterminated = content.last().is_some_and(|&c| c != b'\n');
806162×
        let n = newlines + usize::from(unterminated);
816162×
        let ends_at = memchr::memchr_iter(b'\n', content)
82198512×
            .map(|i| i + 1)
836162×
            .chain(unterminated.then_some(content.len()));
846162×
        let ends = if u32::try_from(content.len()).is_ok() {
856162×
            let mut v = Vec::with_capacity(n);
86198646×
            v.extend(ends_at.map(|e| e as u32));
876162×
            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
        };
936162×
        Lines(Arc::new(Inner { buf, ends }))
946162×
    }
95
96202167×
    pub fn len(&self) -> usize {
97202167×
        self.0.ends.len()
98202167×
    }
99
100139072×
    pub fn is_empty(&self) -> bool {
101139072×
        self.0.ends.is_empty()
102139072×
    }
103
104
    /// Line `i`, with its terminator.
105497689×
    pub fn get(&self, i: usize) -> Option<&[u8]> {
106497689×
        let end = self.0.ends.get(i)?;
107497689×
        let start = if i == 0 { 0 } else { self.0.ends.get(i - 1)? };
108497689×
        Some(&self.0.buf[start..end])
109497689×
    }
110
11141641×
    pub fn iter(&self) -> impl ExactSizeIterator<Item = &[u8]> + Clone + '_ {
112319932×
        (0..self.len()).map(move |i| self.get(i).unwrap())
11341641×
    }
114
115
    /// Every line, joined: the bytes they were split from.
1165760×
    pub fn bytes(&self) -> &[u8] {
1175760×
        &self.0.buf
1185760×
    }
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).
124105×
    pub fn is_split_form(&self) -> bool {
125105×
        let buf = &self.0.buf;
126105×
        let mut start = 0usize;
12739587×
        for i in 0..self.0.ends.len() {
12839587×
            let end = self.0.ends.get(i).unwrap_or(start);
12939587×
            let line = &buf[start..end];
13039587×
            if line.is_empty() {
1311×
                return false;
13239586×
            }
13339586×
            let last = i + 1 == self.0.ends.len();
13439586×
            let body = if last && !line.ends_with(b"\n") {
13578×
                line
13639508×
            } else if line.ends_with(b"\n") {
13739505×
                &line[..line.len() - 1]
138
            } else {
1393×
                return false;
140
            };
14139583×
            if body.contains(&b'\n') {
1421×
                return false;
14339582×
            }
14439582×
            start = end;
145
        }
146100×
        true
147105×
    }
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.
15517×
    pub fn to_vec(&self) -> Vec<Vec<u8>> {
15617×
        self.iter().map(<[u8]>::to_vec).collect()
15717×
    }
158
}
159
160
impl std::ops::Index<usize> for Lines {
161
    type Output = [u8];
162177757×
    fn index(&self, i: usize) -> &[u8] {
163177757×
        self.get(i).expect("line index out of range")
164177757×
    }
165
}
166
167
impl<'a> FromIterator<&'a [u8]> for Lines {
16845527×
    fn from_iter<I: IntoIterator<Item = &'a [u8]>>(iter: I) -> Lines {
16945527×
        let (mut buf, mut ends) = (Vec::new(), Vec::new());
17083892×
        for l in iter {
17183892×
            buf.extend_from_slice(l);
17283892×
            ends.push(buf.len() as u64);
17383892×
        }
17445527×
        let ends = Ends::from_u64(ends, buf.len());
17545527×
        Lines(Arc::new(Inner {
17645527×
            buf: Arc::new(buf),
17745527×
            ends,
17845527×
        }))
17945527×
    }
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 {
2046800×
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2056800×
        f.debug_list()
2066800×
            .entries(self.iter().map(String::from_utf8_lossy))
2076800×
            .finish()
2086800×
    }
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 {
219183490×
    pub fn new(lines: Lines, index: u32) -> LineRef {
220183490×
        LineRef { lines, index }
221183490×
    }
222
223177756×
    pub fn bytes(&self) -> &[u8] {
224177756×
        &self.lines[self.index as usize]
225177756×
    }
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
}