RangeList<T> subtract (Range<T> range, RangeList<T> sub) { /* Start with the input range */ RangeList<T> result; result.add (range); if (sub.empty () || range.empty()) { return result; } typename RangeList<T>::List s = sub.get (); /* The basic idea here is to keep a list of the result ranges, and subtract the bits of `sub' from them one by one. */ for (typename RangeList<T>::List::const_iterator i = s.begin(); i != s.end(); ++i) { /* Here's where we'll put the new current result after subtracting *i from it */ RangeList<T> new_result; typename RangeList<T>::List r = result.get (); /* Work on all parts of the current result using this range *i */ for (typename RangeList<T>::List::const_iterator j = r.begin(); j != r.end(); ++j) { switch (coverage (j->from, j->to, i->from, i->to)) { case OverlapNone: /* The thing we're subtracting (*i) does not overlap this bit of the result (*j), so pass it through. */ new_result.add (*j); break; case OverlapInternal: /* Internal overlap of the thing we're subtracting (*i) from this bit of the result, so we should end up with two bits of (*j) left over, from the start of (*j) to the start of (*i), and from the end of (*i) to the end of (*j). */ assert (j->from < i->from); assert (j->to > i->to); new_result.add (Range<T> (j->from, i->from - 1)); new_result.add (Range<T> (i->to + 1, j->to)); break; case OverlapStart: /* The bit we're subtracting (*i) overlaps the start of the bit of the result (*j), * so we keep only the part of of (*j) from after the end of (*i) */ assert (i->to < j->to); new_result.add (Range<T> (i->to + 1, j->to)); break; case OverlapEnd: /* The bit we're subtracting (*i) overlaps the end of the bit of the result (*j), * so we keep only the part of of (*j) from before the start of (*i) */ assert (j->from < i->from); new_result.add (Range<T> (j->from, i->from - 1)); break; case OverlapExternal: /* total overlap of the bit we're subtracting with the result bit, so the result bit is completely removed; do nothing */ break; } } new_result.coalesce (); result = new_result; } return result; }
// Not empty set inline bool empty() const { return ranges.empty(); }