@@ -140,6 +140,11 @@ impl Range {
140140 self.from() == other.from() || (self.to() > other.from() && other.to() > self.from())
141141 }
142142
143+ #[inline]
144+ pub fn contains_range(&self, other: &Self) -> bool {
145+ self.from() <= other.from() && self.to() >= other.to()
146+ }
147+
143148 pub fn contains(&self, pos: usize) -> bool {
144149 self.from() <= pos && pos < self.to()
145150 }
@@ -544,6 +549,39 @@ impl Selection {
544549 pub fn len(&self) -> usize {
545550 self.ranges.len()
546551 }
552+
553+ // returns true if self ⊇ other
554+ pub fn contains(&self, other: &Selection) -> bool {
555+ // can't contain other if it is larger
556+ if other.len() > self.len() {
557+ return false;
558+ }
559+
560+ let (mut iter_self, mut iter_other) = (self.iter(), other.iter());
561+ let (mut ele_self, mut ele_other) = (iter_self.next(), iter_other.next());
562+
563+ loop {
564+ match (ele_self, ele_other) {
565+ (Some(ra), Some(rb)) => {
566+ if !ra.contains_range(rb) {
567+ // `self` doesn't contain next element from `other`, advance `self`, we need to match all from `other`
568+ ele_self = iter_self.next();
569+ } else {
570+ // matched element from `other`, advance `other`
571+ ele_other = iter_other.next();
572+ };
573+ }
574+ (None, Some(_)) => {
575+ // exhausted `self`, we can't match the reminder of `other`
576+ return false;
577+ }
578+ (_, None) => {
579+ // no elements from `other` left to match, `self` contains `other`
580+ return true;
581+ }
582+ }
583+ }
584+ }
547585}
548586
549587impl<'a> IntoIterator for &'a Selection {
@@ -982,4 +1020,30 @@ mod test {
9821020 &["", "abcd", "efg", "rs", "xyz"]
9831021 );
9841022 }
1023+ #[test]
1024+ fn test_selection_contains() {
1025+ fn contains(a: Vec<(usize, usize)>, b: Vec<(usize, usize)>) -> bool {
1026+ let sela = Selection::new(a.iter().map(|a| Range::new(a.0, a.1)).collect(), 0);
1027+ let selb = Selection::new(b.iter().map(|b| Range::new(b.0, b.1)).collect(), 0);
1028+ sela.contains(&selb)
1029+ }
1030+
1031+ // exact match
1032+ assert!(contains(vec!((1, 1)), vec!((1, 1))));
1033+
1034+ // larger set contains smaller
1035+ assert!(contains(vec!((1, 1), (2, 2), (3, 3)), vec!((2, 2))));
1036+
1037+ // multiple matches
1038+ assert!(contains(vec!((1, 1), (2, 2)), vec!((1, 1), (2, 2))));
1039+
1040+ // smaller set can't contain bigger
1041+ assert!(!contains(vec!((1, 1)), vec!((1, 1), (2, 2))));
1042+
1043+ assert!(contains(
1044+ vec!((1, 1), (2, 4), (5, 6), (7, 9), (10, 13)),
1045+ vec!((3, 4), (7, 9))
1046+ ));
1047+ assert!(!contains(vec!((1, 1), (5, 6)), vec!((1, 6))));
1048+ }
9851049}