From e2735ca2c5aa59209ef31589a03fc3b70a4a8814 Mon Sep 17 00:00:00 2001 From: DonIsaac <22823424+DonIsaac@users.noreply.github.com> Date: Sat, 27 Jul 2024 01:05:08 +0000 Subject: [PATCH] feat(span): add `contains_inclusive` method (#4491) Part of #4445, broken into a separate PR. --- crates/oxc_span/src/span.rs | 39 +++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/crates/oxc_span/src/span.rs b/crates/oxc_span/src/span.rs index 638b47a22202f..0f83cb38dd8d4 100644 --- a/crates/oxc_span/src/span.rs +++ b/crates/oxc_span/src/span.rs @@ -132,6 +132,30 @@ impl Span { self.start == SPAN.start && self.end == SPAN.end } + /// Check if this [`Span`] contains another [`Span`]. + /// + /// [`Span`]s that start & end at the same position as this [`Span`] are + /// considered contained. + /// + /// # Examples + /// + /// ```rust + /// # use oxc_span::Span; + /// let span = Span::new(5, 10); + /// + /// assert!(span.contains_inclusive(span)); // always true for itself + /// assert!(span.contains_inclusive(Span::new(5, 5))); + /// assert!(span.contains_inclusive(Span::new(6, 10))); + /// assert!(span.contains_inclusive(Span::empty(5))); + /// + /// assert!(!span.contains_inclusive(Span::new(4, 10))); + /// assert!(!span.contains_inclusive(Span::empty(0))); + /// ``` + #[inline] + pub const fn contains_inclusive(self, span: Span) -> bool { + self.start <= span.start && span.end <= self.end + } + /// Create a [`Span`] covering the maximum range of two [`Span`]s. /// /// # Example @@ -365,4 +389,19 @@ mod test { assert!(Span::new(0, 1) > Span::new(0, 0)); assert!(Span::new(2, 5) > Span::new(0, 3)); } + + #[test] + fn test_contains() { + let span = Span::new(5, 10); + + assert!(span.contains_inclusive(span)); + assert!(span.contains_inclusive(Span::new(5, 5))); + assert!(span.contains_inclusive(Span::new(10, 10))); + assert!(span.contains_inclusive(Span::new(6, 9))); + + assert!(!span.contains_inclusive(Span::new(0, 0))); + assert!(!span.contains_inclusive(Span::new(4, 10))); + assert!(!span.contains_inclusive(Span::new(5, 11))); + assert!(!span.contains_inclusive(Span::new(4, 11))); + } }