summaryrefslogtreecommitdiff
path: root/src/core/RangeSet.hpp
blob: b196dec2d94c44d26408b4f9e7ccda6e90cceafe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/*
    Ousía
    Copyright (C) 2014  Benjamin Paaßen, Andreas Stöckel

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef _OUSIA_RANGE_SET_HPP_
#define _OUSIA_RANGE_SET_HPP_

#include <limits>
#include <set>

namespace ousia {
/**
 * The Range structure represents an interval of numerical values of type T.
 */
template <typename T>
struct Range {
	/**
	 * Start is the start value of the range.
	 */
	T start;

	/**
	 * End is the end value of the range (inclusively).
	 */
	T end;

	/**
	 * Default constructor of the range class. The range is initialized as
	 * invalid, with start being set to the maximum possible value of the
	 * numerical type T, and end being set to the minimum possible value.
	 */
	Range()
	    : start(std::numeric_limits<T>::max()),
	      end(std::numeric_limits<T>::min())
	{
		// Do nothing here
	}

	/**
	 * Copies the given start and end value. The given values are not checked
	 * for validity. Use the "isValid"
	 *
	 * @param start is the minimum value the range still covers.
	 * @param end is the maximum value the range still covers.
	 */
	Range(const T &start, const T &end) : start(start), end(end)
	{
		// Do nothing here
	}

	/**
	 * Creates a range that covers exactly one element, namely the value given
	 * as parameter n.
	 */
	Range(const T &n) : start(n), end(n)
	{
		// Do nothing here
	}

	/**
	 * Returns true if this range is valid, e.g. its start value is smaller or
	 * equal to its end value.
	 *
	 * @return true if start is smaller or equal to end, false otherwise.
	 */
	bool isValid() const { return start <= end; }

	/**
	 * Checks whether the given value lies inside the range.
	 *
	 * @param v is the value that is being checked.
	 * @return true if the value lies within the range, false otherwise.
	 */
	bool inRange(T v) const { return (v >= start) && (v <= end); }

	/**
	 * Checks whether the given range overlaps with another range. Not that
	 * this check is only meaningful if both ranges are valid.
	 *
	 * @param r is the range that should be checked for overlapping with this
	 * range.
	 */
	bool overlaps(const Range<T> &r) const
	{
		return (((r.start >= start) || (r.end >= start)) &&
		        ((r.start <= end) || (r.end <= end)));
	}

	/**
	 * Returns true if the two given ranges are neighbours (their limits only
	 * differ in the smallest representable difference between them).
	 */
	bool neighbours(const Range<T> &r) const
	{
		constexpr T eps = std::numeric_limits<T>::is_integer
		                      ? 1
		                      : std::numeric_limits<T>::epsilon();
		return ((r.start > end) && ((r.start - eps) <= end)) ||
		       ((r.end < start) && ((r.end + eps) >= start));
	}

	/**
	 * Checks whether the given range completely covers this range.
	 */
	bool coveredBy(const Range<T> &r) const
	{
		return (r.start <= start) && (r.end >= end);
	}

	/**
	 * Checks whether this range completely covers the given range.
	 */
	bool covers(const Range<T> &r) const { return r.coveredBy(*this); }

	/**
	 * Calculates the union of the two ranges -- note that this operation is
	 * only valid if the ranges overlapp. Use the RangeSet class if you cannot
	 * guarantee that.
	 */
	Range<T> merge(const Range<T> &r) const
	{
		return Range(std::min(start, r.start), std::max(end, r.end));
	}

	/**
	 * Returns a range that represents the spans the complete set defined by the
	 * given type T.
	 */
	static Range<T> typeRange()
	{
		return Range(std::numeric_limits<T>::min(),
		             std::numeric_limits<T>::max());
	}

	/**
	 * Returns a range that represents the spans the complete set defined by the
	 * given type T up to a given value.
	 *
	 * @param till is the value up to which the range should be defined (till is
	 * included in the set).
	 */
	static Range<T> typeRangeUntil(const T &till)
	{
		return Range(std::numeric_limits<T>::min(), till);
	}

	/**
	 * Returns a range that represents the spans the complete set defined by the
	 * given type T up to a given value.
	 *
	 * @param from is the value from which the range should be defined (from is
	 * included in the set).
	 */
	static Range<T> typeRangeFrom(const T &from)
	{
		return Range(from, std::numeric_limits<T>::max());
	}

	friend bool operator==(const Range<T> &lhs, const Range<T> &rhs)
	{
		return lhs.start == rhs.start && lhs.end == rhs.end;
	}

	friend bool operator!=(const Range<T> &lhs, const Range<T> &rhs)
	{
		return !(lhs == rhs);
	}
};

/**
 * RangeComp is a comperator used to order to sort the ranges within the
 * ranges list. Sorts by the start element.
 */
template <typename T>
struct RangeComp {
	bool operator()(const Range<T> &lhs, const Range<T> &rhs) const
	{
		return lhs.start < rhs.start;
	}
};

/**
 * RangeSet represents a set of ranges of the given numerical type and is thus
 * capable of representing any possible subset of the given numerical type T.
 */
template <typename T>
class RangeSet {
protected:
	/**
	 * Set of ranges used internally.
	 */
	std::set<Range<T>, RangeComp<T>> ranges;

	/**
	 * Returns an iterator to the first element in the ranges list that overlaps
	 * with the given range.
	 *
	 * @param r is the range for which the first overlapping element should be
	 * found.
	 * @return an iterator pointing to the first overlapping element or to the
	 * end of the list if no such element was found.
	 */
	typename std::set<Range<T>, RangeComp<T>>::iterator firstOverlapping(
	    const Range<T> &r, const bool allowNeighbours) const
	{
		// Find the element with the next larger start value compared to the
		// start value given in r.
		auto it = ranges.upper_bound(r);

		// Go back one element
		if (it != ranges.begin()) {
			it--;
		}

		// Iterate until an overlapping element is found
		while ((it != ranges.end()) &&
		       !(it->overlaps(r) || (allowNeighbours && it->neighbours(r)))) {
			it++;
		}
		return it;
	}

public:
	/**
	 * Calculates the union of this range set and the given range.
	 *
	 * @param range is the range that should be merged into this range set.
	 */
	void merge(Range<T> r)
	{
		// Calculate a new range that covers both the new range and all old
		// ranges in the set -- delete all old elements on the way
		auto it = firstOverlapping(r, true);
		while ((it != ranges.end()) && (it->overlaps(r) || it->neighbours(r))) {
			r = r.merge(*it);
			it = ranges.erase(it);
		}

		// Insert the new range
		ranges.insert(r);
	}

	/**
	 * Calculates the union of this range set and the given range set.
	 *
	 * @param ranges is another range set for which the union with this set
	 * should be calculated.
	 */
	void merge(const RangeSet<T> &s)
	{
		for (Range<T> &r : s.ranges) {
			merge(r);
		}
	}

	/**
	 * Checks whether this range set S contains the given range R:
	 *   S u R = R
	 * (The intersection between R and S equals the given range)
	 *
	 * @param r is the range for which the containment should be checked.
	 * @return true if the above condition is met, false otherwise.
	 */
	bool contains(const Range<T> &r) const
	{
		auto it = firstOverlapping(r, false);
		if (it != ranges.end()) {
			return (*it).covers(r);
		}
		return false;
	}

	/**
	 * Checks whether this range Set S contains a given value v, which is
	 * the case if at least one contained range R contains v.
	 *
	 * @param v is some value.
	 * @return  true if at least one Range r returns true for r.inRange(v)
	 */
	bool contains(const T &v) const
	{
		for (auto &r : ranges) {
			if (r.inRange(v)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Checks whether this range set S1 contains the given range set S2:
	 *
	 * @param s is the range for which the containment should be checked.
	 * @return true if the above condition is met, false otherwise.
	 */
	bool contains(const RangeSet<T> &s) const
	{
		bool res = true;
		for (Range<T> &r : s.ranges) {
			res = res && contains(r);
		}
		return res;
	}

	/**
	 * Returns the minimum value that is still covered by this RangeSet.
	 *
	 * @return the minimum value that is still covered by this RangeSet.
	 */
	T min() const { return ranges.begin()->start; }

	/**
	 * Returns the maximum value that is still covered by this RangeSet.
	 *
	 * @return the maximum value that is still covered by this RangeSet.
	 */
	T max() const
	{
		T max = ranges.begin()->end;
		for (Range<T> &r : ranges) {
			if (r.end > max) {
				max = r.end;
			}
		}
		return std::move(max);
	}

	/**
	 * Empties the set.
	 */
	void clear() { ranges.clear(); }

	/**
	 * Returns the current list of ranges as a const reference.
	 */
	const std::set<Range<T>, RangeComp<T>> &getRanges() const
	{
		return this->ranges;
	}

	friend bool operator==(const RangeSet<T> &lhs, const RangeSet<T> &rhs)
	{
		if (lhs.ranges.size() != rhs.ranges.size()) {
			return false;
		}
		auto leftIt = lhs.ranges.begin();
		auto rightIt = rhs.ranges.begin();
		while (leftIt != lhs.ranges.end()) {
			if (*leftIt != *rightIt) {
				return false;
			}
			leftIt++;
			rightIt++;
		}
		return true;
	}

	friend bool operator!=(const RangeSet<T> &lhs, const RangeSet<T> &rhs)
	{
		return !(lhs == rhs);
	}
};
}

#endif /* _OUSIA_RANGE_SET_HPP_ */