systemd-journal-sdk-index 0.8.1

Index structures and query helpers for the pure Rust systemd journal SDK
Documentation
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
//! Sparse histogram with running counts for time-based aggregation.
//!
//! The histogram stores only bucket boundaries where entries exist. Each
//! bucket contains a running count: the total number of entries from the
//! start up to and including that bucket. This enables efficient range
//! queries via binary search on bucket boundaries.

use crate::{Bitmap, IndexError, Microseconds, Result, Seconds};
use journal_common::compat::is_multiple_of;

use serde::{Deserialize, Serialize};
use std::num::NonZeroU32;

/// A bucket boundary storing a time and running count.
///
/// The `count` is the 0-based index of the last entry in this bucket. For
/// example, if bucket at time 0 has count=4 and bucket at time 60 has count=9,
/// then:
/// - Bucket [0, 60) contains entries with indices 0-4 (5 entries)
/// - Bucket [60, 120) contains entries with indices 5-9 (5 entries)
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[cfg_attr(feature = "allocative", derive(allocative::Allocative))]
pub struct Bucket {
    /// Start time of this bucket (aligned to bucket_duration)
    pub start_time: Seconds,
    /// 0-based index of the last entry in this bucket
    pub count: u32,
}

/// Sparse histogram storing only bucket boundaries with running counts.
///
/// Invariants:
/// - `buckets` is sorted by `start_time`
/// - `start_time % bucket_duration == 0` for all buckets
/// - Always contains at least one bucket
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "allocative", derive(allocative::Allocative))]
pub struct Histogram {
    /// Fixed size of each time bucket in seconds
    pub bucket_duration: NonZeroU32,
    /// Sorted sparse vector of bucket boundaries
    pub buckets: Vec<Bucket>,
}

impl Histogram {
    /// Constructs a histogram from sorted timestamp-offset pairs.
    ///
    /// # Algorithm
    ///
    /// 1. Convert each timestamp to seconds and compute its bucket:
    ///    `(timestamp_secs / bucket_duration) * bucket_duration`
    /// 2. Track bucket boundaries: when an entry falls into a new bucket,
    ///    store the previous bucket with the index of its last entry (running
    ///    count)
    /// 3. Only buckets containing entries are stored (sparse representation)
    ///
    /// # Errors
    ///
    /// - `ZeroBucketDuration` if `bucket_duration` is 0
    /// - `EmptyHistogramInput` if `timestamp_offset_pairs` is empty
    ///
    /// # Panics
    ///
    /// Debug builds panic if `timestamp_offset_pairs` is not sorted.
    pub fn from_timestamp_offset_pairs(
        bucket_duration: Seconds,
        timestamp_offset_pairs: &[(Microseconds, std::num::NonZeroU64)],
    ) -> Result<Histogram> {
        if bucket_duration.0 == 0 {
            return Err(IndexError::ZeroBucketDuration);
        }

        if timestamp_offset_pairs.is_empty() {
            return Err(IndexError::EmptyHistogramInput);
        }

        debug_assert!(timestamp_offset_pairs.is_sorted());

        let mut buckets = Vec::new();
        let mut current_bucket = None;

        for (offset_index, &(timestamp, _offset)) in timestamp_offset_pairs.iter().enumerate() {
            // Calculate which bucket this timestamp falls into
            let bucket =
                Seconds((timestamp.to_seconds().0 / bucket_duration.0) * bucket_duration.0);

            match current_bucket {
                None => {
                    // First entry - don't create bucket yet, just track the bucket
                    debug_assert_eq!(offset_index, 0);
                    current_bucket = Some(bucket);
                }
                Some(prev_bucket) if bucket.0 > prev_bucket.0 => {
                    // New bucket boundary - save the LAST index of the previous bucket
                    buckets.push(Bucket {
                        start_time: prev_bucket,
                        count: offset_index as u32 - 1,
                    });
                    current_bucket = Some(bucket);
                }
                _ => {} // Same bucket, continue
            }
        }

        // Handle last bucket
        if let Some(last_bucket) = current_bucket {
            buckets.push(Bucket {
                start_time: last_bucket,
                count: timestamp_offset_pairs.len() as u32 - 1,
            });
        }

        // Now that we are done, we can convert to non-zero
        let bucket_duration = NonZeroU32::new(bucket_duration.0).expect("non-zero bucket duration");

        Ok(Histogram {
            bucket_duration,
            buckets,
        })
    }

    /// Get the start time of the histogram.
    pub fn start_time(&self) -> Seconds {
        let first_bucket = self.buckets.first().expect("histogram to have buckets");
        first_bucket.start_time
    }

    /// Get the end time of the histogram.
    pub fn end_time(&self) -> Seconds {
        let last_bucket = self.buckets.last().expect("histogram to have buckets");
        Seconds(last_bucket.start_time.0 + self.bucket_duration.get())
    }

    /// Get the time range covered by the histogram.
    pub fn time_range(&self) -> (Seconds, Seconds) {
        (self.start_time(), self.end_time())
    }

    /// Returns the number of buckets in the histogram.
    pub fn num_buckets(&self) -> usize {
        self.buckets.len()
    }

    /// Get the total number of entries in the histogram.
    pub fn total_entries(&self) -> usize {
        let last_bucket = self.buckets.last().expect("histogram to have buckets");
        // FIXME: Off-by-one error
        last_bucket.count as usize + 1
    }

    /// Check if the file histogram is empty.
    pub fn is_empty(&self) -> bool {
        self.buckets.is_empty()
    }

    /// Count entries (from a bitmap) that fall within a time range using the histogram's bucket structure.
    ///
    /// # Algorithm
    ///
    /// 1. Binary search to find the first bucket at or after `start_time`
    /// 2. Binary search to find the last bucket before `end_time`
    /// 3. Extract entry index range from running counts:
    ///    - Start index: running count of previous bucket + 1 (or 0 if first bucket)
    ///    - End index: running count of last bucket (inclusive)
    /// 4. Count bitmap entries in the index range
    ///
    /// Returns `None` if the time range is not aligned to `bucket_duration` or
    /// invalid.
    pub fn count_entries_in_time_range(
        &self,
        bitmap: &Bitmap,
        start_time: Seconds,
        end_time: Seconds,
    ) -> Option<usize> {
        // Validate inputs
        if start_time >= end_time {
            return None;
        }

        // Verify alignment to bucket_duration
        if !is_multiple_of(start_time.0, self.bucket_duration.get())
            || !is_multiple_of(end_time.0, self.bucket_duration.get())
        {
            return None;
        }

        // Handle empty histogram or bitmap
        if self.buckets.is_empty() || bitmap.is_empty() {
            return Some(0);
        }

        // Find the bucket indices for start and end times using binary search
        // partition_point returns the index of the first bucket with start_time >= start_time
        let start_bucket_idx = self.buckets.partition_point(|b| b.start_time < start_time);

        // If start_bucket_idx is beyond all buckets, no matches possible
        if start_bucket_idx >= self.buckets.len() {
            return Some(0);
        }

        // Find the last bucket that starts before end_time
        // partition_point returns the index of the first bucket with start_time >= end_time,
        // so we need to subtract 1 to get the last bucket before end_time
        let end_bucket_idx = self
            .buckets
            .partition_point(|b| b.start_time < end_time)
            .saturating_sub(1);

        // If start is after end, the range doesn't contain any buckets
        if start_bucket_idx > end_bucket_idx {
            return Some(0);
        }

        // Get the running count boundaries
        // For start: we want entries AFTER the previous bucket's running count
        let start_running_count = if start_bucket_idx == 0 {
            0
        } else {
            self.buckets[start_bucket_idx - 1].count + 1
        };

        // For end: we want entries UP TO AND INCLUDING this bucket's running count
        let end_running_count = self.buckets[end_bucket_idx].count;

        // Range is [start_running_count, end_running_count + 1) since range_cardinality is exclusive on the end
        let count = bitmap.range_cardinality(start_running_count..(end_running_count + 1));

        Some(count as usize)
    }

    #[deprecated(since = "0.1.0", note = "Use count_entries_in_time_range() instead")]
    pub fn count_bitmap_entries_in_range(
        &self,
        bitmap: &Bitmap,
        start_time: Seconds,
        end_time: Seconds,
    ) -> Option<usize> {
        self.count_entries_in_time_range(bitmap, start_time, end_time)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Helper to create a test histogram with known buckets
    ///
    /// Creates a histogram with:
    /// - bucket_duration: 60 seconds
    /// - Entries at indices 0-4 in bucket starting at time 0
    /// - Entries at indices 5-9 in bucket starting at time 60
    /// - Entries at indices 10-14 in bucket starting at time 120
    /// - Entries at indices 15-19 in bucket starting at time 180
    fn create_test_histogram() -> Histogram {
        // Create 20 entries across 4 buckets (60 second buckets)
        let pairs: Vec<(Microseconds, std::num::NonZeroU64)> = (0..20)
            .map(|i| {
                // Distribute entries: 0-4 -> [0,60), 5-9 -> [60,120), etc.
                let bucket_index = i / 5;
                let offset_in_bucket = i % 5;
                // Spread entries within each bucket at 10 second intervals
                let timestamp_secs = bucket_index * 60 + offset_in_bucket * 10;
                (
                    Microseconds(timestamp_secs * 1_000_000),
                    std::num::NonZeroU64::new(i as u64 + 1).unwrap(),
                )
            })
            .collect();

        Histogram::from_timestamp_offset_pairs(Seconds(60), &pairs).unwrap()
    }

    // Tests for from_timestamp_offset_pairs construction

    #[test]
    fn test_from_timestamp_offset_pairs_single_entry() {
        let pairs = vec![(
            Seconds(1).to_microseconds(),
            std::num::NonZeroU64::new(1).unwrap(),
        )];
        let histogram = Histogram::from_timestamp_offset_pairs(Seconds(60), &pairs).unwrap();

        assert_eq!(histogram.bucket_duration.get(), 60);
        assert_eq!(histogram.num_buckets(), 1);
        assert_eq!(histogram.buckets[0].start_time, Seconds(0));
        assert_eq!(histogram.buckets[0].count, 0);
        assert_eq!(histogram.total_entries(), 1);
    }

    #[test]
    fn test_from_timestamp_offset_pairs_all_in_one_bucket() {
        let pairs: Vec<_> = (0..5)
            .map(|i| {
                (
                    Seconds(i * 10).to_microseconds(),
                    std::num::NonZeroU64::new(i as u64 + 1).unwrap(),
                )
            })
            .collect();
        let histogram = Histogram::from_timestamp_offset_pairs(Seconds(60), &pairs).unwrap();

        assert_eq!(histogram.num_buckets(), 1);
        assert_eq!(histogram.buckets[0].start_time, Seconds(0));
        assert_eq!(histogram.buckets[0].count, 4);
        assert_eq!(histogram.total_entries(), 5);
    }

    #[test]
    fn test_from_timestamp_offset_pairs_exact_boundaries() {
        // Test entries at exact bucket boundaries
        let pairs = vec![
            (Microseconds(0), std::num::NonZeroU64::new(1).unwrap()),
            (
                Seconds(60).to_microseconds(),
                std::num::NonZeroU64::new(2).unwrap(),
            ),
            (
                Seconds(120).to_microseconds(),
                std::num::NonZeroU64::new(3).unwrap(),
            ),
            (
                Seconds(180).to_microseconds(),
                std::num::NonZeroU64::new(4).unwrap(),
            ),
        ];
        let histogram = Histogram::from_timestamp_offset_pairs(Seconds(60), &pairs).unwrap();

        assert_eq!(histogram.num_buckets(), 4);
        assert_eq!(histogram.buckets[0].start_time, Seconds(0));
        assert_eq!(histogram.buckets[0].count, 0);
        assert_eq!(histogram.buckets[1].start_time, Seconds(60));
        assert_eq!(histogram.buckets[1].count, 1);
        assert_eq!(histogram.buckets[2].start_time, Seconds(120));
        assert_eq!(histogram.buckets[2].count, 2);
        assert_eq!(histogram.buckets[3].start_time, Seconds(180));
        assert_eq!(histogram.buckets[3].count, 3);
        assert_eq!(histogram.total_entries(), 4);
    }

    #[test]
    fn test_from_timestamp_offset_pairs_multiple_buckets() {
        // 2 entries in first bucket, 3 in second bucket
        let pairs = vec![
            (
                Seconds(10).to_microseconds(),
                std::num::NonZeroU64::new(1).unwrap(),
            ),
            (
                Seconds(20).to_microseconds(),
                std::num::NonZeroU64::new(2).unwrap(),
            ),
            (
                Seconds(70).to_microseconds(),
                std::num::NonZeroU64::new(3).unwrap(),
            ),
            (
                Seconds(80).to_microseconds(),
                std::num::NonZeroU64::new(4).unwrap(),
            ),
            (
                Seconds(90).to_microseconds(),
                std::num::NonZeroU64::new(5).unwrap(),
            ),
        ];
        let histogram = Histogram::from_timestamp_offset_pairs(Seconds(60), &pairs).unwrap();

        assert_eq!(histogram.num_buckets(), 2);
        assert_eq!(histogram.buckets[0].start_time, Seconds(0));
        assert_eq!(histogram.buckets[0].count, 1); // Entries 0-1
        assert_eq!(histogram.buckets[1].start_time, Seconds(60));
        assert_eq!(histogram.buckets[1].count, 4); // Entries 0-4
        assert_eq!(histogram.total_entries(), 5);
    }

    #[test]
    fn test_from_timestamp_offset_pairs_sparse_buckets() {
        // Test with gaps between buckets
        let pairs = vec![
            (Microseconds(0), std::num::NonZeroU64::new(1).unwrap()),
            (
                Seconds(180).to_microseconds(),
                std::num::NonZeroU64::new(2).unwrap(),
            ), // Skip buckets 60 and 120
        ];
        let histogram = Histogram::from_timestamp_offset_pairs(Seconds(60), &pairs).unwrap();

        assert_eq!(histogram.num_buckets(), 2);
        assert_eq!(histogram.buckets[0].start_time, Seconds(0));
        assert_eq!(histogram.buckets[0].count, 0);
        assert_eq!(histogram.buckets[1].start_time, Seconds(180));
        assert_eq!(histogram.buckets[1].count, 1);
        assert_eq!(histogram.total_entries(), 2);
    }

    #[test]
    fn test_from_timestamp_offset_pairs_large_bucket_duration() {
        // Test with larger bucket duration
        let pairs = vec![
            (Microseconds(0), std::num::NonZeroU64::new(1).unwrap()),
            (
                Seconds(500).to_microseconds(),
                std::num::NonZeroU64::new(2).unwrap(),
            ),
            (
                Seconds(1000).to_microseconds(),
                std::num::NonZeroU64::new(3).unwrap(),
            ),
        ];
        let histogram = Histogram::from_timestamp_offset_pairs(Seconds(600), &pairs).unwrap();

        assert_eq!(histogram.bucket_duration.get(), 600);
        assert_eq!(histogram.num_buckets(), 2);
        assert_eq!(histogram.buckets[0].start_time, Seconds(0));
        assert_eq!(histogram.buckets[0].count, 1); // Entries 0-1 (0s and 500s both in [0, 600))
        assert_eq!(histogram.buckets[1].start_time, Seconds(600));
        assert_eq!(histogram.buckets[1].count, 2); // Entry 2 (1000s in [600, 1200))
        assert_eq!(histogram.total_entries(), 3);
    }

    #[test]
    fn test_from_timestamp_offset_pairs_zero_bucket_duration() {
        let pairs = vec![(Microseconds(0), std::num::NonZeroU64::new(1).unwrap())];
        let result = Histogram::from_timestamp_offset_pairs(Seconds(0), &pairs);
        assert!(matches!(result, Err(IndexError::ZeroBucketDuration)));
    }

    #[test]
    fn test_from_empty_timestamp_offset_pairs() {
        let pairs = Vec::new();
        let result = Histogram::from_timestamp_offset_pairs(Seconds(1), &pairs);
        assert!(matches!(result, Err(IndexError::EmptyHistogramInput)));
    }

    #[test]
    fn test_count_entries_in_time_range_full_bucket() {
        let histogram = create_test_histogram();
        // Bitmap contains entries 5, 6, 7, 8, 9 (all in bucket starting at 60)
        let bitmap = Bitmap::from_sorted_iter([5, 6, 7, 8, 9]).unwrap();

        // Query for the full bucket from 60 to 120
        let count = histogram.count_entries_in_time_range(&bitmap, Seconds(60), Seconds(120));
        assert_eq!(count, Some(5));
    }

    #[test]
    fn test_count_entries_in_time_range_partial_match() {
        let histogram = create_test_histogram();
        // Bitmap contains some entries in bucket 60-120 and some in 120-180
        let bitmap = Bitmap::from_sorted_iter([7, 8, 9, 10, 11]).unwrap();

        // Query for bucket 60-120 should only count entries 7, 8, 9
        let count = histogram.count_entries_in_time_range(&bitmap, Seconds(60), Seconds(120));
        assert_eq!(count, Some(3));
    }

    #[test]
    fn test_count_entries_in_time_range_multiple_buckets() {
        let histogram = create_test_histogram();
        // Bitmap spans multiple buckets
        let bitmap = Bitmap::from_sorted_iter([5, 6, 10, 11, 15, 16]).unwrap();

        // Query for buckets 60-180 (includes buckets at 60 and 120)
        let count = histogram.count_entries_in_time_range(&bitmap, Seconds(60), Seconds(180));
        assert_eq!(count, Some(4)); // 5, 6, 10, 11
    }

    #[test]
    fn test_count_entries_in_time_range_no_matches() {
        let histogram = create_test_histogram();
        // Bitmap contains entries in bucket 0-60
        let bitmap = Bitmap::from_sorted_iter([0, 1, 2]).unwrap();

        // Query for bucket 120-180 should find no matches
        let count = histogram.count_entries_in_time_range(&bitmap, Seconds(120), Seconds(180));
        assert_eq!(count, Some(0));
    }

    #[test]
    fn test_count_entries_in_time_range_empty_bitmap() {
        let histogram = create_test_histogram();
        let bitmap = Bitmap::new();

        let count = histogram.count_entries_in_time_range(&bitmap, Seconds(0), Seconds(60));
        assert_eq!(count, Some(0));
    }

    #[test]
    fn test_count_entries_in_time_range_unaligned_start() {
        let histogram = create_test_histogram();
        let bitmap = Bitmap::from_sorted_iter([5, 6, 7]).unwrap();

        // Start time not aligned to bucket_duration (60)
        let count = histogram.count_entries_in_time_range(&bitmap, Seconds(30), Seconds(120));
        assert_eq!(count, None);
    }

    #[test]
    fn test_count_entries_in_time_range_unaligned_end() {
        let histogram = create_test_histogram();
        let bitmap = Bitmap::from_sorted_iter([5, 6, 7]).unwrap();

        // End time not aligned to bucket_duration (60)
        let count = histogram.count_entries_in_time_range(&bitmap, Seconds(60), Seconds(100));
        assert_eq!(count, None);
    }

    #[test]
    fn test_count_entries_in_time_range_invalid_range() {
        let histogram = create_test_histogram();
        let bitmap = Bitmap::from_sorted_iter([5, 6, 7]).unwrap();

        // start >= end
        let count = histogram.count_entries_in_time_range(&bitmap, Seconds(120), Seconds(60));
        assert_eq!(count, None);

        // start == end
        let count = histogram.count_entries_in_time_range(&bitmap, Seconds(60), Seconds(60));
        assert_eq!(count, None);
    }

    #[test]
    fn test_count_entries_in_time_range_outside_histogram() {
        let histogram = create_test_histogram();
        let bitmap = Bitmap::from_sorted_iter([5, 6, 7]).unwrap();

        // Range completely before histogram
        let count = histogram.count_entries_in_time_range(&bitmap, Seconds(0), Seconds(60));
        // This will actually work since 0-60 is the first bucket
        assert!(count.is_some());

        // Range completely after histogram (histogram ends at 240)
        let count = histogram.count_entries_in_time_range(&bitmap, Seconds(240), Seconds(300));
        assert_eq!(count, Some(0));
    }

    #[test]
    fn test_count_entries_in_time_range_first_bucket() {
        let histogram = create_test_histogram();
        // Entries in first bucket (0-60)
        let bitmap = Bitmap::from_sorted_iter([0, 1, 2, 3, 4]).unwrap();

        let count = histogram.count_entries_in_time_range(&bitmap, Seconds(0), Seconds(60));
        assert_eq!(count, Some(5));
    }

    #[test]
    fn test_count_entries_in_time_range_last_bucket() {
        let histogram = create_test_histogram();
        // Entries in last bucket (180-240)
        let bitmap = Bitmap::from_sorted_iter([15, 16, 17, 18, 19]).unwrap();

        let count = histogram.count_entries_in_time_range(&bitmap, Seconds(180), Seconds(240));
        assert_eq!(count, Some(5));
    }

    #[test]
    fn test_count_entries_in_time_range_all_buckets() {
        let histogram = create_test_histogram();
        // Entries spanning all buckets
        let bitmap = Bitmap::from_sorted_iter([0, 5, 10, 15]).unwrap();

        // Query for entire histogram range
        let count = histogram.count_entries_in_time_range(&bitmap, Seconds(0), Seconds(240));
        assert_eq!(count, Some(4));
    }

    #[test]
    fn test_histogram_properties() {
        let histogram = create_test_histogram();

        assert_eq!(histogram.start_time(), Seconds(0));
        assert_eq!(histogram.end_time(), Seconds(240));
        assert_eq!(histogram.time_range(), (Seconds(0), Seconds(240)));
        assert_eq!(histogram.num_buckets(), 4);
        assert!(!histogram.is_empty());
        assert_eq!(histogram.total_entries(), 20);
    }

    // Bitmap edge case tests

    #[test]
    fn test_bitmap_with_indices_beyond_histogram_range() {
        let histogram = create_test_histogram();
        // Histogram has entries 0-19, bitmap has indices beyond that
        let bitmap = Bitmap::from_sorted_iter([5, 6, 7, 25, 30, 100]).unwrap();

        // Query bucket 60-120 (entries 5-9)
        // Should only count the valid indices (5, 6, 7) that fall in range
        let count = histogram.count_entries_in_time_range(&bitmap, Seconds(60), Seconds(120));
        assert_eq!(count, Some(3));
    }

    #[test]
    fn test_bitmap_all_indices_outside_queried_range() {
        let histogram = create_test_histogram();
        // Bitmap has valid indices but none in the queried range
        let bitmap = Bitmap::from_sorted_iter([0, 1, 2, 3, 4]).unwrap();

        // Query bucket 120-180 (entries 10-14)
        let count = histogram.count_entries_in_time_range(&bitmap, Seconds(120), Seconds(180));
        assert_eq!(count, Some(0));
    }

    #[test]
    fn test_bitmap_with_sparse_scattered_indices() {
        let histogram = create_test_histogram();
        // Very sparse bitmap with indices scattered across all buckets
        let bitmap = Bitmap::from_sorted_iter([1, 7, 11, 18]).unwrap();

        // Query middle buckets 60-180 (entries 5-14)
        // Should count indices 7 and 11
        let count = histogram.count_entries_in_time_range(&bitmap, Seconds(60), Seconds(180));
        assert_eq!(count, Some(2));
    }

    #[test]
    fn test_bitmap_at_range_boundaries() {
        let histogram = create_test_histogram();
        // Bitmap with entries exactly at the boundaries of the queried range
        let bitmap = Bitmap::from_sorted_iter([4, 5, 9, 10]).unwrap();

        // Query bucket 60-120 (entries 5-9)
        // Should include 5, 9 but not 4 (in previous bucket) or 10 (in next bucket)
        let count = histogram.count_entries_in_time_range(&bitmap, Seconds(60), Seconds(120));
        assert_eq!(count, Some(2));
    }

    #[test]
    fn test_bitmap_with_only_out_of_range_indices() {
        let histogram = create_test_histogram();
        // Bitmap with indices all beyond the histogram's range
        let bitmap = Bitmap::from_sorted_iter([25, 30, 50, 100]).unwrap();

        // Query any valid range
        let count = histogram.count_entries_in_time_range(&bitmap, Seconds(0), Seconds(60));
        assert_eq!(count, Some(0));
    }

    #[test]
    fn test_bitmap_single_index_in_range() {
        let histogram = create_test_histogram();
        // Bitmap with many indices but only one in the queried range
        let bitmap = Bitmap::from_sorted_iter([0, 1, 2, 7, 15, 16, 17]).unwrap();

        // Query bucket 60-120 (entries 5-9), only index 7 matches
        let count = histogram.count_entries_in_time_range(&bitmap, Seconds(60), Seconds(120));
        assert_eq!(count, Some(1));
    }
}