bigtext 0.3.0

Fast text editor for huge files (1-50+ GB): opens instantly, never freezes, streaming search/replace and atomic save
Documentation
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! Streaming line diff of two (possibly huge) files with bounded memory.
//!
//! Identical stretches are skipped with fast chunk comparison (no per-line work). At a
//! difference both sides are rewound to the start of the differing line and the next lines are
//! read into a bounded look-ahead window as (hash, length, offset) records; the two sides are
//! re-synchronised at the earliest pair of positions where three consecutive lines agree (or
//! where both files end). Lines are compared by 64-bit hash plus length, so arbitrarily long
//! lines need no buffering. Differences that do not re-synchronise within the window are
//! reported as one hunk per window, so the pass always makes progress.

use std::collections::HashMap;
use std::ops::Range;

use crate::encoding::count_byte;
use crate::file::Source;
use crate::jobs::{CancelToken, Progress};

const CHUNK: usize = 4 * 1024 * 1024;
/// Look-ahead per side when re-synchronising.
const WINDOW_LINES: usize = 4096;
const WINDOW_BYTES: u64 = 16 * 1024 * 1024;
const ANCHOR: usize = 3;

/// A differing region: `a_count` lines of A starting at `a_line` were replaced by `b_count`
/// lines of B starting at `b_line` (0-based line numbers, byte offsets of the first line).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Hunk {
    pub a_line: u64,
    pub a_count: u64,
    pub a_off: u64,
    pub b_line: u64,
    pub b_count: u64,
    pub b_off: u64,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DiffEnd {
    Completed,
    Stopped,
    Cancelled,
    Failed,
}

#[derive(Clone, Copy, Debug)]
struct Line {
    off: u64,
    len: u64,
    hash: u64,
}

/// Streaming 64-bit hash (FNV-1a over 8-byte words with a final mix).
#[derive(Clone, Copy)]
struct LineHasher {
    h: u64,
    tail: u64,
    tail_len: u32,
}

impl LineHasher {
    fn new() -> Self {
        LineHasher { h: 0xcbf2_9ce4_8422_2325, tail: 0, tail_len: 0 }
    }
    #[inline]
    fn word(&mut self, w: u64) {
        self.h = (self.h ^ w).wrapping_mul(0x0000_0100_0000_01b3).rotate_left(29);
    }
    fn update(&mut self, mut b: &[u8]) {
        while self.tail_len != 0 && !b.is_empty() {
            self.tail |= (b[0] as u64) << (8 * self.tail_len);
            self.tail_len += 1;
            b = &b[1..];
            if self.tail_len == 8 {
                let t = self.tail;
                self.word(t);
                self.tail = 0;
                self.tail_len = 0;
            }
        }
        let mut chunks = b.chunks_exact(8);
        for c in &mut chunks {
            self.word(u64::from_le_bytes(c.try_into().unwrap()));
        }
        for &x in chunks.remainder() {
            self.tail |= (x as u64) << (8 * self.tail_len);
            self.tail_len += 1;
        }
    }
    fn finish(mut self) -> u64 {
        if self.tail_len > 0 {
            let t = self.tail ^ (0xff << (8 * self.tail_len.min(7)));
            self.word(t);
        }
        let mut z = self.h;
        z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
        z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
        z ^ (z >> 31)
    }
}

/// Sequential reader over a source with a reusable chunk buffer.
struct Reader<'a> {
    src: &'a Source,
    pos: u64,
    line: u64,
    buf: Vec<u8>,
    buf_start: u64,
    buf_len: usize,
}

impl<'a> Reader<'a> {
    fn new(src: &'a Source) -> Self {
        Reader { src, pos: 0, line: 0, buf: vec![0; CHUNK], buf_start: 0, buf_len: 0 }
    }

    fn eof(&self) -> bool {
        self.pos >= self.src.len()
    }

    /// Bytes available at `pos` (refilling the buffer as needed).
    fn peek(&mut self) -> Option<&[u8]> {
        let len = self.src.len();
        if self.pos >= len {
            return Some(&[]);
        }
        if self.pos < self.buf_start || self.pos >= self.buf_start + self.buf_len as u64 {
            let n = ((len - self.pos) as usize).min(CHUNK);
            self.src.read_into(self.pos, &mut self.buf[..n]).ok()?;
            self.buf_start = self.pos;
            self.buf_len = n;
        }
        let s = (self.pos - self.buf_start) as usize;
        Some(&self.buf[s..self.buf_len])
    }

    fn advance(&mut self, n: u64, newlines: u64) {
        self.pos += n;
        self.line += newlines;
    }

    /// Reads the next line (including its '\n') as a hash record.
    fn next_line(&mut self) -> Option<Line> {
        let off = self.pos;
        let mut h = LineHasher::new();
        let mut len = 0u64;
        loop {
            let chunk = self.peek()?;
            if chunk.is_empty() {
                break;
            }
            match memchr::memchr(b'\n', chunk) {
                Some(i) => {
                    h.update(&chunk[..=i]);
                    len += i as u64 + 1;
                    self.pos += i as u64 + 1;
                    self.line += 1;
                    return Some(Line { off, len, hash: h.finish() ^ len });
                }
                None => {
                    let n = chunk.len();
                    h.update(chunk);
                    len += n as u64;
                    self.pos += n as u64;
                }
            }
        }
        if len == 0 {
            None
        } else {
            Some(Line { off, len, hash: h.finish() ^ len })
        }
    }
}

/// Length of the common prefix of two byte slices.
fn common_prefix(a: &[u8], b: &[u8]) -> usize {
    let n = a.len().min(b.len());
    let mut i = 0;
    while i + 64 <= n && a[i..i + 64] == b[i..i + 64] {
        i += 64;
    }
    while i < n && a[i] == b[i] {
        i += 1;
    }
    i
}

fn read_window(r: &mut Reader) -> Option<Vec<Line>> {
    let mut v = Vec::new();
    let mut bytes = 0;
    while v.len() < WINDOW_LINES && bytes < WINDOW_BYTES {
        match r.next_line() {
            Some(l) => {
                bytes += l.len;
                v.push(l);
            }
            None if r.eof() => break,
            None => return None,
        }
    }
    Some(v)
}

/// Earliest (i, j) with `ANCHOR` agreeing lines (fewer at the end of both files), minimising i + j.
fn find_anchor(a: &[Line], b: &[Line], a_eof: bool, b_eof: bool) -> Option<(usize, usize)> {
    let mut first_in_b: HashMap<(u64, u64), Vec<usize>> = HashMap::with_capacity(b.len());
    for (j, l) in b.iter().enumerate() {
        first_in_b.entry((l.hash, l.len)).or_default().push(j);
    }
    let agree = |i: usize, j: usize| -> bool {
        for k in 0..ANCHOR {
            match (a.get(i + k), b.get(j + k)) {
                (Some(x), Some(y)) if x.hash == y.hash && x.len == y.len => {}
                // Both sides end together: the tail matches.
                (None, None) if a_eof && b_eof => return true,
                _ => return false,
            }
        }
        true
    };
    let mut best: Option<(usize, usize)> = None;
    for (i, l) in a.iter().enumerate() {
        if let Some((bi, bj)) = best {
            if i > bi + bj {
                break;
            }
        }
        if let Some(js) = first_in_b.get(&(l.hash, l.len)) {
            for &j in js {
                if let Some((bi, bj)) = best {
                    if i + j >= bi + bj {
                        break;
                    }
                }
                if agree(i, j) {
                    best = Some((i, j));
                    break;
                }
            }
        }
    }
    // Both windows reach the ends of their files: the remainders differ entirely.
    if best.is_none() && a_eof && b_eof {
        return Some((a.len(), b.len()));
    }
    best
}

/// Compares `a` and `b`, calling `on_hunk` for each differing region in order (return false to
/// stop). Progress is reported in bytes of `a` + `b` consumed.
pub fn diff(a: &Source, b: &Source, cancel: &CancelToken, progress: Option<&Progress>, mut on_hunk: impl FnMut(Hunk) -> bool) -> DiffEnd {
    let mut ra = Reader::new(a);
    let mut rb = Reader::new(b);
    if let Some(p) = progress {
        p.set_total(a.len() + b.len());
    }
    loop {
        if cancel.is_cancelled() {
            return DiffEnd::Cancelled;
        }
        if let Some(p) = progress {
            p.set_done(ra.pos + rb.pos);
        }
        // Fast path: skip identical bytes chunk by chunk, stopping at line starts.
        let (Some(x), Some(y)) = (ra.peek(), rb.peek()) else { return DiffEnd::Failed };
        if x.is_empty() && y.is_empty() {
            return DiffEnd::Completed;
        }
        let lim = x.len().min(y.len());
        let n = common_prefix(x, y);
        if n == lim && lim > 0 {
            let adv = memchr::memrchr(b'\n', &x[..lim]).map(|i| i + 1).unwrap_or(lim);
            let nl = count_byte(&x[..adv], b'\n');
            ra.advance(adv as u64, nl);
            rb.advance(adv as u64, nl);
            continue;
        }
        // Mismatch (or one side ended): rewind to the start of the differing line.
        let back = memchr::memrchr(b'\n', &x[..n]).map(|i| i + 1).unwrap_or(0);
        let nl = count_byte(&x[..back], b'\n');
        ra.advance(back as u64, nl);
        rb.advance(back as u64, nl);
        // Slow path: re-synchronise using line hashes.
        let (sa_line, sa_off, sb_line, sb_off) = (ra.line, ra.pos, rb.line, rb.pos);
        let Some(wa) = read_window(&mut ra) else { return DiffEnd::Failed };
        let Some(wb) = read_window(&mut rb) else { return DiffEnd::Failed };
        let (a_eof, b_eof) = (ra.eof(), rb.eof());
        let (i, j) = find_anchor(&wa, &wb, a_eof, b_eof).unwrap_or((wa.len(), wb.len()));
        if i > 0 || j > 0 {
            let h = Hunk { a_line: sa_line, a_count: i as u64, a_off: sa_off, b_line: sb_line, b_count: j as u64, b_off: sb_off };
            if !on_hunk(h) {
                return DiffEnd::Stopped;
            }
        }
        // Position both readers right after the hunk (before the anchor).
        let reposition = |r: &mut Reader, w: &[Line], k: usize, start_line: u64, start_off: u64| {
            r.pos = w.get(k).map(|l| l.off).unwrap_or_else(|| w.last().map(|l| l.off + l.len).unwrap_or(start_off));
            r.line = start_line + k as u64;
        };
        reposition(&mut ra, &wa, i, sa_line, sa_off);
        reposition(&mut rb, &wb, j, sb_line, sb_off);
        if i == 0 && j == 0 {
            // Anchored immediately (identical lines after a rewind): consume one equal line
            // to guarantee progress.
            let (la, lb) = (ra.next_line(), rb.next_line());
            if la.is_none() && lb.is_none() {
                return DiffEnd::Completed;
            }
        }
        if ra.eof() && rb.eof() {
            return DiffEnd::Completed;
        }
    }
}

/// Convenience for tests and small inputs: all hunks.
pub fn diff_all(a: &Source, b: &Source) -> Vec<Hunk> {
    let mut v = Vec::new();
    diff(a, b, &CancelToken::new(), None, |h| {
        v.push(h);
        true
    });
    v
}

/// Byte range of `count` lines starting at `off` (for previews).
pub fn hunk_range(off: u64, len: u64) -> Range<u64> {
    off..off + len
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::file::OpenMode;
    use std::io::Write;

    fn src(data: &[u8]) -> (tempfile::NamedTempFile, Source) {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        f.write_all(data).unwrap();
        f.flush().unwrap();
        let s = Source::open(f.path(), OpenMode::Auto).unwrap();
        (f, s)
    }

    fn lines(n: usize) -> String {
        (0..n).map(|i| format!("line number {i}\n")).collect()
    }

    fn summary(h: &[Hunk]) -> Vec<(u64, u64, u64, u64)> {
        h.iter().map(|h| (h.a_line, h.a_count, h.b_line, h.b_count)).collect()
    }

    #[test]
    fn identical_files() {
        let t = lines(1000);
        let (_a, a) = src(t.as_bytes());
        let (_b, b) = src(t.as_bytes());
        assert!(diff_all(&a, &b).is_empty());
        let (_e, e) = src(b"");
        let (_f, f) = src(b"");
        assert!(diff_all(&e, &f).is_empty());
    }

    #[test]
    fn single_change_insert_delete() {
        let base = lines(100);
        let changed = base.replace("line number 50\n", "CHANGED\n");
        let (_a, a) = src(base.as_bytes());
        let (_b, b) = src(changed.as_bytes());
        assert_eq!(summary(&diff_all(&a, &b)), vec![(50, 1, 50, 1)]);

        let inserted = base.replace("line number 10\n", "line number 10\nnew 1\nnew 2\n");
        let (_c, c) = src(inserted.as_bytes());
        assert_eq!(summary(&diff_all(&a, &c)), vec![(11, 0, 11, 2)]);

        let deleted = base.replace("line number 70\nline number 71\n", "");
        let (_d, d) = src(deleted.as_bytes());
        assert_eq!(summary(&diff_all(&a, &d)), vec![(70, 2, 70, 0)]);
    }

    #[test]
    fn differences_at_edges() {
        let base = lines(20);
        let (_a, a) = src(base.as_bytes());
        let head = format!("HEAD\n{base}");
        let (_b, b) = src(head.as_bytes());
        assert_eq!(summary(&diff_all(&a, &b)), vec![(0, 0, 0, 1)]);
        let tail = format!("{base}TAIL\n");
        let (_c, c) = src(tail.as_bytes());
        assert_eq!(summary(&diff_all(&a, &c)), vec![(20, 0, 20, 1)]);
        let (_e, e) = src(b"");
        assert_eq!(summary(&diff_all(&e, &a)), vec![(0, 0, 0, 20)]);
        // Last line without newline differs.
        let (_x, x) = src(b"a\nb\nc");
        let (_y, y) = src(b"a\nb\nd");
        assert_eq!(summary(&diff_all(&x, &y)), vec![(2, 1, 2, 1)]);
    }

    #[test]
    fn many_scattered_changes_in_big_file() {
        let base = lines(300_000); // ~6 MB, more than one chunk
        let mut changed = String::new();
        for (i, l) in base.lines().enumerate() {
            if i % 50_000 == 7 {
                changed.push_str("XXX\n");
            } else {
                changed.push_str(l);
                changed.push('\n');
            }
        }
        let (_a, a) = src(base.as_bytes());
        let (_b, b) = src(changed.as_bytes());
        let h = diff_all(&a, &b);
        assert_eq!(h.len(), 6);
        for (k, x) in h.iter().enumerate() {
            assert_eq!((x.a_line, x.a_count, x.b_count), (k as u64 * 50_000 + 7, 1, 1));
            let at = base.lines().take(x.a_line as usize).map(|l| l.len() + 1).sum::<usize>() as u64;
            assert_eq!(x.a_off, at);
        }
    }

    #[test]
    fn completely_different_files_progress() {
        let a_text: String = (0..10_000).map(|i| format!("a{i}\n")).collect();
        let b_text: String = (0..10_000).map(|i| format!("b{i}\n")).collect();
        let (_a, a) = src(a_text.as_bytes());
        let (_b, b) = src(b_text.as_bytes());
        let h = diff_all(&a, &b);
        let total_a: u64 = h.iter().map(|x| x.a_count).sum();
        let total_b: u64 = h.iter().map(|x| x.b_count).sum();
        assert_eq!((total_a, total_b), (10_000, 10_000));
    }

    #[test]
    fn hasher_is_streaming_consistent() {
        let data: Vec<u8> = (0..1000u32).map(|i| (i * 7 % 251) as u8).collect();
        let mut one = LineHasher::new();
        one.update(&data);
        for split in [1, 3, 7, 8, 9, 500] {
            let mut two = LineHasher::new();
            two.update(&data[..split]);
            two.update(&data[split..]);
            assert_eq!(one.finish(), two.finish());
        }
    }
}