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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
// -----------------------------------------------------------------------------
// This file is generated by `cargo run -p codegen -- --signed`.
// Do not edit manually.
// -----------------------------------------------------------------------------
#[cfg(test)]
mod tests;
use std::sync::Arc;
use int_interval::I32CO;
/// Read-only canonical interval set for `I32CO`.
///
/// A `I32COSet` stores a normalized collection of half-open `I32CO` intervals:
///
/// - intervals are sorted by `start`;
/// - intervals are non-overlapping;
/// - adjacent intervals are merged;
/// - all queries are performed against the sealed immutable array.
///
/// Construction is intentionally restricted. Use `I32COSetBuilder` for normal
/// construction.
pub mod set {
use super::*;
/// Immutable canonical interval set.
///
/// Internally this is an `Arc<[I32CO]>`, so cloning a `I32COSet` is cheap.
///
/// Canonical invariant:
///
/// ```text
/// for every adjacent pair a, b:
/// a.end_excl() < b.start()
/// ```
///
/// The strict `<` means both overlap and adjacency have already been merged.
#[repr(transparent)]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct I32COSet {
intervals: Arc<[I32CO]>,
}
// ------------------------------------------------------------
// basic api: construction / accessors
// ------------------------------------------------------------
mod basic {
use super::*;
impl I32COSet {
/// Builds a set from an already canonical interval vector.
///
/// # Safety
///
/// The caller must guarantee that `intervals` is canonical:
///
/// - intervals are sorted by ascending `start`;
/// - intervals are non-overlapping;
/// - contiguous intervals have already been merged;
/// - therefore, for every adjacent pair `a, b`,
/// `a.end_excl() < b.start()` holds.
///
/// Violating this invariant can make binary-search based queries
/// return incorrect results.
#[inline]
pub(in crate::i32) unsafe fn new_unchecked(intervals: Vec<I32CO>) -> Self {
debug_assert!(Self::is_canonical(&intervals));
Self {
intervals: Arc::from(intervals.into_boxed_slice()),
}
}
/// Checks the canonical invariant used by binary-search queries.
///
/// `I32CO` itself already guarantees single-interval validity. This
/// function only checks the relationship between adjacent intervals.
#[inline]
fn is_canonical(intervals: &[I32CO]) -> bool {
intervals.windows(2).all(|w| w[0].end_excl() < w[1].start())
}
}
impl I32COSet {
/// Returns the number of canonical intervals.
///
/// For the `I32CO` domain, the maximum canonical interval count is 128,
/// e.g. alternating single-point intervals across `[i32::MIN, i32::MAX)`.
#[inline]
pub fn interval_count(&self) -> u32 {
self.intervals.len() as u32
}
/// Returns whether the set contains no intervals.
#[inline]
pub fn is_empty(&self) -> bool {
self.intervals.is_empty()
}
/// Returns the canonical interval slice.
///
/// The returned slice is sorted, non-overlapping, and contains no
/// adjacent intervals.
#[inline]
pub fn as_slice(&self) -> &[I32CO] {
&self.intervals
}
/// Iterates over canonical intervals by value.
#[inline]
pub fn iter_intervals(&self) -> impl Iterator<Item = I32CO> {
self.intervals.iter().copied()
}
}
}
// ------------------------------------------------------------
// predicate api: yes/no queries
// ------------------------------------------------------------
mod predicates {
use super::*;
impl I32COSet {
/// Returns whether `x` is covered by any interval in the set.
///
/// Complexity: `O(log n)`.
#[inline]
pub fn contains_point(&self, x: i32) -> bool {
let i = self.intervals.partition_point(|iv| iv.start() <= x);
i != 0 && self.intervals[i - 1].contains(x)
}
/// Returns whether `query` is fully contained by one interval.
///
/// Since the set is canonical, a contained query interval can only
/// be contained by the interval immediately preceding or starting
/// at `query.start()`.
///
/// Complexity: `O(log n)`.
#[inline]
pub fn contains_interval(&self, query: I32CO) -> bool {
let i = self
.intervals
.partition_point(|iv| iv.start() <= query.start());
i != 0 && self.intervals[i - 1].contains_interval(query)
}
/// Returns whether `query` intersects any interval in the set.
///
/// Complexity: `O(log n)`.
#[inline]
pub fn intersects_interval(&self, query: I32CO) -> bool {
let i = self
.intervals
.partition_point(|iv| iv.end_excl() <= query.start());
self.intervals.get(i).is_some_and(|iv| iv.intersects(query))
}
}
}
// ------------------------------------------------------------
// search api: returning matched intervals
// ------------------------------------------------------------
mod search {
use super::*;
/// Point-based search APIs.
mod point {
use super::*;
impl I32COSet {
/// Returns the unique interval containing `x`, if any.
///
/// Because the set is canonical, at most one interval can
/// contain a single point.
///
/// Complexity: `O(log n)`.
#[inline]
pub fn interval_containing_point(&self, x: i32) -> Option<I32CO> {
let i = self.intervals.partition_point(|iv| iv.start() <= x);
if i == 0 {
return None;
}
let iv = self.intervals[i - 1];
iv.contains(x).then_some(iv)
}
}
}
/// Interval-based search APIs.
mod interval {
use super::*;
impl I32COSet {
/// Iterates over all canonical intervals intersecting `query`.
///
/// The iterator yields original intervals stored in the set,
/// not clipped intersection segments.
///
/// Complexity: `O(log n + k)`, where `k` is the number of
/// returned intervals.
#[inline]
pub fn intervals_intersecting(&self, query: I32CO) -> impl Iterator<Item = I32CO> {
let i = self
.intervals
.partition_point(|iv| iv.end_excl() <= query.start());
self.intervals[i..]
.iter()
.copied()
.take_while(move |iv| iv.start() < query.end_excl())
}
/// Iterates over clipped intersection segments with `query`.
///
/// Example:
///
/// ```text
/// set: [10, 20), [30, 40)
/// query: [15, 35)
/// out: [15, 20), [30, 35)
/// ```
///
/// Complexity: `O(log n + k)`, where `k` is the number of
/// intersecting intervals.
#[inline]
pub fn intersections(&self, query: I32CO) -> impl Iterator<Item = I32CO> {
self.intervals_intersecting(query)
.filter_map(move |iv| iv.intersection(query))
}
}
}
}
// ------------------------------------------------------------
// coverage api: covered length / uncovered length / ratio
// ------------------------------------------------------------
mod coverage {
use super::*;
impl I32COSet {
/// Returns the covered length inside `query`.
///
/// Since `I32COSet` is canonical, all intersection segments are
/// disjoint, so summing their lengths is valid.
///
/// The result is always `<= query.len()`.
#[inline]
pub fn covered_len(&self, query: I32CO) -> u32 {
self.intersections(query).map(|iv| iv.len()).sum()
}
/// Returns the uncovered length inside `query`.
#[inline]
pub fn uncovered_len(&self, query: I32CO) -> u32 {
query.len() - self.covered_len(query)
}
/// Returns `covered_len(query) / query.len()` as `f32`.
///
/// `query.len()` is non-zero because `I32CO` cannot represent an
/// empty interval.
#[inline]
pub fn coverage_ratio(&self, query: I32CO) -> f32 {
self.covered_len(query) as f32 / query.len() as f32
}
}
}
}
/// Concurrent builder for `I32COSet`.
///
/// The builder accepts concurrent inserts into a skip list. During `seal`,
/// raw intervals are scanned in sorted order and merged into a canonical
/// immutable `I32COSet`.
pub mod builder {
use std::cmp::Ordering;
use crossbeam_skiplist::SkipSet;
use super::set::I32COSet;
use super::*;
/// Private ordering key for storing `I32CO` inside `SkipSet`.
///
/// `I32CO` does not need to implement `Ord` in its own crate. This wrapper
/// defines the ordering locally:
///
/// ```text
/// (start, end_excl)
/// ```
///
/// Because this is a set key, duplicate identical intervals are naturally
/// deduplicated during the build phase. That is correct for interval-set
/// semantics.
#[repr(transparent)]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
struct Key(I32CO);
impl Ord for Key {
#[inline]
fn cmp(&self, other: &Self) -> Ordering {
self.0
.start()
.cmp(&other.0.start())
.then_with(|| self.0.end_excl().cmp(&other.0.end_excl()))
}
}
impl PartialOrd for Key {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
/// Concurrent write-side builder for `I32COSet`.
///
/// Insertions are expected `O(log n)` through `crossbeam_skiplist`.
/// No merging is performed during insertion; normalization happens once
/// in `seal`.
#[repr(transparent)]
#[derive(Debug, Default)]
pub struct I32COSetBuilder {
raw: SkipSet<Key>,
}
impl I32COSetBuilder {
/// Creates an empty builder.
#[inline]
pub fn new() -> Self {
Self::default()
}
/// Inserts one interval into the builder.
///
/// This method is safe to call concurrently through shared references.
/// Identical intervals are deduplicated by the underlying `SkipSet`.
#[inline]
pub fn insert(&self, iv: I32CO) {
self.raw.insert(Key(iv));
}
/// Consumes the builder and returns a canonical immutable set.
///
/// The merge process is linear over the sorted skip-list iterator:
///
/// - maintain one pending interval `cur`;
/// - if the next interval overlaps or is adjacent, replace `cur` with
/// its convex hull;
/// - otherwise, push `cur` and start a new pending interval;
/// - finally, push the last pending interval.
pub fn seal(self) -> I32COSet {
let mut iter = self.raw.iter().map(|entry| entry.value().0);
let Some(mut cur) = iter.next() else {
// SAFETY:
// The empty interval list is canonical.
return unsafe { I32COSet::new_unchecked(Vec::new()) };
};
let mut out = Vec::new();
for iv in iter {
if cur.is_contiguous_with(iv) {
cur = cur.convex_hull(iv);
} else {
out.push(cur);
cur = iv;
}
}
out.push(cur);
// SAFETY:
// `self.raw` iterates keys in ascending `(start, end_excl)` order.
// The loop maintains one pending merged interval `cur`.
//
// If `iv` is contiguous with or overlaps `cur`, both are replaced
// by their convex hull, so no overlap or adjacency is emitted.
//
// If `iv` is disjoint from `cur`, then sorted order plus the failed
// contiguity test imply `cur.end_excl() < iv.start()`. Pushing
// `cur` therefore preserves the canonical invariant.
//
// After the loop, the final pending interval is pushed. Therefore
// `out` is sorted, non-overlapping, and contains no adjacent
// intervals.
unsafe { I32COSet::new_unchecked(out) }
}
}
}