Function pest::merge_spans

source ·
pub fn merge_spans<'i>(a: &Span<'i>, b: &Span<'i>) -> Option<Span<'i>>
Expand description

Merges two spans into one.

This function merges two spans that are contiguous or overlapping into a single span that covers the entire range of the two input spans. This is useful when you want to aggregate information from multiple spans into a single entity.

The function checks if the input spans are overlapping or contiguous by comparing their start and end positions. If they are, a new span is created with the minimum start position and the maximum end position of the two input spans.

If the input spans are neither overlapping nor contiguous, the function returns None, indicating that a merge operation was not possible.

§Examples


// Example 1: Contiguous spans
let input = "abc\ndef\nghi";
let span1 = Span::new(input, 1, 7).unwrap();
let span2 = Span::new(input, 7, 11).unwrap();
let merged = merge_spans(&span1, &span2).unwrap();
assert_eq!(merged, Span::new(input, 1, 11).unwrap());

// Example 2: Overlapping spans
let input = "abc\ndef\nghi";
let span1 = Span::new(input, 1, 7).unwrap();
let span2 = Span::new(input, 5, 11).unwrap();
let merged = merge_spans(&span1, &span2).unwrap();
assert_eq!(merged, Span::new(input, 1, 11).unwrap());

// Example 3: Non-contiguous spans
let input = "abc\ndef\nghi";
let span1 = Span::new(input, 1, 7).unwrap();
let span2 = Span::new(input, 8, 11).unwrap();
let merged = merge_spans(&span1, &span2);
assert!(merged.is_none());