egglog_core_relations/offsets/
mod.rs1use std::{cmp, fmt, mem};
2
3use crate::numeric_id::{NumericId, define_id};
4
5use crate::{
6 Pool,
7 pool::{Clear, Pooled, with_pool_set},
8};
9
10define_id!(pub RowId, u32, "a numeric offset into a table");
11
12#[cfg(test)]
13mod tests;
14
15pub(crate) trait Offsets {
20 fn bounds(&self) -> Option<(RowId, RowId)>;
22 fn is_empty(&self) -> bool {
23 self.bounds().is_none_or(|(lo, hi)| lo == hi)
24 }
25 fn offsets(&self, f: impl FnMut(RowId));
26}
27
28#[derive(PartialEq, Eq, Debug, Clone, Copy, Hash)]
29pub struct OffsetRange {
30 pub(crate) start: RowId,
31 pub(crate) end: RowId,
32}
33
34impl Offsets for OffsetRange {
35 fn bounds(&self) -> Option<(RowId, RowId)> {
36 Some((self.start, self.end))
37 }
38
39 fn offsets(&self, f: impl FnMut(RowId)) {
40 RowId::range(self.start, self.end).for_each(f)
41 }
42}
43
44impl OffsetRange {
45 pub fn new(start: RowId, end: RowId) -> OffsetRange {
46 debug_assert!(
47 start <= end,
48 "attempting to create malformed range {start:?}..{end:?}"
49 );
50 OffsetRange { start, end }
51 }
52 pub(crate) fn size(&self) -> usize {
53 self.end.index() - self.start.index()
54 }
55}
56
57#[derive(Default, PartialEq, Eq, Debug, Hash)]
58pub struct SortedOffsetVector(Vec<RowId>);
59
60impl Clone for SortedOffsetVector {
61 fn clone(&self) -> Self {
62 Self(self.0.clone())
63 }
64
65 fn clone_from(&mut self, source: &Self) {
66 self.0.clone_from(&source.0);
67 }
68}
69
70impl SortedOffsetVector {
71 pub(crate) fn slice(&self) -> &SortedOffsetSlice {
72 unsafe { SortedOffsetSlice::new_unchecked(&self.0) }
74 }
75
76 pub(crate) fn push(&mut self, offset: RowId) {
77 assert!(self.0.last().is_none_or(|last| last <= &offset));
78 unsafe { self.push_unchecked(offset) }
79 }
80
81 pub(crate) unsafe fn push_unchecked(&mut self, offset: RowId) {
82 self.0.push(offset)
83 }
84
85 pub(crate) fn retain(&mut self, mut f: impl FnMut(RowId) -> bool) {
86 self.0.retain(|off| f(*off))
87 }
88
89 pub(crate) fn extend_nonoverlapping(&mut self, other: &SortedOffsetSlice) {
90 if other.inner().is_empty() {
91 return;
92 }
93 if self.0.is_empty() {
94 self.0.extend(other.iter());
95 return;
96 }
97 if self.0.last().unwrap() <= other.inner().first().unwrap() {
98 self.0.extend(other.iter());
99 return;
100 }
101 panic!("attempting to extend with overlapping offsets")
102 }
103
104 pub(crate) fn fill_from_dense(&mut self, range: &OffsetRange) {
106 self.0.clear();
107 self.0
108 .extend((range.start.index()..range.end.index()).map(RowId::from_usize));
109 }
110}
111
112impl Clear for SortedOffsetVector {
113 fn clear(&mut self) {
114 self.0.clear()
115 }
116 fn reuse(&self) -> bool {
117 self.0.capacity() > 0
118 }
119 fn bytes(&self) -> usize {
120 self.0.capacity() * mem::size_of::<RowId>()
121 }
122}
123
124impl Offsets for SortedOffsetVector {
125 fn bounds(&self) -> Option<(RowId, RowId)> {
126 self.slice().bounds()
127 }
128
129 fn offsets(&self, f: impl FnMut(RowId)) {
130 self.slice().offsets(f)
131 }
132}
133
134#[derive(PartialEq, Eq)]
135#[repr(transparent)]
136pub struct SortedOffsetSlice([RowId]);
137
138impl fmt::Debug for SortedOffsetSlice {
139 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140 f.debug_list().entries(self.0.iter()).finish()
141 }
142}
143
144impl SortedOffsetSlice {
145 pub(crate) unsafe fn new_unchecked(slice: &[RowId]) -> &SortedOffsetSlice {
146 debug_assert!(
147 slice.windows(2).all(|w| w[0] <= w[1]),
148 "slice is not sorted: {slice:?}"
149 );
150 unsafe { mem::transmute::<&[RowId], &SortedOffsetSlice>(slice) }
152 }
153
154 pub(crate) fn iter(&self) -> impl Iterator<Item = RowId> + '_ {
155 self.0.iter().copied()
156 }
157
158 pub(crate) fn inner(&self) -> &[RowId] {
159 &self.0
160 }
161
162 pub(crate) fn subslice(&self, lo: usize, hi: usize) -> &SortedOffsetSlice {
163 unsafe { SortedOffsetSlice::new_unchecked(&self.inner()[lo..hi]) }
165 }
166
167 pub(crate) fn binary_search_by_id(&self, target: RowId) -> usize {
169 self.binary_search_from(0, target)
170 }
171 pub(crate) fn binary_search_from(&self, start: usize, target: RowId) -> usize {
175 match self.inner()[start..].binary_search(&target) {
176 Ok(mut found) => {
177 found += start;
178 while found > 0 && self.inner()[found - 1] == target {
180 found -= 1;
181 }
182 found
183 }
184 Err(x) => start + x,
185 }
186 }
187
188 #[inline]
189 fn scan_for_offset(&self, start: usize, target: RowId) -> Result<usize, usize> {
190 let slice = self.inner();
191 let len = slice.len();
192
193 if start >= len {
194 return Err(len);
195 }
196 if slice[start] == target {
197 return Ok(start);
198 }
199 if slice[start] > target {
200 return Err(start);
201 }
202
203 let mut lo = start;
206 let mut step = 1usize;
207 let hi = loop {
208 let probe = lo + step;
209 if probe >= len {
210 break len;
211 }
212 match slice[probe].cmp(&target) {
213 cmp::Ordering::Less => {
214 lo = probe;
215 step = step.saturating_mul(2);
216 }
217 cmp::Ordering::Equal => {
218 let mut found = probe;
219 while found > start && slice[found - 1] == target {
220 found -= 1;
221 }
222 return Ok(found);
223 }
224 cmp::Ordering::Greater => break probe,
225 }
226 };
227
228 match slice[lo + 1..hi].binary_search(&target) {
230 Ok(mut found) => {
231 found += lo + 1;
232 while found > start && slice[found - 1] == target {
233 found -= 1;
234 }
235 Ok(found)
236 }
237 Err(x) => Err(lo + 1 + x),
238 }
239 }
240}
241
242impl Offsets for SortedOffsetSlice {
243 fn bounds(&self) -> Option<(RowId, RowId)> {
244 Some((
245 *self.0.first()?,
246 RowId::from_usize(self.0.last()?.index() + 1),
247 ))
248 }
249
250 fn offsets(&self, f: impl FnMut(RowId)) {
251 self.0.iter().copied().for_each(f)
252 }
253}
254
255impl Offsets for &'_ SortedOffsetSlice {
256 fn bounds(&self) -> Option<(RowId, RowId)> {
257 Some((
258 *self.0.first()?,
259 RowId::from_usize(self.0.last()?.index() + 1),
260 ))
261 }
262
263 fn offsets(&self, f: impl FnMut(RowId)) {
264 self.0.iter().copied().for_each(f)
265 }
266}
267
268#[derive(Copy, Clone)]
269pub enum SubsetRef<'a> {
270 Dense(OffsetRange),
271 Sparse(&'a SortedOffsetSlice),
272}
273
274impl Offsets for SubsetRef<'_> {
275 fn bounds(&self) -> Option<(RowId, RowId)> {
276 match self {
277 SubsetRef::Dense(r) => r.bounds(),
278 SubsetRef::Sparse(s) => s.bounds(),
279 }
280 }
281 fn offsets(&self, f: impl FnMut(RowId)) {
282 match self {
283 SubsetRef::Dense(r) => r.offsets(f),
284 SubsetRef::Sparse(s) => s.offsets(f),
285 }
286 }
287}
288
289impl SubsetRef<'_> {
290 pub(crate) fn size(&self) -> usize {
291 match self {
292 SubsetRef::Dense(range) => range.size(),
293 SubsetRef::Sparse(vec) => vec.0.len(),
294 }
295 }
296
297 pub(crate) fn to_owned(self, pool: &Pool<SortedOffsetVector>) -> Subset {
298 match self {
299 SubsetRef::Dense(r) => Subset::Dense(r),
300 SubsetRef::Sparse(s) => {
301 let mut vec = pool.get();
302 vec.extend_nonoverlapping(s);
303 Subset::Sparse(vec)
304 }
305 }
306 }
307
308 pub(crate) fn _slice(&self) -> &[RowId] {
310 match self {
311 SubsetRef::Dense(_) => panic!("getting slice from dense subset"),
312 SubsetRef::Sparse(slc) => slc.inner(),
313 }
314 }
315 pub(crate) fn iter_bounded(
316 self,
317 start: usize,
318 end: usize,
319 mut f: impl FnMut(RowId),
320 ) -> Option<usize> {
321 match self {
322 SubsetRef::Dense(r) => {
323 let mut cur = start;
324 for row in (r.start.index() + start.index())
325 ..cmp::min(r.start.index().saturating_add(end), r.end.index())
326 {
327 f(RowId::new(row as _));
328 cur += 1;
329 }
330 if cur + r.start.index() < r.end.index() {
331 Some(cur)
332 } else {
333 None
334 }
335 }
336 SubsetRef::Sparse(vec) => {
337 let end = cmp::min(vec.0.len(), end);
338 let next = if end == vec.0.len() { None } else { Some(end) };
339 vec.0[start..end].iter().copied().for_each(f);
340 next
341 }
342 }
343 }
344}
345
346#[derive(Debug, Hash, PartialEq, Eq)]
348pub enum Subset {
349 Dense(OffsetRange),
350 Sparse(Pooled<SortedOffsetVector>),
351}
352
353impl Offsets for Subset {
354 fn bounds(&self) -> Option<(RowId, RowId)> {
355 match self {
356 Subset::Dense(r) => r.bounds(),
357 Subset::Sparse(s) => s.slice().bounds(),
358 }
359 }
360 fn offsets(&self, f: impl FnMut(RowId)) {
361 match self {
362 Subset::Dense(r) => r.offsets(f),
363 Subset::Sparse(s) => s.slice().offsets(f),
364 }
365 }
366}
367
368impl Clone for Subset {
369 fn clone(&self) -> Self {
370 match self {
371 Subset::Dense(r) => Subset::Dense(*r),
372 Subset::Sparse(s) => Subset::Sparse(Pooled::cloned(s)),
373 }
374 }
375}
376
377impl Subset {
380 pub fn size(&self) -> usize {
382 match self {
383 Subset::Dense(range) => range.size(),
384 Subset::Sparse(vec) => vec.0.len(),
385 }
386 }
387
388 pub(crate) fn is_dense(&self) -> bool {
389 matches!(self, Subset::Dense(_))
390 }
391
392 pub fn as_ref(&self) -> SubsetRef<'_> {
393 match self {
394 Subset::Dense(r) => SubsetRef::Dense(*r),
395 Subset::Sparse(s) => SubsetRef::Sparse(s.slice()),
396 }
397 }
398
399 pub(crate) fn retain(&mut self, mut filter: impl FnMut(RowId) -> bool) {
400 match self {
401 Subset::Dense(offs) => {
402 let mut res = Subset::empty();
403 offs.offsets(|row| {
404 if filter(row) {
405 res.add_row_sorted(row);
406 }
407 });
408 *self = res;
409 }
410 Subset::Sparse(offs) => offs.retain(filter),
411 }
412 }
413 #[inline]
415 pub(crate) fn intersect(&mut self, other: SubsetRef, pool: &Pool<SortedOffsetVector>) {
416 match (self, other) {
417 (Subset::Dense(cur), SubsetRef::Dense(other)) => {
418 let resl = cmp::max(cur.start, other.start);
419 let resr = cmp::min(cur.end, other.end);
420 if resl >= resr {
421 *cur = OffsetRange::new(resl, resl);
422 } else {
423 *cur = OffsetRange::new(resl, resr);
424 }
425 }
426 (x @ Subset::Dense(_), SubsetRef::Sparse(sparse)) => {
427 let (low, hi) = x.bounds().unwrap();
428 if sparse.bounds().is_some() {
429 let l = sparse.binary_search_by_id(low);
430 let r = sparse.binary_search_by_id(hi);
431 if l >= r {
433 *x = Subset::Dense(OffsetRange::new(RowId::new(0), RowId::new(0)));
434 } else {
435 let subslice = sparse.subslice(l, r);
436 let mut res = pool.get();
437 res.extend_nonoverlapping(subslice);
438 *x = Subset::Sparse(res);
439 }
440 } else {
441 *x = Subset::Dense(OffsetRange::new(RowId::new(0), RowId::new(0)));
443 }
444 }
445 (Subset::Sparse(sparse), SubsetRef::Dense(dense)) => {
446 let l = sparse.slice().binary_search_by_id(dense.start);
448 let r = sparse.slice().binary_search_from(l, dense.end);
449 if l == 0 {
450 sparse.0.truncate(r);
451 } else {
452 sparse.0.copy_within(l..r, 0);
453 sparse.0.truncate(r - l);
454 }
455 }
456 (Subset::Sparse(cur), SubsetRef::Sparse(other)) => {
457 let cur_len = cur.0.len();
458 let other_inner = other.inner();
459 let other_len = other_inner.len();
460 if (cur_len <= 16 && other_len <= 16)
461 || (cur_len / 4 <= other_len && other_len <= cur_len * 4)
462 {
463 let mut write = 0usize;
465 let mut oi = 0usize;
466 for ci in 0..cur_len {
467 let target = cur.0[ci];
468 while oi < other_len && other_inner[oi] < target {
469 oi += 1;
470 }
471 if oi == other_len {
472 break;
473 }
474 if other_inner[oi] == target {
475 cur.0[write] = target;
476 write += 1;
477 oi += 1;
478 }
479 }
480 cur.0.truncate(write);
481 } else if cur_len > other_len {
482 let mut write = 0usize;
491 let mut ci = 0usize;
492 #[allow(clippy::needless_range_loop)]
493 for oi in 0..other_len {
494 if ci >= cur_len {
495 break;
496 }
497 let target = other_inner[oi];
498 debug_assert!(write <= ci);
499 let suffix = unsafe { SortedOffsetSlice::new_unchecked(&cur.0[ci..]) };
502 let result = suffix.scan_for_offset(0, target);
503 match result {
504 Ok(found) => {
505 cur.0[write] = target;
506 write += 1;
507 ci += found + 1;
508 }
509 Err(next_ci) => {
510 ci += next_ci;
511 }
512 }
513 }
514 cur.0.truncate(write);
515 } else {
516 let mut other_off = 0;
519 cur.retain(|rowid| match other.scan_for_offset(other_off, rowid) {
520 Ok(found) => {
521 other_off = found + 1;
522 true
523 }
524 Err(next_off) => {
525 other_off = next_off;
526 false
527 }
528 });
529 }
530 }
531 }
532 }
533
534 pub(crate) fn add_row_sorted(&mut self, row: RowId) {
540 match self {
541 Subset::Dense(range) => {
542 if range.end == range.start {
543 range.start = row;
544 range.end = row.inc();
545 return;
546 }
547 if range.end == row {
548 range.end = row.inc();
549 return;
550 }
551 let mut vec = with_pool_set(|pool_set| pool_set.get::<SortedOffsetVector>());
552 vec.fill_from_dense(range);
553 vec.push(row);
554 *self = Subset::Sparse(vec);
555 }
556 Subset::Sparse(s) => {
557 s.push(row);
558 }
559 }
560 }
561
562 pub(crate) fn empty() -> Subset {
563 Subset::Dense(OffsetRange::new(RowId::new(0), RowId::new(0)))
564 }
565}