2 * Copyright 2013, Rene Gollent, rene@gollent.com.
3 * Distributed under the terms of the MIT License.
9 #include <AutoDeleter.h>
12 RangeList::RangeList()
13 : BObjectList
<Range
>(20, true)
18 RangeList::~RangeList()
24 RangeList::AddRange(int32 lowValue
, int32 highValue
)
26 if (lowValue
> highValue
)
30 if (CountItems() != 0) {
31 for (; i
< CountItems(); i
++) {
32 Range
* range
= ItemAt(i
);
33 if (lowValue
< range
->lowerBound
) {
34 if (highValue
< range
->lowerBound
) {
35 // the new range is completely below the bounds
36 // of the ranges we currently contain,
39 } else if (highValue
<= range
->upperBound
) {
40 // the new range partly overlaps the lower
42 range
->lowerBound
= lowValue
;
45 // the new range completely encompasses
47 range
->lowerBound
= lowValue
;
48 range
->upperBound
= highValue
;
49 _CollapseOverlappingRanges(i
+1, highValue
);
52 } else if (lowValue
< range
->upperBound
) {
53 if (highValue
<= range
->upperBound
) {
54 // the requested range is already completely contained
55 // within our existing range list
58 range
->upperBound
= highValue
;
59 _CollapseOverlappingRanges(i
+ 1, highValue
);
66 Range
* range
= new(std::nothrow
) Range(lowValue
, highValue
);
70 BPrivate::ObjectDeleter
<Range
> rangeDeleter(range
);
71 if (!AddItem(range
, i
))
74 rangeDeleter
.Detach();
80 RangeList::AddRange(const Range
& range
)
82 return AddRange(range
.lowerBound
, range
.upperBound
);
87 RangeList::RemoveRangeAt(int32 index
)
89 if (index
< 0 || index
>= CountItems())
92 RemoveItem(ItemAt(index
));
97 RangeList::Contains(int32 value
) const
99 for (int32 i
= 0; i
< CountItems(); i
++) {
100 const Range
* range
= ItemAt(i
);
101 if (value
< range
->lowerBound
|| value
> range
->upperBound
)
103 else if (value
>= range
->lowerBound
&& value
<= range
->upperBound
)
112 RangeList::CountRanges() const
119 RangeList::RangeAt(int32 index
) const
121 return ItemAt(index
);
126 RangeList::_CollapseOverlappingRanges(int32 startIndex
, int32 highValue
)
128 for (int32 i
= startIndex
; i
< CountItems();) {
129 // check if it also overlaps any of the following
131 Range
* nextRange
= ItemAt(i
);
132 if (nextRange
->lowerBound
> highValue
)
134 else if (nextRange
->upperBound
< highValue
) {
135 RemoveItem(nextRange
);
138 nextRange
->lowerBound
= highValue
+ 1;