bigtext 0.19.1

Free editor for huge text and log files (1-50+ GB): opens them without loading them into memory, 4 GB/s search, atomic save
Documentation
//! The match counter of the find bar ("3 of 1,204"). Find next / previous starts a count of the
//! pattern's matches in the whole document on a worker; it keeps a checkpoint at every 4,096th
//! match, and at the first match 4 MB or more after the previous one. The match a search
//! selected gets its number from another worker, which searches from the checkpoint before it:
//! at most 4,096 matches and about 4 MB. Typing in the find field starts nothing; a new pattern,
//! an edit or closing the tab cancels a count that is no longer wanted. Files read over the
//! network are not counted, since counting would read all of them.

use std::ops::Range;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use bigtext::jobs::{self, CancelToken, Throttle};
use bigtext::search::{self, Matcher, Query, SearchEnd};
use bigtext::text::TextBuf;

use super::filter_panel::fmt_count;
use super::i18n::{tr, trf};
use super::{BigTextApp, Msg};

/// Matches between two checkpoints, at most.
const MARK_EVERY: u64 = 4096;
/// Bytes after a checkpoint from which the next match is one too.
const MARK_GAP: u64 = 4 << 20;

/// A count of the matches of `query` in a document as it was (`version`, `len`).
pub struct MatchCount {
    pub query: Query,
    pub version: u64,
    pub len: u64,
    pub data: Arc<Mutex<CountData>>,
    pub cancel: CancelToken,
    /// The match whose number was asked for, so it is asked once.
    pub asked: Option<(u64, u64)>,
    /// A match and its number (`None`: it is not one of the counted matches, as when Find next
    /// started inside another match).
    pub number: Option<((u64, u64), Option<u64>)>,
}

#[derive(Default)]
pub struct CountData {
    /// Matches counted so far.
    pub total: u64,
    pub done: bool,
    /// (start, matches before it) of the checkpoints, in order.
    pub marks: Vec<(u64, u64)>,
}

/// Counts the matches of `m` in `range`, adding checkpoints to `data` as it goes.
fn count(
    buf: &TextBuf,
    m: &Matcher,
    range: Range<u64>,
    data: &Mutex<CountData>,
    cancel: &CancelToken,
    mut wake: impl FnMut(),
) -> SearchEnd {
    let mut total = 0u64;
    let mut marks = Vec::new();
    let mut last: Option<(u64, u64)> = None;
    let mut throttle = Throttle::new(Duration::from_millis(100));
    let end = search::search_forward_par(buf, m, range, cancel, None, |s, _| {
        if last.is_none_or(|(at, n)| total - n >= MARK_EVERY || s - at >= MARK_GAP) {
            marks.push((s, total));
            last = Some((s, total));
        }
        total += 1;
        if throttle.ready() {
            let mut g = data.lock().unwrap();
            g.total = total;
            g.marks.append(&mut marks);
            drop(g);
            wake();
        }
        true
    });
    let mut g = data.lock().unwrap();
    g.total = total;
    g.marks.append(&mut marks);
    g.done = end == SearchEnd::Completed;
    end
}

/// The number (from 1) of the match `sel` among all matches of `m`, from the checkpoints
/// `marks`; `None` when `sel` is not one of them.
fn number_of(
    buf: &TextBuf,
    m: &Matcher,
    marks: &[(u64, u64)],
    sel: (u64, u64),
    cancel: &CancelToken,
) -> Option<u64> {
    let (s, e) = sel;
    let i = marks.partition_point(|&(at, _)| at <= s).checked_sub(1)?;
    let (from, mut n) = marks[i];
    let mut number = None;
    let end = (e + m.overlap()).min(buf.len());
    search::search_forward(buf, m, from..end, cancel, None, |a, b| {
        if a < s {
            n += 1;
            return true;
        }
        if (a, b) == sel {
            number = Some(n + 1);
        }
        false
    });
    number.filter(|_| !cancel.is_cancelled())
}

impl BigTextApp {
    /// Starts counting the current pattern's matches in the active document, unless a count of
    /// them is there or running, or Find All's complete results give the number.
    pub(super) fn start_match_count(&mut self) {
        let query = self.search.query.clone();
        let Some(d) = self.docs.get(self.active) else {
            return;
        };
        // Only for the find bar, where the counter shows.
        if !self.search.open
            || query.pattern.is_empty()
            || !d.is_ready()
            || d.remote_ssh.is_some()
            || d.buf.source.is_remote()
            || d.growing.is_some()
        {
            return;
        }
        let (version, len) = (d.version, d.buf.len());
        if d.match_count
            .as_ref()
            .is_some_and(|c| c.query == query && c.version == version && c.len == len)
            || self.complete_results().is_some()
        {
            return;
        }
        let Ok(m) = self.search.matcher(d.buf.codec) else {
            return;
        };
        let d = &mut self.docs[self.active];
        if let Some(c) = d.match_count.take() {
            c.cancel.cancel();
        }
        let data = Arc::new(Mutex::new(CountData::default()));
        let cancel = CancelToken::new();
        d.match_count = Some(MatchCount {
            query,
            version,
            len,
            data: data.clone(),
            cancel: cancel.clone(),
            asked: None,
            number: None,
        });
        let snap = d.buf.snapshot();
        let waker = self.waker.clone();
        jobs::spawn("match-count", move || {
            count(&snap, &m, 0..len, &data, &cancel, || waker());
            waker();
        });
    }

    /// Find All's results for the current pattern when they are complete and current: every
    /// match of the document, in order.
    fn complete_results(&self) -> Option<Arc<Mutex<super::search_panel::ResultsData>>> {
        let d = self.docs.get(self.active)?;
        let r = d.results.as_ref()?;
        let g = r.data.lock().unwrap();
        (g.done
            && !g.capped
            && g.end == Some(SearchEnd::Completed)
            && r.query == self.search.query
            && r.version == d.version
            && r.range == (0..d.buf.len()))
            .then(|| r.data.clone())
    }

    /// Every frame: drops a count for another pattern or an older text, and once a count is
    /// done, asks for the number of the match a search selected.
    pub(super) fn match_count_tick(&mut self) {
        let query = &self.search.query;
        for d in &mut self.docs {
            let stale = d.match_count.as_ref().is_some_and(|c| {
                c.query != *query || c.version != d.version || c.len != d.buf.len()
            });
            if stale {
                if let Some(c) = d.match_count.take() {
                    c.cancel.cancel();
                }
            }
        }
        let Some(d) = self.docs.get_mut(self.active) else {
            return;
        };
        let Some(sel) = d.last_found.filter(|&f| f == d.selection()) else {
            return;
        };
        let Some(c) = d.match_count.as_mut() else {
            return;
        };
        if c.asked == Some(sel) || !c.data.lock().unwrap().done {
            return;
        }
        c.asked = Some(sel);
        let Ok(m) = self.search.matcher(d.buf.codec) else {
            return;
        };
        let d = &self.docs[self.active];
        let c = d.match_count.as_ref().unwrap();
        let (data, cancel, snap) = (c.data.clone(), c.cancel.clone(), d.buf.snapshot());
        let (doc, version, tx, waker) = (d.id, d.version, self.tx.clone(), self.waker.clone());
        jobs::spawn("match-number", move || {
            let marks = data.lock().unwrap().marks.clone();
            let number = number_of(&snap, &m, &marks, sel, &cancel);
            if !cancel.is_cancelled() {
                let _ = tx.send(Msg::MatchNumber {
                    doc,
                    version,
                    sel,
                    number,
                });
                waker();
            }
        });
    }

    pub(super) fn on_match_number(
        &mut self,
        doc: u64,
        version: u64,
        sel: (u64, u64),
        number: Option<u64>,
    ) {
        let Some(d) = self.docs.iter_mut().find(|d| d.id == doc) else {
            return;
        };
        if let Some(c) = d.match_count.as_mut().filter(|_| d.version == version) {
            c.number = Some((sel, number));
        }
    }

    /// The counter next to the find field ("3 of 1,204", "? of 1,204…" while counting), with
    /// its tooltip; `None` when there is nothing to show.
    pub(crate) fn match_counter(&self) -> Option<(String, String)> {
        let d = self.docs.get(self.active)?;
        if self.search.query.pattern.is_empty() {
            return None;
        }
        let sel = d.selection();
        let on_found = d.last_found == Some(sel);
        let tip = tr("Matches of the pattern in the whole file, counted in the background");
        let text = |i: Option<u64>, n: String| {
            let i = i.map_or_else(|| "?".to_string(), fmt_count);
            trf("{i} of {n}", &[("i", &i), ("n", &n)])
        };
        if let Some(r) = self.complete_results() {
            let v = &r.lock().unwrap().matches;
            if v.is_empty() {
                return Some((tr("No matches").into(), tip.into()));
            }
            let i = v.partition_point(|&(s, _)| s < sel.0);
            let i = (on_found && v.get(i) == Some(&sel)).then_some(i as u64 + 1);
            return Some((text(i, fmt_count(v.len() as u64)), tip.into()));
        }
        let c = d.match_count.as_ref()?;
        let g = c.data.lock().unwrap();
        if g.done && g.total == 0 {
            return Some((tr("No matches").into(), tip.into()));
        }
        let mut n = fmt_count(g.total);
        if !g.done {
            n.push('…');
        }
        let i = match c.number {
            Some((at, i)) if on_found && at == sel => i,
            _ => None,
        };
        Some((text(i, n), tip.into()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bigtext::encoding::Codec;
    use std::io::Write;

    fn buf_with(data: &[u8]) -> (tempfile::NamedTempFile, TextBuf) {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        f.write_all(data).unwrap();
        f.flush().unwrap();
        let src =
            Arc::new(bigtext::file::Source::open(f.path(), bigtext::file::OpenMode::Auto).unwrap());
        let idx = bigtext::index::build_blocking(&src, Codec::utf8());
        let mut t = TextBuf::new(src, idx, Codec::utf8());
        t.blocking = true;
        (f, t)
    }

    fn matcher(pattern: &str, regex: bool) -> Matcher {
        let q = Query {
            pattern: pattern.into(),
            regex,
            ..Query::default()
        };
        Matcher::new(&q, Codec::utf8()).unwrap()
    }

    #[test]
    fn counts_and_numbers_every_match() {
        // Dense matches (a checkpoint every 4,096) and sparse ones (one every 4 MB).
        let mut data = Vec::new();
        for i in 0..10_000 {
            writeln!(data, "line {i} foo").unwrap();
        }
        data.extend(std::iter::repeat_n(b'.', 9 << 20));
        data.extend_from_slice(b"\nfoo at the end foo\n");
        let (_f, t) = buf_with(&data);
        let m = matcher("foo", false);
        let cd = Mutex::new(CountData::default());
        let cancel = CancelToken::new();
        let end = count(&t, &m, 0..t.len(), &cd, &cancel, || {});
        let g = cd.lock().unwrap();
        assert_eq!((end, g.done, g.total), (SearchEnd::Completed, true, 10_002));
        assert_eq!(
            g.marks[0],
            (data.windows(3).position(|w| w == b"foo").unwrap() as u64, 0)
        );
        assert!(g.marks.windows(2).all(|w| w[1].1 - w[0].1 <= MARK_EVERY));
        // Every match gets its number.
        let mut all = Vec::new();
        search::search_forward(&t, &m, 0..t.len(), &cancel, None, |s, e| {
            all.push((s, e));
            true
        });
        for (i, &sel) in all
            .iter()
            .enumerate()
            .step_by(97)
            .chain(all.iter().enumerate().rev().take(3))
        {
            assert_eq!(
                number_of(&t, &m, &g.marks, sel, &cancel),
                Some(i as u64 + 1),
                "{sel:?}"
            );
        }
        // Not a counted match: inside one, or before the first.
        let (s, e) = all[5];
        assert_eq!(number_of(&t, &m, &g.marks, (s + 1, e), &cancel), None);
        assert_eq!(number_of(&t, &m, &g.marks, (0, 3), &cancel), None);
    }

    #[test]
    fn a_match_inside_a_counted_one_has_no_number() {
        // "aa" in "aaaa": the counted matches are 0..2 and 2..4; Find next from 1 finds 1..3.
        let (_f, t) = buf_with(b"aaaa\n");
        let m = matcher("aa", false);
        let cd = Mutex::new(CountData::default());
        let cancel = CancelToken::new();
        count(&t, &m, 0..t.len(), &cd, &cancel, || {});
        let g = cd.lock().unwrap();
        assert_eq!(g.total, 2);
        assert_eq!(number_of(&t, &m, &g.marks, (2, 4), &cancel), Some(2));
        assert_eq!(number_of(&t, &m, &g.marks, (1, 3), &cancel), None);
        // A regex match keeps its whole length at the end of the range searched.
        let m = matcher("a+", true);
        let cd = Mutex::new(CountData::default());
        count(&t, &m, 0..t.len(), &cd, &cancel, || {});
        let g = cd.lock().unwrap();
        assert_eq!(number_of(&t, &m, &g.marks, (0, 4), &cancel), Some(1));
    }

    #[test]
    fn a_cancelled_count_is_not_done() {
        let (_f, t) = buf_with(b"foo foo foo\n");
        let m = matcher("foo", false);
        let cd = Mutex::new(CountData::default());
        let cancel = CancelToken::new();
        cancel.cancel();
        count(&t, &m, 0..t.len(), &cd, &cancel, || {});
        assert!(!cd.lock().unwrap().done);
    }
}