rich_err/
span.rs

1/// A range of byte indices in a source file.
2pub type Span = core::ops::Range<usize>;
3
4/// Combines two spans into one span.
5///
6/// The resulting span will contain all indices in the original spans, possibly with some additional
7/// indices included between them.
8///
9/// # Examples
10///
11/// ```
12/// # use rich_err::span::combine_spans;
13/// assert_eq!(combine_spans([69..420, 42..100]), 42..420);
14/// assert_eq!(combine_spans([21..32, 27..84]), 21..84);
15/// assert_eq!(combine_spans([0..100, 300..500]), 0..500);
16/// assert_eq!(combine_spans([0..100, 10..20]), 0..100);
17/// ```
18pub const fn combine_spans(spans: [Span; 2]) -> Span {
19    Span {
20        start: usize_min(spans[0].start, spans[1].start),
21        end: usize_max(spans[0].end, spans[1].end),
22    }
23}
24
25/// Combines the consumed span with the consumer.
26///
27/// The consumer will then contain all the indices it used to along with all those in the consumed
28/// span (possibly plus some extras to make it one continuous span).
29///
30/// # Examples
31///
32/// ```
33/// # use rich_err::span::consume_span;
34/// let mut total_span = 69..420;
35/// consume_span(&mut total_span, 42..100);
36/// assert_eq!(total_span, 42..420);
37/// consume_span(&mut total_span, 420..696);
38/// assert_eq!(total_span, 42..696);
39/// consume_span(&mut total_span, 700..1000);
40/// assert_eq!(total_span, 42..1000);
41/// consume_span(&mut total_span, 100..200); // This shouldn't do anything.
42/// assert_eq!(total_span, 42..1000);
43/// ```
44pub const fn consume_span(consumer: &mut Span, to_consume: Span) {
45    *consumer = Span {
46        start: usize_min(consumer.start, to_consume.start),
47        end: usize_max(consumer.end, to_consume.end),
48    };
49}
50
51/// Returns the minimum of two [`usize`]s.
52///
53/// This is a `const` alternative to [`usize::min`].
54const fn usize_min(a: usize, b: usize) -> usize {
55    if a < b { a } else { b }
56}
57
58/// Returns the maximum of two [`usize`]s.
59///
60/// This is a `const` alternative to [`usize::max`].
61const fn usize_max(a: usize, b: usize) -> usize {
62    if a > b { a } else { b }
63}