• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

rust-lang / annotate-snippets-rs / 16028937566

02 Jul 2025 03:11PM UTC coverage: 87.321% (-0.1%) from 87.43%
16028937566

Pull #242

github

web-flow
Merge 141206a6e into 128156280
Pull Request #242: feat: Add Level::no_name

2 of 2 new or added lines in 1 file covered. (100.0%)

2 existing lines in 1 file now uncovered.

1405 of 1609 relevant lines covered (87.32%)

4.66 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

84.88
/src/renderer/source_map.rs
1
use crate::renderer::{char_width, is_different, num_overlap, LineAnnotation, LineAnnotationType};
2
use crate::{Annotation, AnnotationKind, Patch};
3
use std::borrow::Cow;
4
use std::cmp::{max, min};
5
use std::ops::Range;
6

7
#[derive(Debug)]
8
pub(crate) struct SourceMap<'a> {
9
    lines: Vec<LineInfo<'a>>,
10
    pub(crate) source: &'a str,
11
}
12

13
impl<'a> SourceMap<'a> {
14
    pub(crate) fn new(source: &'a str, line_start: usize) -> Self {
6✔
15
        // Empty sources do have a "line", but it is empty, so we need to add
16
        // a line with an empty string to the source map.
17
        if source.is_empty() {
4✔
18
            return Self {
2✔
19
                lines: vec![LineInfo {
4✔
20
                    line: "",
×
21
                    line_index: line_start,
×
22
                    start_byte: 0,
×
23
                    end_byte: 0,
×
24
                    end_line_size: 0,
×
25
                }],
26
                source,
×
27
            };
28
        }
29

30
        let mut current_index = 0;
8✔
31

32
        let mut mapping = vec![];
4✔
33
        for (idx, (line, end_line)) in CursorLines::new(source).enumerate() {
22✔
34
            let line_length = line.len();
11✔
35
            let line_range = current_index..current_index + line_length;
5✔
36
            let end_line_size = end_line.len();
12✔
37

38
            mapping.push(LineInfo {
6✔
39
                line,
×
40
                line_index: line_start + idx,
6✔
41
                start_byte: line_range.start,
×
42
                end_byte: line_range.end + end_line_size,
6✔
43
                end_line_size,
×
44
            });
45

46
            current_index += line_length + end_line_size;
6✔
47
        }
48
        Self {
49
            lines: mapping,
50
            source,
51
        }
52
    }
53

54
    pub(crate) fn get_line(&self, idx: usize) -> Option<&'a str> {
4✔
55
        self.lines
4✔
56
            .iter()
57
            .find(|l| l.line_index == idx)
8✔
58
            .map(|info| info.line)
7✔
59
    }
60

61
    pub(crate) fn span_to_locations(&self, span: Range<usize>) -> (Loc, Loc) {
7✔
62
        let start_info = self
11✔
63
            .lines
×
64
            .iter()
65
            .find(|info| span.start >= info.start_byte && span.start < info.end_byte)
12✔
66
            .unwrap_or(self.lines.last().unwrap());
6✔
67
        let (mut start_char_pos, start_display_pos) = start_info.line
12✔
68
            [0..(span.start - start_info.start_byte).min(start_info.line.len())]
6✔
69
            .chars()
70
            .fold((0, 0), |(char_pos, byte_pos), c| {
12✔
71
                let display = char_width(c);
5✔
72
                (char_pos + 1, byte_pos + display)
5✔
73
            });
74
        // correct the char pos if we are highlighting the end of a line
75
        if (span.start - start_info.start_byte).saturating_sub(start_info.line.len()) > 0 {
13✔
76
            start_char_pos += 1;
2✔
77
        }
78
        let start = Loc {
79
            line: start_info.line_index,
6✔
80
            char: start_char_pos,
81
            display: start_display_pos,
82
            byte: span.start,
4✔
83
        };
84

85
        if span.start == span.end {
7✔
86
            return (start, start);
4✔
87
        }
88

89
        let end_info = self
11✔
90
            .lines
×
91
            .iter()
92
            .find(|info| span.end >= info.start_byte && span.end < info.end_byte)
16✔
93
            .unwrap_or(self.lines.last().unwrap());
6✔
94
        let (end_char_pos, end_display_pos) = end_info.line
9✔
95
            [0..(span.end - end_info.start_byte).min(end_info.line.len())]
9✔
96
            .chars()
97
            .fold((0, 0), |(char_pos, byte_pos), c| {
7✔
98
                let display = char_width(c);
4✔
99
                (char_pos + 1, byte_pos + display)
3✔
100
            });
101

102
        let mut end = Loc {
103
            line: end_info.line_index,
3✔
104
            char: end_char_pos,
105
            display: end_display_pos,
106
            byte: span.end,
3✔
107
        };
108
        if start.line != end.line && end.byte > end_info.end_byte - end_info.end_line_size {
11✔
109
            end.char += 1;
2✔
110
            end.display += 1;
4✔
111
        }
112

113
        (start, end)
3✔
114
    }
115

116
    pub(crate) fn span_to_snippet(&self, span: Range<usize>) -> Option<&str> {
3✔
117
        self.source.get(span)
3✔
118
    }
119

120
    pub(crate) fn span_to_lines(&self, span: Range<usize>) -> Vec<&LineInfo<'a>> {
3✔
121
        let mut lines = vec![];
3✔
122
        let start = span.start;
3✔
123
        let end = span.end;
3✔
124
        for line_info in &self.lines {
6✔
125
            if start >= line_info.end_byte {
4✔
126
                continue;
×
127
            }
128
            if end < line_info.start_byte {
3✔
129
                break;
×
130
            }
131
            lines.push(line_info);
3✔
132
        }
133
        lines
4✔
134
    }
135

136
    pub(crate) fn annotated_lines(
7✔
137
        &self,
138
        annotations: Vec<Annotation<'a>>,
139
        fold: bool,
140
    ) -> (usize, Vec<AnnotatedLineInfo<'a>>) {
141
        let source_len = self.source.len();
12✔
142
        if let Some(bigger) = annotations.iter().find_map(|x| {
12✔
143
            // Allow highlighting one past the last character in the source.
144
            if source_len + 1 < x.span.end {
12✔
145
                Some(&x.span)
1✔
146
            } else {
147
                None
6✔
148
            }
149
        }) {
150
            panic!("Annotation range `{bigger:?}` is beyond the end of buffer `{source_len}`")
2✔
151
        }
152

153
        let mut annotated_line_infos = self
11✔
154
            .lines
×
155
            .iter()
156
            .map(|info| AnnotatedLineInfo {
15✔
157
                line: info.line,
4✔
158
                line_index: info.line_index,
8✔
159
                annotations: vec![],
4✔
160
            })
161
            .collect::<Vec<_>>();
162
        let mut multiline_annotations = vec![];
4✔
163

164
        for Annotation {
12✔
165
            span,
8✔
166
            label,
4✔
167
            kind,
8✔
168
            highlight_source,
4✔
169
        } in annotations
16✔
170
        {
171
            let (lo, mut hi) = self.span_to_locations(span.clone());
12✔
172

173
            // Watch out for "empty spans". If we get a span like 6..6, we
174
            // want to just display a `^` at 6, so convert that to
175
            // 6..7. This is degenerate input, but it's best to degrade
176
            // gracefully -- and the parser likes to supply a span like
177
            // that for EOF, in particular.
178

179
            if lo.display == hi.display && lo.line == hi.line {
12✔
180
                hi.display += 1;
4✔
181
            }
182

183
            if lo.line == hi.line {
4✔
184
                let line_ann = LineAnnotation {
185
                    start: lo,
186
                    end: hi,
187
                    kind,
188
                    label,
189
                    annotation_type: LineAnnotationType::Singleline,
190
                    highlight_source,
191
                };
192
                self.add_annotation_to_file(&mut annotated_line_infos, lo.line, line_ann);
8✔
193
            } else {
194
                multiline_annotations.push(MultilineAnnotation {
8✔
195
                    depth: 1,
×
196
                    start: lo,
×
197
                    end: hi,
4✔
198
                    kind,
×
199
                    label,
4✔
200
                    overlaps_exactly: false,
×
201
                    highlight_source,
×
202
                });
203
            }
204
        }
205

206
        let mut primary_spans = vec![];
3✔
207

208
        // Find overlapping multiline annotations, put them at different depths
209
        multiline_annotations.sort_by_key(|ml| (ml.start.line, usize::MAX - ml.end.line));
12✔
210
        for ann in multiline_annotations.clone() {
9✔
211
            if ann.kind.is_primary() {
7✔
212
                primary_spans.push((ann.start, ann.end));
4✔
213
            }
214
            for a in &mut multiline_annotations {
8✔
215
                // Move all other multiline annotations overlapping with this one
216
                // one level to the right.
217
                if !ann.same_span(a)
9✔
218
                    && num_overlap(ann.start.line, ann.end.line, a.start.line, a.end.line, true)
4✔
219
                {
220
                    a.increase_depth();
2✔
221
                } else if ann.same_span(a) && &ann != a {
12✔
222
                    a.overlaps_exactly = true;
1✔
223
                } else {
224
                    if primary_spans
16✔
225
                        .iter()
226
                        .any(|(s, e)| a.start == *s && a.end == *e)
12✔
227
                    {
228
                        a.kind = AnnotationKind::Primary;
4✔
229
                    }
230
                    break;
×
231
                }
232
            }
233
        }
234

235
        let mut max_depth = 0; // max overlapping multiline spans
4✔
236
        for ann in &multiline_annotations {
7✔
237
            max_depth = max(max_depth, ann.depth);
6✔
238
        }
239
        // Change order of multispan depth to minimize the number of overlaps in the ASCII art.
240
        for a in &mut multiline_annotations {
7✔
241
            a.depth = max_depth - a.depth + 1;
6✔
242
        }
243
        for ann in multiline_annotations {
8✔
244
            let mut end_ann = ann.as_end();
7✔
245
            if ann.overlaps_exactly {
5✔
246
                end_ann.annotation_type = LineAnnotationType::Singleline;
1✔
247
            } else {
248
                // avoid output like
249
                //
250
                //  |        foo(
251
                //  |   _____^
252
                //  |  |_____|
253
                //  | ||         bar,
254
                //  | ||     );
255
                //  | ||      ^
256
                //  | ||______|
257
                //  |  |______foo
258
                //  |         baz
259
                //
260
                // and instead get
261
                //
262
                //  |       foo(
263
                //  |  _____^
264
                //  | |         bar,
265
                //  | |     );
266
                //  | |      ^
267
                //  | |      |
268
                //  | |______foo
269
                //  |        baz
270
                self.add_annotation_to_file(
4✔
271
                    &mut annotated_line_infos,
×
272
                    ann.start.line,
4✔
273
                    ann.as_start(),
4✔
274
                );
275
                // 4 is the minimum vertical length of a multiline span when presented: two lines
276
                // of code and two lines of underline. This is not true for the special case where
277
                // the beginning doesn't have an underline, but the current logic seems to be
278
                // working correctly.
279
                let middle = min(ann.start.line + 4, ann.end.line);
4✔
280
                // We'll show up to 4 lines past the beginning of the multispan start.
281
                // We will *not* include the tail of lines that are only whitespace, a comment or
282
                // a bare delimiter.
283
                let filter = |s: &str| {
3✔
284
                    let s = s.trim();
3✔
285
                    // Consider comments as empty, but don't consider docstrings to be empty.
286
                    !(s.starts_with("//") && !(s.starts_with("///") || s.starts_with("//!")))
6✔
287
                        // Consider lines with nothing but whitespace, a single delimiter as empty.
288
                        && !["", "{", "}", "(", ")", "[", "]"].contains(&s)
3✔
289
                };
290
                let until = (ann.start.line..middle)
7✔
291
                    .rev()
292
                    .filter_map(|line| self.get_line(line).map(|s| (line + 1, s)))
14✔
293
                    .find(|(_, s)| filter(s))
6✔
294
                    .map_or(ann.start.line, |(line, _)| line);
6✔
295
                for line in ann.start.line + 1..until {
3✔
296
                    // Every `|` that joins the beginning of the span (`___^`) to the end (`|__^`).
297
                    self.add_annotation_to_file(&mut annotated_line_infos, line, ann.as_line());
6✔
298
                }
299
                let line_end = ann.end.line - 1;
3✔
300
                let end_is_empty = self.get_line(line_end).map_or(false, |s| !filter(s));
12✔
301
                if middle < line_end && !end_is_empty {
6✔
302
                    self.add_annotation_to_file(&mut annotated_line_infos, line_end, ann.as_line());
2✔
303
                }
304
            }
305
            self.add_annotation_to_file(&mut annotated_line_infos, end_ann.end.line, end_ann);
3✔
306
        }
307

308
        if fold {
4✔
309
            annotated_line_infos.retain(|l| !l.annotations.is_empty());
12✔
310
        }
311

312
        (max_depth, annotated_line_infos)
4✔
313
    }
314

315
    fn add_annotation_to_file(
4✔
316
        &self,
317
        annotated_line_infos: &mut Vec<AnnotatedLineInfo<'a>>,
318
        line_index: usize,
319
        line_ann: LineAnnotation<'a>,
320
    ) {
321
        if let Some(line_info) = annotated_line_infos
8✔
322
            .iter_mut()
323
            .find(|line_info| line_info.line_index == line_index)
8✔
324
        {
325
            line_info.annotations.push(line_ann);
8✔
326
        } else {
327
            let info = self
×
328
                .lines
×
329
                .iter()
330
                .find(|l| l.line_index == line_index)
×
331
                .unwrap();
332
            annotated_line_infos.push(AnnotatedLineInfo {
×
333
                line: info.line,
×
334
                line_index,
×
335
                annotations: vec![line_ann],
×
336
            });
337
            annotated_line_infos.sort_by_key(|l| l.line_index);
×
338
        }
339
    }
340

341
    pub(crate) fn splice_lines<'b>(
4✔
342
        &'b self,
343
        mut patches: Vec<Patch<'b>>,
344
    ) -> Vec<(String, Vec<Patch<'b>>, Vec<Vec<SubstitutionHighlight>>)> {
345
        fn push_trailing(
6✔
346
            buf: &mut String,
347
            line_opt: Option<&str>,
348
            lo: &Loc,
349
            hi_opt: Option<&Loc>,
350
        ) -> usize {
351
            let mut line_count = 0;
6✔
352
            // Convert CharPos to Usize, as CharPose is character offset
353
            // Extract low index and high index
354
            let (lo, hi_opt) = (lo.char, hi_opt.map(|hi| hi.char));
15✔
355
            if let Some(line) = line_opt {
5✔
356
                if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
18✔
357
                    // Get high index while account for rare unicode and emoji with char_indices
358
                    let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
17✔
359
                    match hi_opt {
4✔
360
                        // If high index exist, take string from low to high index
361
                        Some(hi) if hi > lo => {
5✔
362
                            // count how many '\n' exist
363
                            line_count = line[lo..hi].matches('\n').count();
2✔
364
                            buf.push_str(&line[lo..hi]);
3✔
365
                        }
366
                        Some(_) => (),
×
367
                        // If high index absence, take string from low index till end string.len
368
                        None => {
×
369
                            // count how many '\n' exist
370
                            line_count = line[lo..].matches('\n').count();
5✔
371
                            buf.push_str(&line[lo..]);
5✔
372
                        }
373
                    }
374
                }
375
                // If high index is None
376
                if hi_opt.is_none() {
3✔
377
                    buf.push('\n');
6✔
378
                }
379
            }
380
            line_count
4✔
381
        }
382
        // Assumption: all spans are in the same file, and all spans
383
        // are disjoint. Sort in ascending order.
384
        patches.sort_by_key(|p| p.span.start);
12✔
385

386
        // Find the bounding span.
387
        let Some(lo) = patches.iter().map(|p| p.span.start).min() else {
12✔
388
            return Vec::new();
×
389
        };
390
        let Some(hi) = patches.iter().map(|p| p.span.end).max() else {
15✔
391
            return Vec::new();
×
392
        };
393

394
        let lines = self.span_to_lines(lo..hi);
3✔
395

396
        let mut highlights = vec![];
3✔
397
        // To build up the result, we do this for each span:
398
        // - push the line segment trailing the previous span
399
        //   (at the beginning a "phantom" span pointing at the start of the line)
400
        // - push lines between the previous and current span (if any)
401
        // - if the previous and current span are not on the same line
402
        //   push the line segment leading up to the current span
403
        // - splice in the span substitution
404
        //
405
        // Finally push the trailing line segment of the last span
406
        let (mut prev_hi, _) = self.span_to_locations(lo..hi);
8✔
407
        prev_hi.char = 0;
4✔
408
        let mut prev_line = lines.first().map(|line| line.line);
11✔
409
        let mut buf = String::new();
4✔
410

411
        let mut line_highlight = vec![];
4✔
412
        // We need to keep track of the difference between the existing code and the added
413
        // or deleted code in order to point at the correct column *after* substitution.
414
        let mut acc = 0;
4✔
415
        for part in &mut patches {
8✔
416
            // If this is a replacement of, e.g. `"a"` into `"ab"`, adjust the
417
            // suggestion and snippet to look as if we just suggested to add
418
            // `"b"`, which is typically much easier for the user to understand.
419
            part.trim_trivial_replacements(self);
4✔
420
            let (cur_lo, cur_hi) = self.span_to_locations(part.span.clone());
4✔
421
            if prev_hi.line == cur_lo.line {
4✔
422
                let mut count = push_trailing(&mut buf, prev_line, &prev_hi, Some(&cur_lo));
7✔
423
                while count > 0 {
4✔
424
                    highlights.push(std::mem::take(&mut line_highlight));
×
425
                    acc = 0;
×
426
                    count -= 1;
×
427
                }
428
            } else {
429
                acc = 0;
1✔
430
                highlights.push(std::mem::take(&mut line_highlight));
2✔
431
                let mut count = push_trailing(&mut buf, prev_line, &prev_hi, None);
1✔
432
                while count > 0 {
1✔
433
                    highlights.push(std::mem::take(&mut line_highlight));
×
434
                    count -= 1;
×
435
                }
436
                // push lines between the previous and current span (if any)
437
                for idx in prev_hi.line + 1..(cur_lo.line) {
2✔
438
                    if let Some(line) = self.get_line(idx) {
2✔
439
                        buf.push_str(line.as_ref());
1✔
440
                        buf.push('\n');
1✔
441
                        highlights.push(std::mem::take(&mut line_highlight));
1✔
442
                    }
443
                }
444
                if let Some(cur_line) = self.get_line(cur_lo.line) {
1✔
445
                    let end = match cur_line.char_indices().nth(cur_lo.char) {
2✔
446
                        Some((i, _)) => i,
1✔
447
                        None => cur_line.len(),
×
448
                    };
449
                    buf.push_str(&cur_line[..end]);
1✔
450
                }
451
            }
452
            // Add a whole line highlight per line in the snippet.
453
            let len: isize = part
12✔
454
                .replacement
×
455
                .split('\n')
456
                .next()
457
                .unwrap_or(&part.replacement)
4✔
458
                .chars()
459
                .map(|c| match c {
7✔
460
                    '\t' => 4,
×
461
                    _ => 1,
3✔
462
                })
463
                .sum();
464
            if !is_different(self, &part.replacement, part.span.clone()) {
4✔
465
                // Account for cases where we are suggesting the same code that's already
466
                // there. This shouldn't happen often, but in some cases for multipart
467
                // suggestions it's much easier to handle it here than in the origin.
468
            } else {
469
                line_highlight.push(SubstitutionHighlight {
8✔
470
                    start: (cur_lo.char as isize + acc) as usize,
4✔
471
                    end: (cur_lo.char as isize + acc + len) as usize,
8✔
472
                });
473
            }
474
            buf.push_str(&part.replacement);
8✔
475
            // Account for the difference between the width of the current code and the
476
            // snippet being suggested, so that the *later* suggestions are correctly
477
            // aligned on the screen. Note that cur_hi and cur_lo can be on different
478
            // lines, so cur_hi.col can be smaller than cur_lo.col
479
            acc += len - (cur_hi.char as isize - cur_lo.char as isize);
4✔
480
            prev_hi = cur_hi;
4✔
481
            prev_line = self.get_line(prev_hi.line);
8✔
482
            for line in part.replacement.split('\n').skip(1) {
4✔
483
                acc = 0;
1✔
484
                highlights.push(std::mem::take(&mut line_highlight));
1✔
485
                let end: usize = line
1✔
486
                    .chars()
487
                    .map(|c| match c {
2✔
488
                        '\t' => 4,
×
489
                        _ => 1,
1✔
490
                    })
491
                    .sum();
492
                line_highlight.push(SubstitutionHighlight { start: 0, end });
1✔
493
            }
494
        }
495
        highlights.push(std::mem::take(&mut line_highlight));
4✔
496
        // if the replacement already ends with a newline, don't print the next line
497
        if !buf.ends_with('\n') {
4✔
498
            push_trailing(&mut buf, prev_line, &prev_hi, None);
9✔
499
        }
500
        // remove trailing newlines
501
        while buf.ends_with('\n') {
8✔
502
            buf.pop();
8✔
503
        }
504
        if highlights.iter().all(|parts| parts.is_empty()) {
16✔
505
            Vec::new()
×
506
        } else {
507
            vec![(buf, patches, highlights)]
8✔
508
        }
509
    }
510
}
511

512
#[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
513
pub(crate) struct MultilineAnnotation<'a> {
514
    pub depth: usize,
515
    pub start: Loc,
516
    pub end: Loc,
517
    pub kind: AnnotationKind,
518
    pub label: Option<Cow<'a, str>>,
519
    pub overlaps_exactly: bool,
520
    pub highlight_source: bool,
521
}
522

523
impl<'a> MultilineAnnotation<'a> {
524
    pub(crate) fn increase_depth(&mut self) {
2✔
525
        self.depth += 1;
2✔
526
    }
527

528
    /// Compare two `MultilineAnnotation`s considering only the `Span` they cover.
529
    pub(crate) fn same_span(&self, other: &MultilineAnnotation<'_>) -> bool {
4✔
530
        self.start == other.start && self.end == other.end
4✔
531
    }
532

533
    pub(crate) fn as_start(&self) -> LineAnnotation<'a> {
4✔
534
        LineAnnotation {
535
            start: self.start,
4✔
536
            end: Loc {
4✔
537
                line: self.start.line,
538
                char: self.start.char + 1,
539
                display: self.start.display + 1,
540
                byte: self.start.byte + 1,
541
            },
542
            kind: self.kind,
4✔
543
            label: None,
544
            annotation_type: LineAnnotationType::MultilineStart(self.depth),
4✔
545
            highlight_source: self.highlight_source,
4✔
546
        }
547
    }
548

549
    pub(crate) fn as_end(&self) -> LineAnnotation<'a> {
3✔
550
        LineAnnotation {
551
            start: Loc {
4✔
552
                line: self.end.line,
553
                char: self.end.char.saturating_sub(1),
554
                display: self.end.display.saturating_sub(1),
555
                byte: self.end.byte.saturating_sub(1),
556
            },
557
            end: self.end,
4✔
558
            kind: self.kind,
4✔
559
            label: self.label.clone(),
4✔
560
            annotation_type: LineAnnotationType::MultilineEnd(self.depth),
4✔
561
            highlight_source: self.highlight_source,
4✔
562
        }
563
    }
564

565
    pub(crate) fn as_line(&self) -> LineAnnotation<'a> {
3✔
566
        LineAnnotation {
567
            start: Loc::default(),
3✔
568
            end: Loc::default(),
3✔
569
            kind: self.kind,
3✔
570
            label: None,
571
            annotation_type: LineAnnotationType::MultilineLine(self.depth),
3✔
572
            highlight_source: self.highlight_source,
3✔
573
        }
574
    }
575
}
576

577
#[derive(Debug)]
578
pub(crate) struct LineInfo<'a> {
579
    pub(crate) line: &'a str,
580
    pub(crate) line_index: usize,
581
    pub(crate) start_byte: usize,
582
    pub(crate) end_byte: usize,
583
    end_line_size: usize,
584
}
585

586
#[derive(Debug)]
587
pub(crate) struct AnnotatedLineInfo<'a> {
588
    pub(crate) line: &'a str,
589
    pub(crate) line_index: usize,
590
    pub(crate) annotations: Vec<LineAnnotation<'a>>,
591
}
592

593
/// A source code location used for error reporting.
594
#[derive(Clone, Copy, Debug, Default, PartialOrd, Ord, PartialEq, Eq)]
595
pub(crate) struct Loc {
596
    /// The (1-based) line number.
597
    pub(crate) line: usize,
598
    /// The (0-based) column offset.
599
    pub(crate) char: usize,
600
    /// The (0-based) column offset when displayed.
601
    pub(crate) display: usize,
602
    /// The (0-based) byte offset.
603
    pub(crate) byte: usize,
604
}
605

606
struct CursorLines<'a>(&'a str);
607

608
impl CursorLines<'_> {
609
    fn new(src: &str) -> CursorLines<'_> {
4✔
610
        CursorLines(src)
611
    }
612
}
613

614
#[derive(Copy, Clone, Debug, PartialEq)]
615
enum EndLine {
616
    Eof,
617
    Lf,
618
    Crlf,
619
}
620

621
impl EndLine {
622
    /// The number of characters this line ending occupies in bytes.
623
    pub(crate) fn len(self) -> usize {
5✔
624
        match self {
7✔
625
            EndLine::Eof => 0,
626
            EndLine::Lf => 1,
627
            EndLine::Crlf => 2,
628
        }
629
    }
630
}
631

632
impl<'a> Iterator for CursorLines<'a> {
633
    type Item = (&'a str, EndLine);
634

635
    fn next(&mut self) -> Option<Self::Item> {
4✔
636
        if self.0.is_empty() {
8✔
637
            None
6✔
638
        } else {
639
            self.0
3✔
640
                .find('\n')
641
                .map(|x| {
7✔
642
                    let ret = if 0 < x {
6✔
643
                        if self.0.as_bytes()[x - 1] == b'\r' {
14✔
644
                            (&self.0[..x - 1], EndLine::Crlf)
4✔
645
                        } else {
646
                            (&self.0[..x], EndLine::Lf)
4✔
647
                        }
648
                    } else {
649
                        ("", EndLine::Lf)
3✔
650
                    };
651
                    self.0 = &self.0[x + 1..];
10✔
652
                    ret
6✔
653
                })
654
                .or_else(|| {
5✔
655
                    let ret = Some((self.0, EndLine::Eof));
5✔
656
                    self.0 = "";
5✔
657
                    ret
×
658
                })
659
        }
660
    }
661
}
662

663
/// Used to translate between `Span`s and byte positions within a single output line in highlighted
664
/// code of structured suggestions.
665
#[derive(Debug, Clone, Copy)]
666
pub(crate) struct SubstitutionHighlight {
667
    pub(crate) start: usize,
668
    pub(crate) end: usize,
669
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc