Debian Codegraph @

Xtimeless/src/data/chunked.rs

raw symbols SCIP
1 //! This is code responsible for possibly-chunked data.
2
3 #[derive(Clone, Default, Debug)]
4 struct DataChunk<T> {
5 /// The start offset of this chunk, should correspond to the time vector
6 /// indices. If that updates, this MUST also update.
7 start_offset: usize,
8
9 /// The actual value data!
10 data: Vec<T>,
11 }
12
13 impl<T> DataChunk<T> {
14 fn push(&mut self, item: T) {
15 self.data.push(item)
16 }
17 }
18
19 /// An iterator created from a [`ChunkedData`].
20 pub struct ChunkedDataIter<I: Iterator> {
21 iter: I,
22 size: usize, // TODO: We can probably store this as a `OnceCell` instead to avoid computing it if we don't need it.
23 }
24
25 impl<T, I: Iterator<Item = T>> Iterator for ChunkedDataIter<I> {
26 type Item = T;
27
28 fn next(&mut self) -> Option<Self::Item> {
29 self.iter.next()
30 }
31
32 fn size_hint(&self) -> (usize, Option<usize>) {
33 (self.size, Some(self.size))
34 }
35 }
36
37 impl<T, I: Iterator<Item = T>> ExactSizeIterator for ChunkedDataIter<I> {}
38
39 impl<T, I: Iterator<Item = T> + DoubleEndedIterator> DoubleEndedIterator for ChunkedDataIter<I> {
40 fn next_back(&mut self) -> Option<Self::Item> {
41 self.iter.next_back()
42 }
43 }
44
45 /// A struct representing data that may potentially have breaks.
46 /// If you expect that you may want to store time values but _not_
47 /// data values, use this to avoid storing blanks.
48 #[derive(Clone, Default, Debug)]
49 pub struct ChunkedData<D> {
50 next_index: usize,
51 is_active: bool,
52 chunks: Vec<DataChunk<D>>,
53 }
54
55 impl<D> ChunkedData<D> {
56 /// Returns an iterator of items alongside the associated indices for each item.
57 pub fn iter_with_index(&self) -> ChunkedDataIter<impl DoubleEndedIterator<Item = (usize, &D)>> {
58 let size = self.chunks.iter().map(|dc| dc.data.len()).sum();
59 let iter = self.chunks.iter().flat_map(|dc| {
60 let start = dc.start_offset;
61
62 dc.data
63 .iter()
64 .enumerate()
65 .map(move |(offset, datum)| (start + offset, datum))
66 });
67
68 ChunkedDataIter { iter, size }
69 }
70
71 /// Returns an iterator of items.
72 pub fn iter(&self) -> ChunkedDataIter<impl DoubleEndedIterator<Item = &D>> {
73 let size = self.chunks.iter().map(|dc| dc.data.len()).sum();
74 let iter = self.chunks.iter().flat_map(|dc| dc.data.iter());
75
76 ChunkedDataIter { iter, size }
77 }
78
79 /// Returns an iterator of owned items. This consumes the [`ChunkedData`].
80 ///
81 /// Note this is currently not just `into_iter` due to how it's implemented, this is subject to change.
82 pub fn into_owned_iter(self) -> ChunkedDataIter<impl DoubleEndedIterator<Item = D>> {
83 let size = self.chunks.iter().map(|dc| dc.data.len()).sum();
84 let iter = self.chunks.into_iter().flat_map(|dc| dc.data.into_iter());
85
86 ChunkedDataIter { iter, size }
87 }
88
89 /// Given a slice that serves as the "base" yielding items `T`, return an iterator of `(T, D)`, where each `D` from
90 /// the [`ChunkedData`] has its index associated with that of `base_slice`.
91 ///
92 /// This is meant to be used alongside a slice of time values.
93 ///
94 /// Note this will return the minimum of the number of elements in either the base slice or the [`ChunkedData`].
95 pub fn iter_along_base<'a, T>(
96 &'a self, base_slice: &'a [T],
97 ) -> ChunkedDataIter<impl DoubleEndedIterator<Item = (&'a T, &'a D)>> {
98 let size = if base_slice.len() >= self.length() {
99 // Happy path. We return at most the number of stored elements!
100 self.num_elements()
101 } else {
102 // Uh oh. We need a bit more logic around this step.
103
104 let mut num_returned_elements = 0;
105
106 for dc in self.chunks.iter() {
107 let start = dc.start_offset;
108 let end = dc.start_offset + dc.data.len();
109
110 if base_slice.len() > end {
111 num_returned_elements += dc.data.len();
112 } else if base_slice.len() < start {
113 break;
114 } else {
115 // It's somewhere in the middle.
116 num_returned_elements += base_slice.len() - start;
117 }
118 }
119
120 num_returned_elements
121 };
122
123 let iter = self.chunks.iter().flat_map(move |dc| {
124 let start = dc.start_offset;
125 let to_take = base_slice.len().saturating_sub(start); // Take at most all the values in the chunk, or up to the number of base element indices.
126
127 dc.data
128 .iter()
129 .take(to_take)
130 .enumerate()
131 .map(move |(offset, datum)| {
132 let actual_index = start + offset;
133 let base = &base_slice[actual_index];
134
135 (base, datum)
136 })
137 });
138
139 ChunkedDataIter { iter, size }
140 }
141
142 /// Return how many elements actually are stored in the [`ChunkedData`].
143 pub fn num_elements(&self) -> usize {
144 self.chunks.iter().map(|dc| dc.data.len()).sum()
145 }
146
147 /// Return the "length" of the [`ChunkedData`], _including_ skipped
148 /// elements.
149 pub fn length(&self) -> usize {
150 self.next_index
151 }
152
153 /// Push an element.
154 pub fn push(&mut self, item: D) {
155 if self.is_active {
156 let current_chunk = self
157 .chunks
158 .last_mut()
159 .expect("chunks must be initialized with at least a value if is_active is set");
160 current_chunk.push(item);
161 } else {
162 // Start a new chunk.
163 self.chunks.push(DataChunk {
164 start_offset: self.next_index,
165 data: vec![item],
166 });
167 self.is_active = true;
168 }
169
170 self.next_index += 1;
171 }
172
173 /// Manually mark that a break is needed in the chunk.
174 pub fn insert_break(&mut self) {
175 // "Seal" the latest chunk.
176 self.is_active = false;
177 }
178
179 /// Push an element. If `item` is [`None`], then it will automatically
180 /// insert a break in the chunk if needed.
181 pub fn try_push(&mut self, item: Option<D>) {
182 match item {
183 Some(item) => {
184 self.push(item);
185 }
186 None => {
187 self.insert_break();
188 self.next_index += 1;
189 }
190 }
191 }
192
193 /// Remove all elements up to (and including) `index`, including "skipped"
194 /// elements. This will result in the effective length becoming
195 /// `prev_length - index - 1`.
196 ///
197 /// If `index` goes past the number of elements, this function will return
198 /// an error containing the stored index in the [`ChunkedData`].
199 pub fn prune(&mut self, index: usize) -> Result<(), usize> {
200 if self.next_index == 0 || self.next_index - 1 < index || self.chunks.is_empty() {
201 return Err(self.next_index);
202 }
203
204 self.next_index -= index + 1;
205
206 let dc_index = match self.chunks.binary_search_by(|c| c.start_offset.cmp(&index)) {
207 Ok(result) => result,
208 Err(result) => {
209 if result > 0 {
210 result - 1
211 } else {
212 // Nothing to prune. We still need to change the offsets though.
213 for chunk in &mut self.chunks {
214 chunk.start_offset -= index + 1;
215 }
216
217 return Ok(());
218 }
219 }
220 };
221
222 // SAFETY: This index must be valid since it was returned from the binary search.
223 let curr = unsafe { self.chunks.get_unchecked_mut(dc_index) };
224 let to_remove = index - curr.start_offset + 1;
225
226 if to_remove <= curr.data.len() {
227 curr.data.drain(..to_remove);
228 curr.start_offset = 0;
229
230 // Remove all previous chunks.
231 self.chunks.drain(0..dc_index);
232
233 // Update offsets for all following chunks.
234 for chunk in self.chunks.iter_mut().skip(1) {
235 chunk.start_offset -= to_remove;
236 }
237 } else {
238 // Drain this chunk too.
239 self.chunks.drain(0..=dc_index);
240
241 for chunk in &mut self.chunks {
242 chunk.start_offset -= to_remove;
243 }
244 }
245
246 Ok(())
247 }
248
249 /// Shrink the [`ChunkedData`] after.
250 pub fn shrink_to_fit(&mut self) {
251 for chunk in &mut self.chunks {
252 chunk.data.shrink_to_fit();
253 }
254
255 self.chunks.shrink_to_fit();
256 }
257
258 /// Convenience function to prune _and_ shrink the [`ChunkedData`] after.
259 pub fn prune_and_shrink_to_fit(&mut self, index: usize) -> Result<(), usize> {
260 self.prune(index)?;
261 self.shrink_to_fit();
262
263 Ok(())
264 }
265
266 /// Try and return the first element.
267 pub fn first(&self) -> Option<&D> {
268 self.chunks.first().and_then(|chunk| chunk.data.first())
269 }
270
271 /// Try and return the last element.
272 pub fn last(&self) -> Option<&D> {
273 self.chunks.last().and_then(|chunk| chunk.data.last())
274 }
275
276 /// Return whether there are zero elements left stored internally.
277 pub fn no_elements(&self) -> bool {
278 self.num_elements() == 0
279 }
280 }
281
282 #[cfg(test)]
283 mod tests {
284 use super::*;
285
286 #[test]
287 fn chunked_push() {
288 let mut data = ChunkedData::default();
289 assert!(data.no_elements());
290
291 data.try_push(Some(1));
292
293 assert!(!data.chunks.is_empty());
294 assert!(data.is_active);
295 assert_eq!(data.chunks.last().as_ref().unwrap().data, vec![1]);
296 assert_eq!(data.next_index, 1);
297
298 data.try_push(Some(2));
299 data.try_push(None);
300
301 assert!(!data.is_active);
302 assert_eq!(data.chunks.len(), 1);
303 assert_eq!(data.chunks.first().unwrap().data, vec![1, 2]);
304 assert_eq!(data.next_index, 3);
305
306 data.try_push(None);
307 assert!(!data.is_active);
308 assert_eq!(data.next_index, 4);
309
310 data.try_push(Some(3));
311 assert!(data.is_active);
312 assert_eq!(data.chunks.last().as_ref().unwrap().data, vec![3]);
313 assert_eq!(data.next_index, 5);
314
315 assert_eq!(data.length(), 5);
316 assert_eq!(data.num_elements(), 3);
317 }
318
319 /// Ensure that if we push nothing at first, we don't incorrectly try and
320 /// seal nothing.
321 #[test]
322 fn chunked_empty_initial_push() {
323 let mut data: ChunkedData<u64> = ChunkedData::default();
324
325 data.try_push(None);
326 assert!(!data.is_active);
327
328 data.try_push(Some(1));
329 assert!(data.is_active);
330 assert_eq!(data.next_index, 2);
331 }
332
333 const POPULATION: [Option<u64>; 10] = [
334 Some(1),
335 Some(2),
336 Some(3),
337 None,
338 None,
339 None,
340 Some(7),
341 Some(8),
342 Some(9),
343 Some(10),
344 ];
345
346 fn test_populate(data: &mut ChunkedData<u64>) {
347 for p in POPULATION {
348 data.try_push(p);
349 }
350 }
351
352 /// Initialize data, prune, and insert.
353 #[track_caller]
354 fn test_pruning(to_prune_index: usize) {
355 // println!("Trying to prune up to index {to_prune_index}...");
356
357 let mut data = ChunkedData::default();
358 test_populate(&mut data);
359
360 assert!(data.prune(to_prune_index).is_ok());
361
362 let removed = to_prune_index + 1;
363 let result = data
364 .iter_with_index()
365 .map(|(a, b)| (a, *b))
366 .collect::<Vec<_>>();
367
368 let expected = POPULATION
369 .into_iter()
370 .skip(removed)
371 .enumerate()
372 .filter_map(|(a, b)| b.map(|b| (a, b)))
373 .collect::<Vec<_>>();
374
375 assert_eq!(result, expected);
376 assert_eq!(data.next_index, POPULATION.len() - (to_prune_index + 1));
377 }
378
379 #[test]
380 fn chunked_prune() {
381 test_pruning(0);
382 test_pruning(1);
383 test_pruning(2);
384 test_pruning(3);
385 test_pruning(4);
386 test_pruning(5);
387 test_pruning(6);
388 test_pruning(7);
389 test_pruning(8);
390 test_pruning(9);
391 }
392
393 /// Handle if we try and prune something empty.
394 #[test]
395 fn chunked_prune_empty() {
396 let mut data: ChunkedData<u64> = ChunkedData::default();
397 assert!(data.prune(0).is_err());
398 }
399
400 /// Handle if we try to clear an index past the index stored.
401 #[test]
402 fn chunked_prune_past_index() {
403 let mut data = ChunkedData::default();
404 test_populate(&mut data);
405
406 assert!(data.prune(10).is_err());
407 }
408
409 #[test]
410 fn chunked_prune_without_curr() {
411 let mut data = ChunkedData::default();
412 test_populate(&mut data);
413 data.try_push(None);
414
415 assert!(data.prune(10).is_ok());
416 }
417
418 #[test]
419 fn prune_zero_when_none() {
420 let mut data = ChunkedData::default();
421 data.try_push(None);
422 data.try_push(None);
423 data.try_push(None);
424 test_populate(&mut data);
425
426 assert!(data.prune(0).is_ok());
427 assert_eq!(data.chunks[0].start_offset, 2);
428 assert_eq!(data.chunks[1].start_offset, 8);
429 assert_eq!(data.next_index, POPULATION.len() + 3 - 1);
430
431 assert!(data.prune(0).is_ok());
432 assert_eq!(data.chunks[0].start_offset, 1);
433 assert_eq!(data.chunks[1].start_offset, 7);
434 assert_eq!(data.next_index, POPULATION.len() + 3 - 2);
435
436 assert!(data.prune(0).is_ok());
437 assert_eq!(data.chunks[0].start_offset, 0);
438 assert_eq!(data.chunks[1].start_offset, 6);
439 assert_eq!(data.next_index, POPULATION.len() + 3 - 3);
440
441 assert!(data.prune(0).is_ok());
442 assert_eq!(data.chunks[0].start_offset, 0);
443 assert_eq!(data.chunks[0].data.as_slice(), &[2, 3]);
444 assert_eq!(data.chunks[1].start_offset, 5);
445 assert_eq!(data.next_index, POPULATION.len() + 3 - 4);
446 }
447
448 #[test]
449 fn first_last() {
450 let mut data = ChunkedData::default();
451 test_populate(&mut data);
452
453 assert_eq!(data.first(), Some(&1));
454 assert_eq!(data.last(), Some(&10));
455 }
456
457 #[test]
458 fn iter() {
459 let mut data = ChunkedData::default();
460 test_populate(&mut data);
461
462 assert_eq!(
463 data.into_owned_iter().collect::<Vec<_>>(),
464 POPULATION.iter().filter_map(|v| *v).collect::<Vec<_>>(),
465 );
466 }
467
468 #[test]
469 fn reverse_iter() {
470 let mut data = ChunkedData::default();
471 test_populate(&mut data);
472
473 assert_eq!(
474 data.into_owned_iter().rev().collect::<Vec<_>>(),
475 POPULATION
476 .iter()
477 .filter_map(|v| *v)
478 .rev()
479 .collect::<Vec<_>>(),
480 );
481 }
482
483 #[track_caller]
484 fn base_slice_test(
485 data: &ChunkedData<u32>, base_slice: &[u32], expected: &[(u32, u32)],
486 base_slice_index: usize, expected_slice_index: usize,
487 ) {
488 let base_slice = &base_slice[0..base_slice_index];
489
490 assert_eq!(
491 data.iter_along_base(base_slice).len(),
492 expected_slice_index,
493 "the returned size of the iterator should match"
494 );
495 assert_eq!(
496 data.iter_along_base(base_slice)
497 .map(|(a, b)| (*a, *b))
498 .collect::<Vec<_>>(),
499 expected[0..expected_slice_index],
500 "the actual generated values should match"
501 );
502 }
503
504 #[test]
505 fn base_slice_simple() {
506 let mut data = ChunkedData::default();
507 data.push(1);
508 data.push(2);
509 data.push(3);
510
511 let base_slice = [1, 2, 3, 4, 5];
512 let expected = [(1, 1), (2, 2), (3, 3)];
513
514 // Test with a larger base slice
515 base_slice_test(&data, &base_slice, &expected, 5, 3);
516
517 // Test with an exact base slice
518 base_slice_test(&data, &base_slice, &expected, 3, 3);
519
520 // Test with a smaller base slice
521 base_slice_test(&data, &base_slice, &expected, 2, 2);
522 base_slice_test(&data, &base_slice, &expected, 1, 1);
523 base_slice_test(&data, &base_slice, &expected, 0, 0);
524 }
525
526 #[test]
527 fn base_slice_chunked() {
528 let mut data = ChunkedData::default();
529 data.push(1);
530 data.push(2);
531 data.push(3);
532 data.try_push(None);
533 data.try_push(None);
534 data.try_push(None);
535 data.push(7);
536 data.push(8);
537 data.push(9);
538
539 let base_slice = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
540 let expected = [(1, 1), (2, 2), (3, 3), (7, 7), (8, 8), (9, 9)];
541
542 // Test with a larger base slice
543 base_slice_test(&data, &base_slice, &expected, 10, 6);
544
545 // Test with an exact base slice
546 base_slice_test(&data, &base_slice, &expected, 9, 6);
547
548 // Test with a smaller base slice
549 base_slice_test(&data, &base_slice, &expected, 8, 5);
550 base_slice_test(&data, &base_slice, &expected, 7, 4);
551 base_slice_test(&data, &base_slice, &expected, 6, 3);
552 base_slice_test(&data, &base_slice, &expected, 5, 3);
553 base_slice_test(&data, &base_slice, &expected, 4, 3);
554 base_slice_test(&data, &base_slice, &expected, 3, 3);
555 base_slice_test(&data, &base_slice, &expected, 2, 2);
556 base_slice_test(&data, &base_slice, &expected, 1, 1);
557 base_slice_test(&data, &base_slice, &expected, 0, 0);
558 }
559 }