diff: Add index for file row spans

c7734caf5a4d2e7924e785cb81546a50f510bb81
many-files   757 -> 7575 fps
  session      665 -> 8263 fps
  warm-scroll  4277 -> 10044 fps
Alexis Sellier committed ago 1 parent 336c12d9
crates/diff/benches/render.rs +5 -1
366 366
        Err(error) => {
367 367
            eprintln!("failed to decode generated benchmark diff: {error}");
368 368
            std::process::exit(1);
369 369
        }
370 370
    };
371 -
    let rows = DiffViewer::new(document.clone(), DiffOptions::default()).row_count();
371 +
    let rows = rustik_tui::Widget::size(
372 +
        &DiffViewer::new(document.clone(), DiffOptions::default()),
373 +
        Constraint::UNBOUNDED,
374 +
    )
375 +
    .rows;
372 376
    let mut rates = Vec::with_capacity(args.runs);
373 377
    let mut checksum = rows;
374 378
375 379
    for run in 0..args.runs {
376 380
        let (run_elapsed, run_checksum) = run_once(workload, document.clone(), frames);
src/file_{file:04}.rs\n" +0 -0
crates/diff/src/bin/rustik-diff.rs +1 -2
147 147
148 148
        options.file_tree = FileTreeMode::Auto;
149 149
        options.file_tree_root = root;
150 150
    } else {
151 151
        let mut viewer = DiffViewer::new(document, options);
152 -
        let rows = viewer.row_count().min(STATIC_MAX_ROWS);
153 -
        let constraints = tui::Constraint::max(tui::Size::new(STATIC_COLS, rows));
152 +
        let constraints = tui::Constraint::max(tui::Size::new(STATIC_COLS, STATIC_MAX_ROWS));
154 153
155 154
        tui_termion::term::print_constrained(&mut viewer, constraints)?;
156 155
        return Ok(());
157 156
    }
158 157
    let backend = tui_termion::term::screen()?;
a.rs\x1b[m +0 -0
crates/diff/src/renderer.rs +97 -51
84 84
    pub pane: DiffPane,
85 85
    /// File selection shown in the main diff pane.
86 86
    pub file_selection: FileSelection,
87 87
}
88 88
89 +
impl DiffState {
90 +
    /// Returns whether replacing this state with `next` invalidates cached row positions.
91 +
    fn invalidates_index(&self, next: &Self) -> bool {
92 +
        self.collapsed_files != next.collapsed_files || self.file_selection != next.file_selection
93 +
    }
94 +
}
95 +
89 96
/// Focus target inside a diff document.
90 97
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
91 98
pub enum DiffFocus {
92 99
    /// Focus a file header.
93 100
    File(FileId),
202 209
    word_diffs: BTreeMap<HunkId, word::WordChanges>,
203 210
    /// Rendered commit-preamble rows for the most recent body width.
204 211
    preamble: Vec<Line>,
205 212
    /// File-tree pane state and model.
206 213
    file_tree: tree::FileTreeViewer,
214 +
    /// Cached rendered row positions for visible files.
215 +
    index: RowIndex,
216 +
}
217 +
218 +
/// Cached rendered row positions for the current document visibility state.
219 +
///
220 +
/// Visible files tile the content region contiguously, so each file is stored
221 +
/// by its first rendered row only; its last row is the next file's start (or
222 +
/// [`RowIndex::rows`] for the final file).
223 +
#[derive(Clone, Debug, Default)]
224 +
struct RowIndex {
225 +
    /// Visible files in rendered order, each at its first rendered row.
226 +
    files: Vec<IndexedFileRows>,
227 +
    /// Total number of rendered rows.
228 +
    rows: usize,
229 +
}
230 +
231 +
/// The rendered position of one visible file.
232 +
#[derive(Clone, Copy, Debug)]
233 +
struct IndexedFileRows {
234 +
    /// Index into the document file list.
235 +
    file_index: usize,
236 +
    /// First rendered row occupied by the file.
237 +
    start: usize,
207 238
}
208 239
209 240
/// One rendered row before viewport projection.
210 241
#[derive(Clone, Debug)]
211 242
struct RenderRow {
325 356
    pub fn new(document: DiffDocument, options: DiffOptions) -> Self {
326 357
        let preamble = Self::preamble(document.commit.as_ref(), MIN_RENDER_COLS);
327 358
        let file_tree = tree::FileTreeViewer::new(&document, options.file_tree_root.clone());
328 359
        let state = DiffState::default();
329 360
330 -
        Self {
361 +
        let mut viewer = Self {
331 362
            document,
332 363
            options,
333 364
            state,
334 365
            highlights: BTreeMap::new(),
335 366
            pending_highlights: BTreeSet::new(),
336 367
            word_diffs: BTreeMap::new(),
337 368
            preamble,
338 369
            file_tree,
339 -
        }
370 +
            index: RowIndex::default(),
371 +
        };
372 +
        viewer.rebuild_index();
373 +
        viewer
340 374
    }
341 375
342 376
    /// Returns the viewed document.
343 377
    pub const fn document(&self) -> &DiffDocument {
344 378
        &self.document
349 383
        &self.state
350 384
    }
351 385
352 386
    /// Replaces the viewer state.
353 387
    pub fn set_state(&mut self, state: DiffState) {
388 +
        let rebuild = self.state.invalidates_index(&state);
354 389
        self.state = state;
390 +
391 +
        if rebuild {
392 +
            self.rebuild_index();
393 +
        }
355 394
    }
356 395
357 396
    /// Sets the first visible rendered row.
358 397
    pub fn set_scroll(&mut self, scroll: usize) {
359 398
        self.state.scroll = scroll;
365 404
    }
366 405
367 406
    /// Sets the collapsed file sections.
368 407
    pub fn set_collapsed_files(&mut self, collapsed_files: BTreeSet<FileId>) {
369 408
        self.state.collapsed_files = collapsed_files;
409 +
        self.rebuild_index();
370 410
    }
371 411
372 412
    /// Renders the current frame into `buf`.
373 413
    pub fn render(&mut self, area: Rect, buf: &mut Buffer) {
374 414
        if area.is_empty() {
425 465
    /// Renders the main diff pane into `buf`.
426 466
    fn render_diff(&mut self, area: Rect, buf: &mut Buffer) {
427 467
        let body_cols = ScrollView::body_cols(area);
428 468
        // Rebuild preamble for the available body width so line wrapping matches
429 469
        // current viewport size.
470 +
        let preamble_rows = self.preamble.len();
430 471
        self.preamble = Self::preamble(self.document.commit.as_ref(), body_cols);
431 472
473 +
        if self.preamble.len() != preamble_rows {
474 +
            self.rebuild_index();
475 +
        }
432 476
        let scroll = self.state.scroll;
433 -
        let content_rows = self.row_count();
434 477
        let sticky = self.sticky_rows(scroll, area.rows, body_cols);
435 478
        // Body offset skips sticky rows so the main diff starts below the fixed
436 479
        // header strip.
437 480
        let body_offset = scroll.saturating_add(sticky.len().min(area.rows));
438 481
439 -
        ScrollView::virtualized(content_rows, body_offset, |row, cols| {
482 +
        ScrollView::virtualized(self.index.rows, body_offset, |row, cols| {
440 483
            self.render_row(row, cols)
441 484
                .map(|row| row.line)
442 485
                .unwrap_or_default()
443 486
        })
444 487
        .sticky(sticky)
445 -
        .scrollbar_view(View::new(scroll, content_rows, area.rows))
488 +
        .scrollbar_view(View::new(scroll, self.index.rows, area.rows))
446 489
        .scrollbar(Self::scrollbar_style())
447 490
        .render(area, buf);
448 491
    }
449 492
450 493
    /// Applies an action to the viewer state.
453 496
        let layout = self.layout(area);
454 497
        let diff = layout.diff;
455 498
456 499
        match action {
457 500
            DiffAction::Scroll(scroll) => {
458 -
                let content_rows = self.row_count();
459 501
                let mut viewport = Viewport::from_offset(self.state.scroll);
460 -
                viewport.scroll(scroll, content_rows, diff.rows);
502 +
                viewport.scroll(scroll, self.index.rows, diff.rows);
461 503
                self.state.scroll = viewport.offset;
462 504
            }
463 505
            DiffAction::Resize => {
464 -
                let content_rows = self.row_count();
465 506
                let mut viewport = Viewport::from_offset(self.state.scroll);
466 -
                viewport.clamp(content_rows, diff.rows);
507 +
                viewport.clamp(self.index.rows, diff.rows);
467 508
                self.state.scroll = viewport.offset;
468 509
                if layout.tree.is_none() {
469 510
                    self.state.pane = DiffPane::Main;
470 511
                }
471 512
            }
516 557
            DiffAction::ExpandFileTreeFolder => {
517 558
                self.file_tree.expand_folder();
518 559
            }
519 560
        }
520 561
521 -
        if self.state.collapsed_files != before.collapsed_files
522 -
            || self.state.file_selection != before.file_selection
523 -
        {
524 -
            self.state.scroll = View::new(self.state.scroll, self.row_count(), diff.rows).offset;
562 +
        if before.invalidates_index(&self.state) {
563 +
            self.rebuild_index();
564 +
            self.state.scroll = View::new(self.state.scroll, self.index.rows, diff.rows).offset;
525 565
        }
526 566
        if self.state == before {
527 567
            ViewChange::Unchanged
528 568
        } else {
529 569
            ViewChange::Changed
638 678
639 679
    /// Returns highlight requests for visible source rows plus configured lookahead.
640 680
    pub fn highlight_requests(&mut self, area: Rect) -> Vec<HighlightRequest> {
641 681
        let diff = self.layout(area).diff;
642 682
        let take = diff.rows.saturating_add(self.options.highlight_lookahead);
643 -
        let view = View::new(self.state.scroll, self.row_count(), diff.rows);
683 +
        let view = View::new(self.state.scroll, self.index.rows, diff.rows);
644 684
        let start = view
645 685
            .offset
646 686
            .saturating_add(self.sticky_row_count(view.offset, diff.rows));
647 687
        let mut requests = Vec::new();
648 688
716 756
            changed = true;
717 757
        }
718 758
        changed
719 759
    }
720 760
721 -
    /// Returns the content row count without building render rows.
722 -
    pub fn row_count(&self) -> usize {
723 -
        self.preamble.len()
724 -
            + self
725 -
                .document
726 -
                .files
727 -
                .iter()
728 -
                .filter(|file| self.file_visible(file.id))
729 -
                .map(|file| self.file_rows(file))
730 -
                .sum::<usize>()
731 -
    }
732 -
733 761
    /// Returns whether `file` is shown in the main diff pane.
734 762
    fn file_visible(&self, file: FileId) -> bool {
735 763
        self.state.file_selection.contains(file)
736 764
    }
737 765
847 875
        None
848 876
    }
849 877
850 878
    /// Returns the file location for a global rendered row.
851 879
    fn file_row_location(&self, row: usize) -> Option<FileRowLocation<'_>> {
852 -
        let mut start = self.preamble.len();
853 -
        for file in &self.document.files {
880 +
        let files = &self.index.files;
881 +
        // The file containing `row` is the last one starting at or before it.
882 +
        let index = files
883 +
            .partition_point(|indexed| indexed.start <= row)
884 +
            .checked_sub(1)?;
885 +
        let indexed = files[index];
886 +
        let end = files
887 +
            .get(index + 1)
888 +
            .map_or(self.index.rows, |next| next.start);
889 +
        if row >= end {
890 +
            return None;
891 +
        }
892 +
        let file = self.document.files.get(indexed.file_index)?;
893 +
894 +
        Some(FileRowLocation {
895 +
            file,
896 +
            start: indexed.start,
897 +
            end,
898 +
            local: row - indexed.start,
899 +
        })
900 +
    }
901 +
902 +
    /// Rebuilds cached row positions for the current document visibility state.
903 +
    fn rebuild_index(&mut self) {
904 +
        let mut rows = self.preamble.len();
905 +
        let mut files = Vec::new();
906 +
907 +
        for (file_index, file) in self.document.files.iter().enumerate() {
854 908
            if !self.file_visible(file.id) {
855 909
                continue;
856 910
            }
857 -
            let end = start + self.file_rows(file);
858 -
            if (start..end).contains(&row) {
859 -
                return Some(FileRowLocation {
860 -
                    file,
861 -
                    start,
862 -
                    end,
863 -
                    local: row - start,
864 -
                });
865 -
            }
866 -
            start = end;
911 +
            files.push(IndexedFileRows {
912 +
                file_index,
913 +
                start: rows,
914 +
            });
915 +
            rows += self.file_rows(file);
867 916
        }
868 -
        None
917 +
        self.index = RowIndex { files, rows };
869 918
    }
870 919
871 920
    /// Lays out the commit preamble for the given body width.
872 921
    fn preamble(commit: Option<&Commit>, cols: usize) -> Vec<Line> {
873 922
        let Some(commit) = commit else {
987 1036
            .map_or(0, |_| STICKY_HEADER_ROWS.min(visible_rows))
988 1037
    }
989 1038
990 1039
    /// Returns the source row for the sticky header at the current offset.
991 1040
    fn sticky_start(&self, scroll: usize, visible_rows: usize) -> Option<usize> {
992 -
        let rows = self.row_count();
993 -
        let scroll = scroll.min(rows.saturating_sub(visible_rows));
1041 +
        let scroll = scroll.min(self.index.rows.saturating_sub(visible_rows));
994 1042
        if scroll == 0 {
995 1043
            return None;
996 1044
        }
997 1045
        let location = self.file_row_location(scroll)?;
998 1046
        if scroll <= location.start {
1024 1072
            return;
1025 1073
        };
1026 1074
1027 1075
        self.state.focus = Some(target.focus);
1028 1076
        if filter == FocusFilter::File {
1029 -
            self.state.scroll = View::new(target.row, self.row_count(), visible_rows).offset;
1077 +
            self.state.scroll = View::new(target.row, self.index.rows, visible_rows).offset;
1030 1078
            return;
1031 1079
        }
1032 1080
1033 1081
        let mut viewport = Viewport::from_offset(self.state.scroll);
1034 1082
        let margin = visible_rows / 4;
1035 1083
        viewport.scroll_to_row(
1036 1084
            target.row,
1037 -
            self.row_count(),
1085 +
            self.index.rows,
1038 1086
            visible_rows,
1039 1087
            Placement::Margin {
1040 1088
                before: margin.max(self.sticky_row_count(self.state.scroll, visible_rows)),
1041 1089
                after: margin,
1042 1090
            },
1045 1093
    }
1046 1094
1047 1095
    /// Returns focusable targets in rendered row order.
1048 1096
    fn focus_targets(&self, filter: FocusFilter) -> Vec<FocusTarget> {
1049 1097
        let mut targets = Vec::new();
1050 -
        let mut row = self.preamble.len();
1051 1098
1052 -
        for file in &self.document.files {
1053 -
            if !self.file_visible(file.id) {
1099 +
        for indexed in &self.index.files {
1100 +
            let Some(file) = self.document.files.get(indexed.file_index) else {
1054 1101
                continue;
1055 -
            }
1102 +
            };
1056 1103
            let collapsed = self.state.collapsed_files.contains(&file.id);
1057 1104
            if filter == FocusFilter::File {
1058 1105
                targets.push(FocusTarget {
1059 1106
                    focus: DiffFocus::File(file.id),
1060 -
                    row,
1107 +
                    row: indexed.start,
1061 1108
                });
1062 1109
            }
1063 1110
            if filter == FocusFilter::Hunk {
1064 1111
                for (hunk, local) in file.hunk_body_rows(collapsed) {
1065 1112
                    targets.push(FocusTarget {
1066 1113
                        focus: DiffFocus::Hunk(hunk.id),
1067 -
                        row: row + local,
1114 +
                        row: indexed.start + local,
1068 1115
                    });
1069 1116
                }
1070 1117
            }
1071 -
            row += file.rendered_rows(collapsed);
1072 1118
        }
1073 1119
        targets
1074 1120
    }
1075 1121
1076 1122
    /// Toggles the file containing the current focus.
1276 1322
        let cols = if parent.max.cols == usize::MAX {
1277 1323
            MIN_RENDER_COLS
1278 1324
        } else {
1279 1325
            parent.max.cols
1280 1326
        };
1281 -
        Size::new(cols, self.row_count()).constrain(parent)
1327 +
        Size::new(cols, self.index.rows).constrain(parent)
1282 1328
    }
1283 1329
1284 1330
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
1285 1331
        DiffViewer::render(self, area, buf);
1286 1332
    }
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
src/a.rs +0 -0
src/b.rs +0 -0
README.md +0 -0
a.rs +0 -0
crates/diff/src/renderer/tree.rs +0 -0
a.rs +0 -0
b.rs +0 -0