Debian Codegraph @

src/cumulative.rs

raw symbols SCIP
1 use std::collections::BTreeMap;
2
3 use crate::quantile::{Quantile, QuantilesResult, SampleQuantiles};
4 use crate::{
5 Bucket, Config, Count, Error, Histogram, Histogram32, SparseHistogram, SparseHistogram32,
6 };
7
8 macro_rules! define_cumulative_histogram {
9 ($name:ident, $ref_name:ident, $iter:ident, $qr_iter:ident, $hist:ident, $sparse:ident, $count:ty) => {
10 /// A read-only, cumulative histogram for fast quantile queries.
11 ///
12 /// This is a variant of the [`SparseHistogram`] with cumulative counts
13 /// (starting from the first bucket) for each bucket that is present.
14 ///
15 /// Stores only non-zero buckets in columnar form, like [`SparseHistogram`],
16 /// but with **cumulative** counts: `count[i]` equals the total number of
17 /// observations in buckets `0..=i` (i.e., a running prefix sum). The last
18 /// element of `count` equals the total observation count.
19 ///
20 /// `CumulativeROHistogram` is intended to be read-only—i.e. it shouldn't
21 /// accept updates for new observations, because such operations would be
22 /// expensive given counts are cumulative. On the other hand, querying
23 /// percentiles is cheaper than standard or sparse histograms without
24 /// cumulative counts, which can be performed with binary search.
25 /// Additional methods to provide the percentile range each or all bucket(s)
26 /// represent are implmented to facilitate analytics based on such histograms.
27 // `mean` is an `f64`, so `Eq` cannot be derived for this type.
28 #[derive(Clone, Debug, PartialEq)]
29 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
30 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
31 pub struct $name {
32 config: Config,
33 index: Vec<u32>,
34 count: Vec<$count>,
35 /// Mean of all observations, estimated using bucket midpoints.
36 /// `None` when the histogram is empty. Computed at construction.
37 mean: Option<f64>,
38 }
39
40 impl $name {
41 /// Creates a cumulative histogram from its raw parts.
42 ///
43 /// The `count` vector must contain **cumulative** counts (a running prefix
44 /// sum of individual bucket counts).
45 ///
46 /// Returns an error if:
47 /// - `index` and `count` have different lengths
48 /// - any index is out of range for the config
49 /// - the indices are not in strictly ascending order
50 /// - the counts are not strictly non-decreasing
51 /// - any count is zero
52 pub fn from_parts(
53 config: Config,
54 index: Vec<u32>,
55 count: Vec<$count>,
56 ) -> Result<Self, Error> {
57 $ref_name::validate(&config, &index, &count)?;
58 let mean = $ref_name::compute_mean(&config, &index, &count);
59 Ok(Self {
60 config,
61 index,
62 count,
63 mean,
64 })
65 }
66
67 /// Consumes the histogram, returning the config, index, and cumulative
68 /// count vectors.
69 pub fn into_parts(self) -> (Config, Vec<u32>, Vec<$count>) {
70 (self.config, self.index, self.count)
71 }
72
73 /// Returns the bucket configuration.
74 pub fn config(&self) -> Config {
75 self.config
76 }
77
78 /// Returns a slice of the non-zero bucket indices.
79 pub fn index(&self) -> &[u32] {
80 &self.index
81 }
82
83 /// Returns a slice of the cumulative bucket counts.
84 pub fn count(&self) -> &[$count] {
85 &self.count
86 }
87
88 /// Returns the total number of observations across all buckets.
89 pub fn total_count(&self) -> u64 {
90 self.as_ref().total_count()
91 }
92
93 /// Returns the mean of all observations, estimated using bucket
94 /// midpoints, or `None` if the histogram is empty.
95 ///
96 /// This value is computed once at construction time.
97 pub fn mean(&self) -> Option<f64> {
98 self.mean
99 }
100
101 /// Returns the number of non-zero buckets.
102 pub fn len(&self) -> usize {
103 self.index.len()
104 }
105
106 /// Returns `true` if the histogram contains no observations.
107 pub fn is_empty(&self) -> bool {
108 self.index.is_empty()
109 }
110
111 /// Returns the quantile range `(lower, upper)` for the bucket at
112 /// position `bucket_idx` in the sparse representation.
113 ///
114 /// - `lower` is the fraction of observations strictly before this bucket
115 /// (in `[0.0, 1.0]`).
116 /// - `upper` is the fraction of observations at or before this bucket
117 /// (in `[0.0, 1.0]`).
118 ///
119 /// Returns `None` if the histogram is empty or `bucket_idx` is out of
120 /// range.
121 pub fn bucket_quantile_range(&self, bucket_idx: usize) -> Option<(f64, f64)> {
122 self.as_ref().bucket_quantile_range(bucket_idx)
123 }
124
125 /// Returns an iterator yielding `(Bucket, lower_quantile, upper_quantile)`
126 /// for each non-zero bucket.
127 ///
128 /// Each `Bucket` contains the **individual** (non-cumulative) count.
129 /// The quantile range `(lower, upper)` indicates the fraction of total
130 /// observations before and up to this bucket.
131 pub fn iter_with_quantiles(&self) -> $qr_iter<'_> {
132 self.as_ref().iter_with_quantiles()
133 }
134
135 /// Returns an iterator across the non-zero histogram buckets.
136 ///
137 /// Each `Bucket` contains the **individual** (non-cumulative) count for
138 /// that bucket.
139 pub fn iter(&self) -> $iter<'_> {
140 self.as_ref().iter()
141 }
142
143 /// Compute quantiles for the given values.
144 pub fn quantiles(&self, quantiles: &[f64]) -> Result<Option<QuantilesResult>, Error> {
145 self.as_ref().quantiles(quantiles)
146 }
147
148 /// Compute a single quantile.
149 pub fn quantile(&self, quantile: f64) -> Result<Option<QuantilesResult>, Error> {
150 self.as_ref().quantile(quantile)
151 }
152
153 /// Returns a borrowed view over this histogram's storage.
154 pub fn as_ref(&self) -> $ref_name<'_> {
155 $ref_name::from_parts_with_mean(self.config, &self.index, &self.count, self.mean)
156 }
157 }
158
159 impl SampleQuantiles for $name {
160 fn quantiles(&self, quantiles: &[f64]) -> Result<Option<QuantilesResult>, Error> {
161 self.as_ref().quantiles(quantiles)
162 }
163 }
164
165 impl<'a> IntoIterator for &'a $name {
166 type Item = Bucket;
167 type IntoIter = $iter<'a>;
168
169 fn into_iter(self) -> Self::IntoIter {
170 self.iter()
171 }
172 }
173
174 /// An iterator across the histogram buckets with individual counts.
175 pub struct $iter<'a> {
176 position: usize,
177 config: Config,
178 index: &'a [u32],
179 count: &'a [$count],
180 }
181
182 impl Iterator for $iter<'_> {
183 type Item = Bucket;
184
185 fn next(&mut self) -> Option<Bucket> {
186 if self.position >= self.index.len() {
187 return None;
188 }
189
190 let i = self.position;
191 let individual_count = if i == 0 {
192 self.count[0].as_u128() as u64
193 } else {
194 self.count[i].wrapping_sub(self.count[i - 1]).as_u128() as u64
195 };
196 let bucket = Bucket {
197 count: individual_count,
198 range: self.config.index_to_range(self.index[i] as usize),
199 };
200
201 self.position += 1;
202 Some(bucket)
203 }
204 }
205
206 impl ExactSizeIterator for $iter<'_> {
207 fn len(&self) -> usize {
208 self.index.len() - self.position
209 }
210 }
211
212 impl std::iter::FusedIterator for $iter<'_> {}
213
214 /// An iterator yielding `(Bucket, lower_quantile, upper_quantile)` for each
215 /// non-zero bucket.
216 pub struct $qr_iter<'a> {
217 position: usize,
218 config: Config,
219 index: &'a [u32],
220 count: &'a [$count],
221 total: f64,
222 }
223
224 impl Iterator for $qr_iter<'_> {
225 type Item = (Bucket, f64, f64);
226
227 fn next(&mut self) -> Option<Self::Item> {
228 if self.position >= self.index.len() {
229 return None;
230 }
231
232 let i = self.position;
233 let lower = if i == 0 {
234 0.0
235 } else {
236 self.count[i - 1].as_u128() as f64 / self.total
237 };
238 let upper = self.count[i].as_u128() as f64 / self.total;
239
240 let individual_count = if i == 0 {
241 self.count[0].as_u128() as u64
242 } else {
243 self.count[i].wrapping_sub(self.count[i - 1]).as_u128() as u64
244 };
245 let bucket = Bucket {
246 count: individual_count,
247 range: self.config.index_to_range(self.index[i] as usize),
248 };
249
250 self.position += 1;
251 Some((bucket, lower, upper))
252 }
253 }
254
255 impl ExactSizeIterator for $qr_iter<'_> {
256 fn len(&self) -> usize {
257 self.index.len() - self.position
258 }
259 }
260
261 impl std::iter::FusedIterator for $qr_iter<'_> {}
262
263 impl From<&$hist> for $name {
264 fn from(histogram: &$hist) -> Self {
265 let mut index = Vec::new();
266 let mut count = Vec::new();
267 let mut running_sum: $count = <$count as Count>::ZERO;
268
269 for (idx, &n) in histogram.as_slice().iter().enumerate() {
270 if n != <$count as Count>::ZERO {
271 running_sum = running_sum.wrapping_add(n);
272 index.push(idx as u32);
273 count.push(running_sum);
274 }
275 }
276
277 let mean = $ref_name::compute_mean(&histogram.config(), &index, &count);
278 Self {
279 config: histogram.config(),
280 index,
281 count,
282 mean,
283 }
284 }
285 }
286
287 impl From<&$sparse> for $name {
288 fn from(histogram: &$sparse) -> Self {
289 let mut running_sum: $count = <$count as Count>::ZERO;
290 let cumulative: Vec<$count> = histogram
291 .count()
292 .iter()
293 .map(|&n| {
294 running_sum = running_sum.wrapping_add(n);
295 running_sum
296 })
297 .collect();
298
299 let index = histogram.index().to_vec();
300 let mean = $ref_name::compute_mean(&histogram.config(), &index, &cumulative);
301 Self {
302 config: histogram.config(),
303 index,
304 count: cumulative,
305 mean,
306 }
307 }
308 }
309
310 // ── Borrowed view ─────────────────────────────────────────────────────
311
312 /// A borrowed view over cumulative histogram storage.
313 ///
314 /// Holds references to `index` and `count` slices together with the
315 /// [`Config`], mirroring the read-only API surface of the owned histogram
316 /// type.
317 ///
318 /// The type is [`Copy`] — passing it around is cheap. Use
319 /// `as_ref()` on the owned type or the `From<&Owned>` impl to obtain one.
320 // `mean` is an `f64`, so `Eq` cannot be derived for this type.
321 #[derive(Clone, Copy, Debug, PartialEq)]
322 pub struct $ref_name<'a> {
323 config: Config,
324 index: &'a [u32],
325 count: &'a [$count],
326 /// Midpoint-estimated mean; `None` when empty.
327 mean: Option<f64>,
328 }
329
330 impl<'a> $ref_name<'a> {
331 /// Validates the slice invariants (same semantics as the owned `from_parts`).
332 fn validate(config: &Config, index: &[u32], count: &[$count]) -> Result<(), Error> {
333 if index.len() != count.len() {
334 return Err(Error::IncompatibleParameters);
335 }
336
337 let total_buckets = config.total_buckets();
338 let mut prev_idx = None;
339 for &idx in index {
340 if idx as usize >= total_buckets {
341 return Err(Error::OutOfRange);
342 }
343 if let Some(p) = prev_idx {
344 if idx <= p {
345 return Err(Error::IncompatibleParameters);
346 }
347 }
348 prev_idx = Some(idx);
349 }
350
351 let mut prev_count = None;
352 for &c in count {
353 if c == <$count as Count>::ZERO {
354 return Err(Error::IncompatibleParameters);
355 }
356 if let Some(p) = prev_count {
357 if c < p {
358 return Err(Error::IncompatibleParameters);
359 }
360 }
361 prev_count = Some(c);
362 }
363
364 Ok(())
365 }
366
367 /// Creates a borrowed view, validating all invariants.
368 ///
369 /// Returns the same errors as the owned `from_parts`.
370 pub fn from_parts(
371 config: Config,
372 index: &'a [u32],
373 count: &'a [$count],
374 ) -> Result<Self, Error> {
375 Self::validate(&config, index, count)?;
376 let mean = Self::compute_mean(&config, index, count);
377 Ok(Self {
378 config,
379 index,
380 count,
381 mean,
382 })
383 }
384
385 /// Creates a borrowed view without validating invariants.
386 ///
387 /// # Safety
388 ///
389 /// Caller must ensure `index` and `count` satisfy the same invariants
390 /// as the owned `from_parts`.
391 pub fn from_parts_unchecked(
392 config: Config,
393 index: &'a [u32],
394 count: &'a [$count],
395 ) -> Self {
396 let mean = Self::compute_mean(&config, index, count);
397 Self {
398 config,
399 index,
400 count,
401 mean,
402 }
403 }
404
405 /// Borrowed view with a precomputed mean; used by the owned
406 /// type's `as_ref()` / `From` impls, which already cache it.
407 fn from_parts_with_mean(
408 config: Config,
409 index: &'a [u32],
410 count: &'a [$count],
411 mean: Option<f64>,
412 ) -> Self {
413 Self {
414 config,
415 index,
416 count,
417 mean,
418 }
419 }
420
421 /// Returns the bucket configuration.
422 pub fn config(&self) -> Config {
423 self.config
424 }
425
426 /// Returns a slice of the non-zero bucket indices.
427 pub fn index(&self) -> &'a [u32] {
428 self.index
429 }
430
431 /// Returns a slice of the cumulative bucket counts.
432 pub fn count(&self) -> &'a [$count] {
433 self.count
434 }
435
436 /// Returns the number of non-zero buckets.
437 pub fn len(&self) -> usize {
438 self.index.len()
439 }
440
441 /// Returns `true` if the histogram contains no observations.
442 pub fn is_empty(&self) -> bool {
443 self.index.is_empty()
444 }
445
446 /// Returns the total number of observations across all buckets.
447 pub fn total_count(&self) -> u64 {
448 self.count.last().map(|c| c.as_u128() as u64).unwrap_or(0)
449 }
450
451 /// Returns the quantile range `(lower, upper)` for the bucket at
452 /// position `bucket_idx` in the sparse representation.
453 pub fn bucket_quantile_range(&self, bucket_idx: usize) -> Option<(f64, f64)> {
454 if bucket_idx >= self.count.len() {
455 return None;
456 }
457 let total = self.count.last().map(|c| c.as_u128() as f64)?;
458 if total == 0.0 {
459 return None;
460 }
461 let lower = if bucket_idx == 0 {
462 0.0
463 } else {
464 self.count[bucket_idx - 1].as_u128() as f64 / total
465 };
466 let upper = self.count[bucket_idx].as_u128() as f64 / total;
467 Some((lower, upper))
468 }
469
470 /// Returns an iterator across the non-zero histogram buckets.
471 pub fn iter(&self) -> $iter<'a> {
472 $iter {
473 position: 0,
474 config: self.config,
475 index: self.index,
476 count: self.count,
477 }
478 }
479
480 /// Returns an iterator yielding `(Bucket, lower_quantile, upper_quantile)`
481 /// for each non-zero bucket.
482 pub fn iter_with_quantiles(&self) -> $qr_iter<'a> {
483 let total = self.count.last().map(|c| c.as_u128() as f64).unwrap_or(0.0);
484 $qr_iter {
485 position: 0,
486 config: self.config,
487 index: self.index,
488 count: self.count,
489 total,
490 }
491 }
492
493 /// Compute quantiles for the given values.
494 pub fn quantiles(&self, quantiles: &[f64]) -> Result<Option<QuantilesResult>, Error> {
495 <Self as SampleQuantiles>::quantiles(self, quantiles)
496 }
497
498 /// Compute a single quantile.
499 pub fn quantile(&self, quantile: f64) -> Result<Option<QuantilesResult>, Error> {
500 <Self as SampleQuantiles>::quantile(self, quantile)
501 }
502
503 /// Returns the midpoint-estimated mean, or `None` if empty.
504 ///
505 /// Stored on the view, so this is a cheap field access like
506 /// [`count`](Self::count) — no per-call computation.
507 pub fn mean(&self) -> Option<f64> {
508 self.mean
509 }
510
511 /// Computes the mean of all observations using bucket midpoints.
512 ///
513 /// `count` holds cumulative counts. Returns `None` when there are
514 /// no observations.
515 fn compute_mean(config: &Config, index: &[u32], count: &[$count]) -> Option<f64> {
516 let total = count.last()?.as_u128();
517 if total == 0 {
518 return None;
519 }
520
521 let mut weighted_sum = 0.0_f64;
522 for i in 0..index.len() {
523 let individual = Self::individual_count(count, i) as f64;
524 let range = config.index_to_range(index[i] as usize);
525 let midpoint = (*range.start() as f64 + *range.end() as f64) / 2.0;
526 weighted_sum += midpoint * individual;
527 }
528
529 Some(weighted_sum / total as f64)
530 }
531
532 /// Returns the individual (non-cumulative) count at the given position.
533 fn individual_count(count: &[$count], position: usize) -> u64 {
534 if position == 0 {
535 count[0].as_u128() as u64
536 } else {
537 count[position].wrapping_sub(count[position - 1]).as_u128() as u64
538 }
539 }
540
541 /// Find the first position where cumulative count >= target.
542 fn find_quantile_position(count: &[$count], target: u128) -> usize {
543 const CACHE_LINE_ENTRIES: usize = 64 / std::mem::size_of::<$count>();
544 if count.len() <= CACHE_LINE_ENTRIES {
545 for (i, c) in count.iter().enumerate() {
546 if c.as_u128() >= target {
547 return i;
548 }
549 }
550 count.len() - 1
551 } else {
552 let pos = count.partition_point(|c| c.as_u128() < target);
553 pos.min(count.len() - 1)
554 }
555 }
556 }
557
558 impl SampleQuantiles for $ref_name<'_> {
559 fn quantiles(&self, quantiles: &[f64]) -> Result<Option<QuantilesResult>, Error> {
560 // Validate all quantile values
561 for q in quantiles {
562 if !(0.0..=1.0).contains(q) {
563 return Err(Error::InvalidQuantile);
564 }
565 }
566
567 // Empty histogram
568 if self.count.is_empty() {
569 return Ok(None);
570 }
571
572 let total_count = self.count.last().unwrap().as_u128();
573 if total_count == 0 {
574 return Ok(None);
575 }
576
577 // Sort and dedup requested quantiles
578 let mut sorted: Vec<Quantile> = quantiles
579 .iter()
580 .map(|&q| Quantile::new(q).unwrap())
581 .collect();
582 sorted.sort();
583 sorted.dedup();
584
585 // min/max from first and last entries
586 let min = Bucket {
587 count: Self::individual_count(self.count, 0),
588 range: self.config.index_to_range(self.index[0] as usize),
589 };
590 let last = self.count.len() - 1;
591 let max = Bucket {
592 count: Self::individual_count(self.count, last),
593 range: self.config.index_to_range(self.index[last] as usize),
594 };
595
596 // Find bucket for each quantile
597 let mut entries = BTreeMap::new();
598 for quantile in &sorted {
599 let target = std::cmp::max(
600 1u128,
601 (quantile.as_f64() * total_count as f64).ceil() as u128,
602 );
603
604 let pos = Self::find_quantile_position(self.count, target);
605
606 entries.insert(
607 *quantile,
608 Bucket {
609 count: Self::individual_count(self.count, pos),
610 range: self.config.index_to_range(self.index[pos] as usize),
611 },
612 );
613 }
614
615 Ok(Some(QuantilesResult::new(entries, total_count, min, max)))
616 }
617 }
618
619 impl<'a> From<&'a $name> for $ref_name<'a> {
620 fn from(h: &'a $name) -> Self {
621 Self::from_parts_with_mean(h.config(), h.index(), h.count(), h.mean())
622 }
623 }
624
625 impl<'a> IntoIterator for $ref_name<'a> {
626 type Item = Bucket;
627 type IntoIter = $iter<'a>;
628
629 fn into_iter(self) -> Self::IntoIter {
630 self.iter()
631 }
632 }
633
634 impl<'a, 'b> IntoIterator for &'a $ref_name<'b> {
635 type Item = Bucket;
636 type IntoIter = $iter<'b>;
637
638 fn into_iter(self) -> Self::IntoIter {
639 self.iter()
640 }
641 }
642 };
643 }
644
645 define_cumulative_histogram!(
646 CumulativeROHistogram,
647 CumulativeROHistogramRef,
648 CumulativeIter,
649 QuantileRangeIter,
650 Histogram,
651 SparseHistogram,
652 u64
653 );
654 define_cumulative_histogram!(
655 CumulativeROHistogram32,
656 CumulativeROHistogram32Ref,
657 CumulativeIter32,
658 QuantileRangeIter32,
659 Histogram32,
660 SparseHistogram32,
661 u32
662 );
663
664 #[cfg(test)]
665 mod tests {
666 use super::*;
667
668 #[test]
669 fn from_histogram() {
670 let mut h = Histogram::new(7, 64).unwrap();
671 h.increment(1).unwrap();
672 h.increment(1).unwrap();
673 h.increment(5).unwrap();
674 h.increment(100).unwrap();
675
676 let croh = CumulativeROHistogram::from(&h);
677 assert_eq!(croh.config(), h.config());
678 // Three distinct buckets: index 1 (count 2), index 5 (count 1), index 100 (count 1)
679 assert_eq!(croh.index().len(), 3);
680 // Cumulative: [2, 3, 4]
681 assert_eq!(croh.count(), &[2, 3, 4]);
682 assert_eq!(croh.total_count(), 4);
683 }
684
685 #[test]
686 fn from_sparse() {
687 let config = Config::new(7, 32).unwrap();
688 let sparse = SparseHistogram::from_parts(config, vec![1, 3, 5], vec![6, 12, 7]).unwrap();
689
690 let croh = CumulativeROHistogram::from(&sparse);
691 assert_eq!(croh.config(), config);
692 assert_eq!(croh.index(), &[1, 3, 5]);
693 // Cumulative: [6, 18, 25]
694 assert_eq!(croh.count(), &[6, 18, 25]);
695 assert_eq!(croh.total_count(), 25);
696 }
697
698 #[test]
699 fn quantiles_match_histogram() {
700 let mut h = Histogram::new(4, 10).unwrap();
701 for v in 1..1024 {
702 h.increment(v).unwrap();
703 }
704
705 let sparse = SparseHistogram::from(&h);
706 let croh = CumulativeROHistogram::from(&h);
707
708 let quantiles = &[0.0, 0.01, 0.1, 0.25, 0.5, 0.75, 0.9, 0.99, 0.999, 1.0];
709
710 let hr = h.quantiles(quantiles).unwrap().unwrap();
711 let sr = sparse.quantiles(quantiles).unwrap().unwrap();
712 let cr = croh.quantiles(quantiles).unwrap().unwrap();
713
714 assert_eq!(hr.total_count(), cr.total_count());
715 assert_eq!(sr.total_count(), cr.total_count());
716 assert_eq!(hr.min().range(), cr.min().range());
717 assert_eq!(hr.max().range(), cr.max().range());
718
719 for ((hq, sq), cq) in hr
720 .entries()
721 .iter()
722 .zip(sr.entries().iter())
723 .zip(cr.entries().iter())
724 {
725 assert_eq!(hq.0, cq.0);
726 assert_eq!(sq.0, cq.0);
727 assert_eq!(hq.1.range(), cq.1.range());
728 assert_eq!(sq.1.range(), cq.1.range());
729 assert_eq!(hq.1.count(), cq.1.count());
730 }
731 }
732
733 #[test]
734 fn mean_from_parts() {
735 let config = Config::new(7, 32).unwrap();
736 // Buckets 0, 1, 2 map to single-value ranges 0, 1, 2.
737 // Individual counts: [2, 3, 5] (cumulative [2, 5, 10]).
738 // Mean = (0*2 + 1*3 + 2*5) / 10 = 13 / 10 = 1.3
739 let croh =
740 CumulativeROHistogram::from_parts(config, vec![0, 1, 2], vec![2, 5, 10]).unwrap();
741 let mean = croh.mean().unwrap();
742 assert!((mean - 1.3).abs() < 1e-9, "mean was {mean}");
743 }
744
745 #[test]
746 fn mean_uses_bucket_midpoint() {
747 let config = Config::new(7, 32).unwrap();
748 // index 384 -> range 512..=515, midpoint 513.5
749 let range = config.index_to_range(384);
750 let expected = (*range.start() as f64 + *range.end() as f64) / 2.0;
751 let croh = CumulativeROHistogram::from_parts(config, vec![384], vec![4]).unwrap();
752 assert!((croh.mean().unwrap() - expected).abs() < 1e-9);
753 }
754
755 #[test]
756 fn mean_empty_is_none() {
757 let config = Config::new(7, 32).unwrap();
758 let croh = CumulativeROHistogram::from_parts(config, vec![], vec![]).unwrap();
759 assert_eq!(croh.mean(), None);
760
761 let h = Histogram::new(7, 64).unwrap();
762 assert_eq!(CumulativeROHistogram::from(&h).mean(), None);
763 }
764
765 #[test]
766 fn mean_matches_across_constructors() {
767 let mut h = Histogram::new(7, 64).unwrap();
768 for v in [1, 1, 5, 5, 5, 100, 250, 999] {
769 h.increment(v).unwrap();
770 }
771 let from_hist = CumulativeROHistogram::from(&h);
772 let from_sparse = CumulativeROHistogram::from(&SparseHistogram::from(&h));
773
774 let a = from_hist.mean().unwrap();
775 let b = from_sparse.mean().unwrap();
776 assert!((a - b).abs() < 1e-9, "{a} vs {b}");
777
778 // Independently compute expected mean via the iterator over buckets.
779 let mut weighted = 0.0_f64;
780 let mut total = 0.0_f64;
781 for bucket in from_hist.iter() {
782 let mid = (bucket.start() as f64 + bucket.end() as f64) / 2.0;
783 weighted += mid * bucket.count() as f64;
784 total += bucket.count() as f64;
785 }
786 assert!((a - weighted / total).abs() < 1e-9);
787 }
788
789 #[test]
790 fn mean_u32() {
791 let config = Config::new(7, 32).unwrap();
792 let croh =
793 CumulativeROHistogram32::from_parts(config, vec![0, 1, 2], vec![2u32, 5, 10]).unwrap();
794 assert!((croh.mean().unwrap() - 1.3).abs() < 1e-9);
795 }
796
797 #[test]
798 fn empty_histogram() {
799 let h = Histogram::new(7, 64).unwrap();
800 let croh = CumulativeROHistogram::from(&h);
801
802 assert!(croh.is_empty());
803 assert_eq!(croh.len(), 0);
804 assert_eq!(croh.total_count(), 0);
805 assert_eq!(croh.quantiles(&[0.5]).unwrap(), None);
806 assert_eq!(croh.quantile(0.5).unwrap(), None);
807 }
808
809 #[test]
810 fn single_sample() {
811 let mut h = Histogram::new(7, 64).unwrap();
812 h.increment(42).unwrap();
813
814 let croh = CumulativeROHistogram::from(&h);
815 assert_eq!(croh.len(), 1);
816 assert_eq!(croh.total_count(), 1);
817
818 let result = croh.quantile(0.0).unwrap().unwrap();
819 assert_eq!(result.min().end(), 42);
820
821 let result = croh.quantile(1.0).unwrap().unwrap();
822 assert_eq!(result.max().end(), 42);
823
824 let result = croh.quantile(0.5).unwrap().unwrap();
825 let q = Quantile::new(0.5).unwrap();
826 assert_eq!(result.get(&q).unwrap().end(), 42);
827 }
828
829 #[test]
830 fn from_parts_validation() {
831 let config = Config::new(7, 32).unwrap();
832
833 // Mismatched lengths
834 assert_eq!(
835 CumulativeROHistogram::from_parts(config, vec![1, 2], vec![1]),
836 Err(Error::IncompatibleParameters)
837 );
838
839 // Out of range index
840 assert_eq!(
841 CumulativeROHistogram::from_parts(config, vec![u32::MAX], vec![1]),
842 Err(Error::OutOfRange)
843 );
844
845 // Non-ascending indices
846 assert_eq!(
847 CumulativeROHistogram::from_parts(config, vec![3, 1], vec![1, 2]),
848 Err(Error::IncompatibleParameters)
849 );
850
851 // Duplicate indices
852 assert_eq!(
853 CumulativeROHistogram::from_parts(config, vec![1, 1], vec![1, 2]),
854 Err(Error::IncompatibleParameters)
855 );
856
857 // Non-non-decreasing counts
858 assert_eq!(
859 CumulativeROHistogram::from_parts(config, vec![1, 3], vec![5, 3]),
860 Err(Error::IncompatibleParameters)
861 );
862
863 // Zero count
864 assert_eq!(
865 CumulativeROHistogram::from_parts(config, vec![1], vec![0]),
866 Err(Error::IncompatibleParameters)
867 );
868
869 // Valid
870 assert!(CumulativeROHistogram::from_parts(config, vec![1, 3, 5], vec![6, 18, 25]).is_ok());
871
872 // Empty is valid
873 assert!(CumulativeROHistogram::from_parts(config, vec![], vec![]).is_ok());
874 }
875
876 #[test]
877 fn quantile_ranges() {
878 let config = Config::new(7, 32).unwrap();
879 // 3 buckets with individual counts 10, 30, 60 → cumulative [10, 40, 100]
880 let croh =
881 CumulativeROHistogram::from_parts(config, vec![1, 3, 5], vec![10, 40, 100]).unwrap();
882
883 // Bucket 0: [0.0, 0.1)
884 let (lo, hi) = croh.bucket_quantile_range(0).unwrap();
885 assert!((lo - 0.0).abs() < f64::EPSILON);
886 assert!((hi - 0.1).abs() < f64::EPSILON);
887
888 // Bucket 1: [0.1, 0.4)
889 let (lo, hi) = croh.bucket_quantile_range(1).unwrap();
890 assert!((lo - 0.1).abs() < f64::EPSILON);
891 assert!((hi - 0.4).abs() < f64::EPSILON);
892
893 // Bucket 2: [0.4, 1.0]
894 let (lo, hi) = croh.bucket_quantile_range(2).unwrap();
895 assert!((lo - 0.4).abs() < f64::EPSILON);
896 assert!((hi - 1.0).abs() < f64::EPSILON);
897
898 // Out of range
899 assert_eq!(croh.bucket_quantile_range(3), None);
900
901 // Empty histogram
902 let empty = CumulativeROHistogram::from_parts(config, vec![], vec![]).unwrap();
903 assert_eq!(empty.bucket_quantile_range(0), None);
904 }
905
906 #[test]
907 fn iter_with_quantiles() {
908 let config = Config::new(7, 32).unwrap();
909 let croh =
910 CumulativeROHistogram::from_parts(config, vec![1, 3, 5], vec![10, 40, 100]).unwrap();
911
912 let items: Vec<_> = croh.iter_with_quantiles().collect();
913 assert_eq!(items.len(), 3);
914
915 // Check individual counts
916 assert_eq!(items[0].0.count(), 10);
917 assert_eq!(items[1].0.count(), 30);
918 assert_eq!(items[2].0.count(), 60);
919
920 // Check quantile ranges
921 assert!((items[0].1 - 0.0).abs() < f64::EPSILON);
922 assert!((items[0].2 - 0.1).abs() < f64::EPSILON);
923 assert!((items[1].1 - 0.1).abs() < f64::EPSILON);
924 assert!((items[1].2 - 0.4).abs() < f64::EPSILON);
925 assert!((items[2].1 - 0.4).abs() < f64::EPSILON);
926 assert!((items[2].2 - 1.0).abs() < f64::EPSILON);
927 }
928
929 #[test]
930 fn iter_individual_counts() {
931 let mut h = Histogram::new(7, 64).unwrap();
932 h.increment(1).unwrap();
933 h.increment(1).unwrap();
934 h.increment(5).unwrap();
935 h.increment(100).unwrap();
936
937 let sparse = SparseHistogram::from(&h);
938 let croh = CumulativeROHistogram::from(&h);
939
940 let sparse_buckets: Vec<_> = sparse.iter().collect();
941 let croh_buckets: Vec<_> = croh.iter().collect();
942
943 assert_eq!(sparse_buckets.len(), croh_buckets.len());
944 for (sb, cb) in sparse_buckets.iter().zip(croh_buckets.iter()) {
945 assert_eq!(sb.count(), cb.count());
946 assert_eq!(sb.range(), cb.range());
947 }
948 }
949
950 #[test]
951 fn into_parts_roundtrip() {
952 let config = Config::new(7, 32).unwrap();
953 let original =
954 CumulativeROHistogram::from_parts(config, vec![1, 3, 5], vec![6, 18, 25]).unwrap();
955
956 let (cfg, idx, cnt) = original.clone().into_parts();
957 let reconstructed = CumulativeROHistogram::from_parts(cfg, idx, cnt).unwrap();
958
959 assert_eq!(original, reconstructed);
960 }
961
962 #[test]
963 fn invalid_quantile_returns_error() {
964 let config = Config::new(7, 32).unwrap();
965 let croh = CumulativeROHistogram::from_parts(config, vec![1], vec![5]).unwrap();
966
967 assert_eq!(croh.quantiles(&[1.5]), Err(Error::InvalidQuantile));
968 assert_eq!(croh.quantiles(&[-0.1]), Err(Error::InvalidQuantile));
969 }
970
971 #[test]
972 fn from_histogram_u32() {
973 let mut h = Histogram32::new(7, 64).unwrap();
974 h.increment(1).unwrap();
975 h.increment(1).unwrap();
976 h.increment(5).unwrap();
977 h.increment(100).unwrap();
978 let croh = CumulativeROHistogram32::from(&h);
979 assert_eq!(croh.index().len(), 3);
980 assert_eq!(croh.count(), &[2u32, 3, 4]);
981 assert_eq!(croh.total_count(), 4);
982 }
983
984 #[test]
985 fn from_parts_u32() {
986 let config = Config::new(7, 32).unwrap();
987 let croh =
988 CumulativeROHistogram32::from_parts(config, vec![1, 3, 5], vec![6u32, 18, 25]).unwrap();
989 assert_eq!(croh.total_count(), 25);
990 }
991
992 #[test]
993 fn quantiles_u32_match_u64() {
994 let mut h32 = Histogram32::new(4, 10).unwrap();
995 let mut h64 = Histogram::new(4, 10).unwrap();
996 for v in 1..1024u64 {
997 h32.increment(v).unwrap();
998 h64.increment(v).unwrap();
999 }
1000 let c32 = CumulativeROHistogram32::from(&h32);
1001 let c64 = CumulativeROHistogram::from(&h64);
1002 let qs = &[0.0, 0.5, 0.99, 1.0];
1003 let r32 = c32.quantiles(qs).unwrap().unwrap();
1004 let r64 = c64.quantiles(qs).unwrap().unwrap();
1005 for ((q32, _), (q64, _)) in r32.entries().iter().zip(r64.entries().iter()) {
1006 assert_eq!(q32, q64);
1007 }
1008 }
1009
1010 // ── Ref type tests ────────────────────────────────────────────────────────
1011
1012 #[test]
1013 fn ref_validation_parity_u64() {
1014 let config = Config::new(7, 32).unwrap();
1015
1016 // Mismatched lengths
1017 assert_eq!(
1018 CumulativeROHistogramRef::from_parts(config, &[1u32, 2], &[1u64]),
1019 Err(Error::IncompatibleParameters)
1020 );
1021
1022 // Out of range index
1023 assert_eq!(
1024 CumulativeROHistogramRef::from_parts(config, &[u32::MAX], &[1u64]),
1025 Err(Error::OutOfRange)
1026 );
1027
1028 // Non-ascending indices
1029 assert_eq!(
1030 CumulativeROHistogramRef::from_parts(config, &[3u32, 1], &[1u64, 2]),
1031 Err(Error::IncompatibleParameters)
1032 );
1033
1034 // Duplicate indices
1035 assert_eq!(
1036 CumulativeROHistogramRef::from_parts(config, &[1u32, 1], &[1u64, 2]),
1037 Err(Error::IncompatibleParameters)
1038 );
1039
1040 // Non-monotone counts
1041 assert_eq!(
1042 CumulativeROHistogramRef::from_parts(config, &[1u32, 3], &[5u64, 3]),
1043 Err(Error::IncompatibleParameters)
1044 );
1045
1046 // Zero count
1047 assert_eq!(
1048 CumulativeROHistogramRef::from_parts(config, &[1u32], &[0u64]),
1049 Err(Error::IncompatibleParameters)
1050 );
1051
1052 // Valid
1053 assert!(
1054 CumulativeROHistogramRef::from_parts(config, &[1u32, 3, 5], &[6u64, 18, 25]).is_ok()
1055 );
1056
1057 // Empty
1058 assert!(CumulativeROHistogramRef::from_parts(config, &[], &[]).is_ok());
1059 }
1060
1061 #[test]
1062 fn ref_validation_parity_u32() {
1063 let config = Config::new(7, 32).unwrap();
1064
1065 assert_eq!(
1066 CumulativeROHistogram32Ref::from_parts(config, &[1u32, 2], &[1u32]),
1067 Err(Error::IncompatibleParameters)
1068 );
1069 assert_eq!(
1070 CumulativeROHistogram32Ref::from_parts(config, &[u32::MAX], &[1u32]),
1071 Err(Error::OutOfRange)
1072 );
1073 assert_eq!(
1074 CumulativeROHistogram32Ref::from_parts(config, &[3u32, 1], &[1u32, 2]),
1075 Err(Error::IncompatibleParameters)
1076 );
1077 assert_eq!(
1078 CumulativeROHistogram32Ref::from_parts(config, &[1u32, 3], &[5u32, 3]),
1079 Err(Error::IncompatibleParameters)
1080 );
1081 assert_eq!(
1082 CumulativeROHistogram32Ref::from_parts(config, &[1u32], &[0u32]),
1083 Err(Error::IncompatibleParameters)
1084 );
1085 assert!(
1086 CumulativeROHistogram32Ref::from_parts(config, &[1u32, 3, 5], &[6u32, 18, 25]).is_ok()
1087 );
1088 }
1089
1090 #[test]
1091 fn ref_quantile_parity_u64() {
1092 let config = Config::new(7, 32).unwrap();
1093 let owned =
1094 CumulativeROHistogram::from_parts(config, vec![1, 3, 5], vec![10u64, 40, 100]).unwrap();
1095 let r = CumulativeROHistogramRef::from_parts(config, owned.index(), owned.count()).unwrap();
1096
1097 let qs = &[0.0, 0.5, 0.99, 1.0];
1098 assert_eq!(owned.quantiles(qs).unwrap(), r.quantiles(qs).unwrap());
1099 }
1100
1101 #[test]
1102 fn ref_quantile_parity_u32() {
1103 let config = Config::new(7, 32).unwrap();
1104 let owned =
1105 CumulativeROHistogram32::from_parts(config, vec![1, 3, 5], vec![10u32, 40, 100])
1106 .unwrap();
1107 let r =
1108 CumulativeROHistogram32Ref::from_parts(config, owned.index(), owned.count()).unwrap();
1109
1110 let qs = &[0.0, 0.5, 0.99, 1.0];
1111 assert_eq!(owned.quantiles(qs).unwrap(), r.quantiles(qs).unwrap());
1112 }
1113
1114 #[test]
1115 fn ref_from_parts_unchecked_matches_owned() {
1116 let config = Config::new(7, 32).unwrap();
1117 let owned =
1118 CumulativeROHistogram::from_parts(config, vec![1, 3, 5], vec![10u64, 40, 100]).unwrap();
1119 let r =
1120 CumulativeROHistogramRef::from_parts_unchecked(config, owned.index(), owned.count());
1121
1122 let qs = &[0.25, 0.5, 0.75];
1123 assert_eq!(owned.quantiles(qs).unwrap(), r.quantiles(qs).unwrap());
1124 }
1125
1126 #[test]
1127 fn ref_from_owned_round_trip() {
1128 let config = Config::new(7, 32).unwrap();
1129 let owned =
1130 CumulativeROHistogram::from_parts(config, vec![1, 3, 5], vec![10u64, 40, 100]).unwrap();
1131 let r = CumulativeROHistogramRef::from(&owned);
1132
1133 let qs = &[0.0, 0.5, 1.0];
1134 assert_eq!(r.quantiles(qs).unwrap(), owned.quantiles(qs).unwrap());
1135 }
1136
1137 #[test]
1138 fn ref_iter_agrees_with_owned() {
1139 let config = Config::new(7, 32).unwrap();
1140 let owned =
1141 CumulativeROHistogram::from_parts(config, vec![1, 3, 5], vec![10u64, 40, 100]).unwrap();
1142 let r = CumulativeROHistogramRef::from(&owned);
1143
1144 let owned_buckets: Vec<_> = owned.iter().collect();
1145 let ref_buckets: Vec<_> = r.iter().collect();
1146 assert_eq!(owned_buckets, ref_buckets);
1147 }
1148
1149 #[test]
1150 fn ref_iter_with_quantiles_agrees_with_owned() {
1151 let config = Config::new(7, 32).unwrap();
1152 let owned =
1153 CumulativeROHistogram::from_parts(config, vec![1, 3, 5], vec![10u64, 40, 100]).unwrap();
1154 let r = CumulativeROHistogramRef::from(&owned);
1155
1156 let owned_items: Vec<_> = owned.iter_with_quantiles().collect();
1157 let ref_items: Vec<_> = r.iter_with_quantiles().collect();
1158 assert_eq!(owned_items.len(), ref_items.len());
1159 for (a, b) in owned_items.iter().zip(ref_items.iter()) {
1160 assert_eq!(a.0, b.0);
1161 assert!((a.1 - b.1).abs() < f64::EPSILON);
1162 assert!((a.2 - b.2).abs() < f64::EPSILON);
1163 }
1164 }
1165
1166 #[test]
1167 fn ref_bucket_quantile_range_parity() {
1168 let config = Config::new(7, 32).unwrap();
1169 let owned =
1170 CumulativeROHistogram::from_parts(config, vec![1, 3, 5], vec![10u64, 40, 100]).unwrap();
1171 let r = CumulativeROHistogramRef::from(&owned);
1172
1173 for i in 0..=3 {
1174 assert_eq!(owned.bucket_quantile_range(i), r.bucket_quantile_range(i));
1175 }
1176 }
1177
1178 #[test]
1179 fn ref_empty_edge_case() {
1180 let config = Config::new(7, 32).unwrap();
1181 let r = CumulativeROHistogramRef::from_parts(config, &[], &[]).unwrap();
1182 assert!(r.is_empty());
1183 assert_eq!(r.len(), 0);
1184 assert_eq!(r.total_count(), 0);
1185 assert_eq!(r.quantiles(&[0.5]).unwrap(), None);
1186 assert_eq!(r.bucket_quantile_range(0), None);
1187 }
1188
1189 #[test]
1190 fn ref_single_sample_edge_case() {
1191 let mut h = Histogram::new(7, 64).unwrap();
1192 h.increment(42).unwrap();
1193 let owned = CumulativeROHistogram::from(&h);
1194 let r = CumulativeROHistogramRef::from(&owned);
1195
1196 assert_eq!(r.len(), 1);
1197 assert_eq!(r.total_count(), 1);
1198 let result = r.quantile(0.5).unwrap().unwrap();
1199 let q = Quantile::new(0.5).unwrap();
1200 assert_eq!(result.get(&q).unwrap().end(), 42);
1201 }
1202
1203 #[test]
1204 fn ref_into_iterator() {
1205 let config = Config::new(7, 32).unwrap();
1206 let owned =
1207 CumulativeROHistogram::from_parts(config, vec![1, 3, 5], vec![10u64, 40, 100]).unwrap();
1208 let r = CumulativeROHistogramRef::from(&owned);
1209
1210 // IntoIterator for owned ref (consumes)
1211 let buckets_consumed: Vec<_> = r.into_iter().collect();
1212 // IntoIterator for &ref (borrows)
1213 let buckets_borrowed: Vec<_> = (&r).into_iter().collect();
1214 let owned_buckets: Vec<_> = owned.iter().collect();
1215
1216 assert_eq!(buckets_consumed, owned_buckets);
1217 assert_eq!(buckets_borrowed, owned_buckets);
1218 }
1219
1220 #[test]
1221 fn ref_u32_symmetry() {
1222 let config = Config::new(7, 32).unwrap();
1223 let owned =
1224 CumulativeROHistogram32::from_parts(config, vec![1, 3, 5], vec![10u32, 40, 100])
1225 .unwrap();
1226 let r = CumulativeROHistogram32Ref::from(&owned);
1227
1228 // Iter parity
1229 let owned_buckets: Vec<_> = owned.iter().collect();
1230 let ref_buckets: Vec<_> = r.iter().collect();
1231 assert_eq!(owned_buckets, ref_buckets);
1232
1233 // Quantile parity
1234 let qs = &[0.0, 0.5, 0.99, 1.0];
1235 assert_eq!(owned.quantiles(qs).unwrap(), r.quantiles(qs).unwrap());
1236
1237 // bucket_quantile_range parity
1238 for i in 0..=3 {
1239 assert_eq!(owned.bucket_quantile_range(i), r.bucket_quantile_range(i));
1240 }
1241 }
1242
1243 #[test]
1244 fn ref_as_ref_method() {
1245 let config = Config::new(7, 32).unwrap();
1246 let owned =
1247 CumulativeROHistogram::from_parts(config, vec![1, 3, 5], vec![10u64, 40, 100]).unwrap();
1248 let r = owned.as_ref();
1249
1250 let qs = &[0.5, 0.99];
1251 assert_eq!(owned.quantiles(qs).unwrap(), r.quantiles(qs).unwrap());
1252 }
1253
1254 #[test]
1255 fn ref_mean_parity_u64() {
1256 let config = Config::new(7, 32).unwrap();
1257 let owned =
1258 CumulativeROHistogram::from_parts(config, vec![0, 1, 2], vec![2u64, 5, 10]).unwrap();
1259 let r = CumulativeROHistogramRef::from(&owned);
1260 assert_eq!(owned.mean(), r.mean());
1261 assert!((r.mean().unwrap() - 1.3).abs() < 1e-9);
1262 }
1263
1264 #[test]
1265 fn ref_mean_parity_u32() {
1266 let config = Config::new(7, 32).unwrap();
1267 let owned =
1268 CumulativeROHistogram32::from_parts(config, vec![0, 1, 2], vec![2u32, 5, 10]).unwrap();
1269 let r = CumulativeROHistogram32Ref::from(&owned);
1270 assert_eq!(owned.mean(), r.mean());
1271 }
1272
1273 #[test]
1274 fn ref_mean_empty_is_none() {
1275 let config = Config::new(7, 32).unwrap();
1276 let r = CumulativeROHistogramRef::from_parts(config, &[], &[]).unwrap();
1277 assert_eq!(r.mean(), None);
1278 }
1279
1280 #[test]
1281 fn ref_sample_quantiles_trait() {
1282 use crate::quantile::SampleQuantiles;
1283 let config = Config::new(7, 32).unwrap();
1284 let owned =
1285 CumulativeROHistogram::from_parts(config, vec![1, 3, 5], vec![10u64, 40, 100]).unwrap();
1286 let r = CumulativeROHistogramRef::from(&owned);
1287
1288 let qs = &[0.25, 0.75];
1289 assert_eq!(
1290 SampleQuantiles::quantiles(&r, qs).unwrap(),
1291 SampleQuantiles::quantiles(&owned, qs).unwrap()
1292 );
1293 }
1294 }