Debian Codegraph @

src/sparse.rs

raw symbols SCIP
1 use std::collections::BTreeMap;
2
3 use crate::quantile::{Quantile, QuantilesResult, SampleQuantiles};
4 use crate::{Bucket, Config, Count, Error, Histogram, Histogram32};
5
6 macro_rules! define_sparse_histogram {
7 ($name:ident, $ref_name:ident, $iter:ident, $hist:ident, $count:ty) => {
8 /// A sparse, columnar representation of a histogram.
9 ///
10 /// Significantly smaller than the dense form when many buckets are
11 /// zero. Each non-zero bucket is stored as a pair `(index[i],
12 /// count[i])` where `index[i]` is the bucket index and `count[i]`
13 /// is its count, in ascending index order.
14 #[derive(Clone, Debug, PartialEq, Eq)]
15 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
17 pub struct $name {
18 pub(crate) config: Config,
19 pub(crate) index: Vec<u32>,
20 pub(crate) count: Vec<$count>,
21 }
22
23 impl $name {
24 /// Construct a new histogram from the provided parameters.
25 pub fn new(grouping_power: u8, max_value_power: u8) -> Result<Self, Error> {
26 let config = Config::new(grouping_power, max_value_power)?;
27 Ok(Self::with_config(&config))
28 }
29
30 /// Creates a new histogram using a provided [`crate::Config`].
31 pub fn with_config(config: &Config) -> Self {
32 Self {
33 config: *config,
34 index: Vec::new(),
35 count: Vec::new(),
36 }
37 }
38
39 /// Creates a sparse histogram from its raw parts.
40 ///
41 /// Returns an error if:
42 /// - `index` and `count` have different lengths
43 /// - any index is out of range for the config
44 /// - the indices are not in strictly ascending order
45 pub fn from_parts(
46 config: Config,
47 index: Vec<u32>,
48 count: Vec<$count>,
49 ) -> Result<Self, Error> {
50 $ref_name::validate(&config, &index, &count)?;
51 Ok(Self {
52 config,
53 index,
54 count,
55 })
56 }
57
58 /// Consumes the histogram, returning the config, index, and count vectors.
59 pub fn into_parts(self) -> (Config, Vec<u32>, Vec<$count>) {
60 (self.config, self.index, self.count)
61 }
62
63 /// Returns the bucket configuration.
64 pub fn config(&self) -> Config {
65 self.config
66 }
67
68 /// Returns a slice of the non-zero bucket indices.
69 pub fn index(&self) -> &[u32] {
70 &self.index
71 }
72
73 /// Returns a slice of the bucket counts.
74 pub fn count(&self) -> &[$count] {
75 &self.count
76 }
77
78 /// Returns the number of non-zero buckets.
79 pub fn len(&self) -> usize {
80 self.index.len()
81 }
82
83 /// Returns `true` if the histogram contains no observations.
84 pub fn is_empty(&self) -> bool {
85 self.index.is_empty()
86 }
87
88 /// Helper function to store a bucket in the histogram.
89 fn add_bucket(&mut self, idx: u32, n: $count) {
90 if n != <$count as Count>::ZERO {
91 self.index.push(idx);
92 self.count.push(n);
93 }
94 }
95
96 /// Adds the other histogram to this histogram and returns the result as a
97 /// new histogram.
98 ///
99 /// Returns `Err(Error::IncompatibleParameters)` if the configs don't match,
100 /// or `Err(Error::Overflow)` if any bucket overflows.
101 #[allow(clippy::comparison_chain)]
102 pub fn checked_add(&self, h: &Self) -> Result<Self, Error> {
103 if self.config != h.config {
104 return Err(Error::IncompatibleParameters);
105 }
106
107 let mut histogram = Self::with_config(&self.config);
108
109 let (mut i, mut j) = (0, 0);
110 while i < self.index.len() && j < h.index.len() {
111 let (k1, v1) = (self.index[i], self.count[i]);
112 let (k2, v2) = (h.index[j], h.count[j]);
113
114 if k1 == k2 {
115 let v = v1.checked_add(v2).ok_or(Error::Overflow)?;
116 histogram.add_bucket(k1, v);
117 (i, j) = (i + 1, j + 1);
118 } else if k1 < k2 {
119 histogram.add_bucket(k1, v1);
120 i += 1;
121 } else {
122 histogram.add_bucket(k2, v2);
123 j += 1;
124 }
125 }
126
127 if i < self.index.len() {
128 histogram.index.extend(&self.index[i..]);
129 histogram.count.extend(&self.count[i..]);
130 }
131
132 if j < h.index.len() {
133 histogram.index.extend(&h.index[j..]);
134 histogram.count.extend(&h.count[j..]);
135 }
136
137 Ok(histogram)
138 }
139
140 /// Adds the other histogram to this histogram and returns the result as a
141 /// new histogram.
142 ///
143 /// Returns `Err(Error::IncompatibleParameters)` if the configs don't match.
144 /// Buckets which have values in both histograms are allowed to wrap.
145 #[allow(clippy::comparison_chain)]
146 pub fn wrapping_add(&self, h: &Self) -> Result<Self, Error> {
147 if self.config != h.config {
148 return Err(Error::IncompatibleParameters);
149 }
150
151 let mut histogram = Self::with_config(&self.config);
152
153 // Sort and merge buckets from both histograms
154 let (mut i, mut j) = (0, 0);
155 while i < self.index.len() && j < h.index.len() {
156 let (k1, v1) = (self.index[i], self.count[i]);
157 let (k2, v2) = (h.index[j], h.count[j]);
158
159 if k1 == k2 {
160 histogram.add_bucket(k1, v1.wrapping_add(v2));
161 (i, j) = (i + 1, j + 1);
162 } else if k1 < k2 {
163 histogram.add_bucket(k1, v1);
164 i += 1;
165 } else {
166 histogram.add_bucket(k2, v2);
167 j += 1;
168 }
169 }
170
171 // Fill remaining values, if any, from the left histogram
172 if i < self.index.len() {
173 histogram.index.extend(&self.index[i..self.index.len()]);
174 histogram.count.extend(&self.count[i..self.count.len()]);
175 }
176
177 // Fill remaining values, if any, from the right histogram
178 if j < h.index.len() {
179 histogram.index.extend(&h.index[j..h.index.len()]);
180 histogram.count.extend(&h.count[j..h.count.len()]);
181 }
182
183 Ok(histogram)
184 }
185
186 /// Subtracts the other histogram from this histogram and returns the result as a
187 /// new histogram.
188 ///
189 /// Returns `Err(Error::IncompatibleParameters)` if the configs don't match,
190 /// `Err(Error::InvalidSubset)` if the other histogram has buckets not present in
191 /// this one, or `Err(Error::Underflow)` if any bucket would underflow.
192 #[allow(clippy::comparison_chain)]
193 pub fn checked_sub(&self, h: &Self) -> Result<Self, Error> {
194 if self.config != h.config {
195 return Err(Error::IncompatibleParameters);
196 }
197
198 let mut histogram = Self::with_config(&self.config);
199
200 // Sort and merge buckets from both histograms
201 let (mut i, mut j) = (0, 0);
202 while i < self.index.len() && j < h.index.len() {
203 let (k1, v1) = (self.index[i], self.count[i]);
204 let (k2, v2) = (h.index[j], h.count[j]);
205
206 if k1 == k2 {
207 let v = v1.checked_sub(v2).ok_or(Error::Underflow)?;
208 if v != <$count as Count>::ZERO {
209 histogram.add_bucket(k1, v);
210 }
211 (i, j) = (i + 1, j + 1);
212 } else if k1 < k2 {
213 histogram.add_bucket(k1, v1);
214 i += 1;
215 } else {
216 // Other histogram has a bucket not present in this histogram
217 return Err(Error::InvalidSubset);
218 }
219 }
220
221 // Check that the subset histogram has been consumed
222 if j < h.index.len() {
223 return Err(Error::InvalidSubset);
224 }
225
226 // Fill remaining buckets, if any, from the superset histogram
227 if i < self.index.len() {
228 histogram.index.extend(&self.index[i..self.index.len()]);
229 histogram.count.extend(&self.count[i..self.count.len()]);
230 }
231
232 Ok(histogram)
233 }
234
235 /// Subtracts the other histogram from this histogram and returns the result
236 /// as a new histogram.
237 ///
238 /// Returns `Err(Error::IncompatibleParameters)` if the configs don't match,
239 /// or `Err(Error::InvalidSubset)` if the other histogram has buckets not
240 /// present in this one. Buckets are allowed to wrap on underflow.
241 #[allow(clippy::comparison_chain)]
242 pub fn wrapping_sub(&self, h: &Self) -> Result<Self, Error> {
243 if self.config != h.config {
244 return Err(Error::IncompatibleParameters);
245 }
246
247 let mut histogram = Self::with_config(&self.config);
248
249 let (mut i, mut j) = (0, 0);
250 while i < self.index.len() && j < h.index.len() {
251 let (k1, v1) = (self.index[i], self.count[i]);
252 let (k2, v2) = (h.index[j], h.count[j]);
253
254 if k1 == k2 {
255 histogram.add_bucket(k1, v1.wrapping_sub(v2));
256 (i, j) = (i + 1, j + 1);
257 } else if k1 < k2 {
258 histogram.add_bucket(k1, v1);
259 i += 1;
260 } else {
261 return Err(Error::InvalidSubset);
262 }
263 }
264
265 if i < self.index.len() {
266 histogram.index.extend(&self.index[i..]);
267 histogram.count.extend(&self.count[i..]);
268 }
269
270 if j < h.index.len() {
271 return Err(Error::InvalidSubset);
272 }
273
274 Ok(histogram)
275 }
276
277 /// Returns a new histogram with a reduced grouping power.
278 ///
279 /// Returns an error if the requested grouping power is not less than the current
280 /// grouping power.
281 pub fn downsample(&self, grouping_power: u8) -> Result<Self, Error> {
282 if grouping_power >= self.config.grouping_power() {
283 return Err(Error::IncompatibleParameters);
284 }
285
286 let config = Config::new(grouping_power, self.config.max_value_power())?;
287 let mut histogram = Self::with_config(&config);
288
289 let mut aggregating_idx: u32 = 0;
290 let mut aggregating_count: $count = <$count as Count>::ZERO;
291 for (idx, n) in self.index.iter().zip(self.count.iter()) {
292 let new_idx = config
293 .value_to_index(self.config.index_to_lower_bound(*idx as usize))?
294 as u32;
295
296 if new_idx == aggregating_idx {
297 aggregating_count = aggregating_count.wrapping_add(*n);
298 continue;
299 }
300
301 histogram.add_bucket(aggregating_idx, aggregating_count);
302 aggregating_idx = new_idx;
303 aggregating_count = *n;
304 }
305
306 histogram.add_bucket(aggregating_idx, aggregating_count);
307
308 Ok(histogram)
309 }
310
311 /// Returns an iterator across the non-zero histogram buckets.
312 pub fn iter(&self) -> $iter<'_> {
313 self.as_ref().iter()
314 }
315
316 /// Compute quantiles for the given values.
317 pub fn quantiles(&self, quantiles: &[f64]) -> Result<Option<QuantilesResult>, Error> {
318 <Self as SampleQuantiles>::quantiles(self, quantiles)
319 }
320
321 /// Compute a single quantile.
322 pub fn quantile(&self, quantile: f64) -> Result<Option<QuantilesResult>, Error> {
323 <Self as SampleQuantiles>::quantile(self, quantile)
324 }
325
326 /// Returns a borrowed view over this histogram's storage.
327 pub fn as_ref(&self) -> $ref_name<'_> {
328 $ref_name::from_parts_unchecked(self.config, &self.index, &self.count)
329 }
330 }
331
332 impl SampleQuantiles for $name {
333 fn quantiles(&self, quantiles: &[f64]) -> Result<Option<QuantilesResult>, Error> {
334 self.as_ref().quantiles(quantiles)
335 }
336 }
337
338 impl<'a> IntoIterator for &'a $name {
339 type Item = Bucket;
340 type IntoIter = $iter<'a>;
341
342 fn into_iter(self) -> Self::IntoIter {
343 self.iter()
344 }
345 }
346
347 /// An iterator across the histogram buckets.
348 pub struct $iter<'a> {
349 index: usize,
350 config: Config,
351 sparse_index: &'a [u32],
352 count: &'a [$count],
353 }
354
355 impl Iterator for $iter<'_> {
356 type Item = Bucket;
357
358 fn next(&mut self) -> Option<<Self as std::iter::Iterator>::Item> {
359 if self.index >= self.sparse_index.len() {
360 return None;
361 }
362
363 let bucket = Bucket {
364 count: self.count[self.index].as_u128() as u64,
365 range: self
366 .config
367 .index_to_range(self.sparse_index[self.index] as usize),
368 };
369
370 self.index += 1;
371
372 Some(bucket)
373 }
374 }
375
376 impl ExactSizeIterator for $iter<'_> {
377 fn len(&self) -> usize {
378 self.sparse_index.len() - self.index
379 }
380 }
381
382 impl std::iter::FusedIterator for $iter<'_> {}
383
384 impl From<&$hist> for $name {
385 fn from(histogram: &$hist) -> Self {
386 let mut index = Vec::new();
387 let mut count = Vec::new();
388
389 for (idx, n) in histogram.as_slice().iter().enumerate() {
390 if *n != <$count as Count>::ZERO {
391 index.push(idx as u32);
392 count.push(*n);
393 }
394 }
395
396 Self {
397 config: histogram.config(),
398 index,
399 count,
400 }
401 }
402 }
403
404 // ── Borrowed view ─────────────────────────────────────────────────────
405
406 /// A borrowed view over sparse histogram storage.
407 ///
408 /// Holds references to `index` and `count` slices together with the
409 /// [`Config`], mirroring the read-only API surface of the owned histogram
410 /// type.
411 ///
412 /// The type is [`Copy`] — passing it around is cheap. Use
413 /// `as_ref()` on the owned type or the `From<&Owned>` impl to obtain one.
414 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
415 pub struct $ref_name<'a> {
416 config: Config,
417 index: &'a [u32],
418 count: &'a [$count],
419 }
420
421 impl<'a> $ref_name<'a> {
422 /// Validates the slice invariants (same semantics as the owned `from_parts`).
423 fn validate(config: &Config, index: &[u32], count: &[$count]) -> Result<(), Error> {
424 if index.len() != count.len() {
425 return Err(Error::IncompatibleParameters);
426 }
427
428 let total_buckets = config.total_buckets();
429 let mut prev = None;
430 for &idx in index {
431 if idx as usize >= total_buckets {
432 return Err(Error::OutOfRange);
433 }
434 if let Some(p) = prev {
435 if idx <= p {
436 return Err(Error::IncompatibleParameters);
437 }
438 }
439 prev = Some(idx);
440 }
441
442 for &c in count {
443 if c == <$count as Count>::ZERO {
444 return Err(Error::IncompatibleParameters);
445 }
446 }
447
448 Ok(())
449 }
450
451 /// Creates a borrowed view, validating all invariants.
452 ///
453 /// Returns the same errors as the owned `from_parts`.
454 pub fn from_parts(
455 config: Config,
456 index: &'a [u32],
457 count: &'a [$count],
458 ) -> Result<Self, Error> {
459 Self::validate(&config, index, count)?;
460 Ok(Self {
461 config,
462 index,
463 count,
464 })
465 }
466
467 /// Creates a borrowed view without validating invariants.
468 ///
469 /// # Safety
470 ///
471 /// Caller must ensure `index` and `count` satisfy the same invariants
472 /// as the owned `from_parts`.
473 pub fn from_parts_unchecked(
474 config: Config,
475 index: &'a [u32],
476 count: &'a [$count],
477 ) -> Self {
478 Self {
479 config,
480 index,
481 count,
482 }
483 }
484
485 /// Returns the bucket configuration.
486 pub fn config(&self) -> Config {
487 self.config
488 }
489
490 /// Returns a slice of the non-zero bucket indices.
491 pub fn index(&self) -> &'a [u32] {
492 self.index
493 }
494
495 /// Returns a slice of the bucket counts.
496 pub fn count(&self) -> &'a [$count] {
497 self.count
498 }
499
500 /// Returns the number of non-zero buckets.
501 pub fn len(&self) -> usize {
502 self.index.len()
503 }
504
505 /// Returns `true` if the histogram contains no observations.
506 pub fn is_empty(&self) -> bool {
507 self.index.is_empty()
508 }
509
510 /// Returns an iterator across the non-zero histogram buckets.
511 pub fn iter(&self) -> $iter<'a> {
512 $iter {
513 index: 0,
514 config: self.config,
515 sparse_index: self.index,
516 count: self.count,
517 }
518 }
519
520 /// Compute quantiles for the given values.
521 pub fn quantiles(&self, quantiles: &[f64]) -> Result<Option<QuantilesResult>, Error> {
522 <Self as SampleQuantiles>::quantiles(self, quantiles)
523 }
524
525 /// Compute a single quantile.
526 pub fn quantile(&self, quantile: f64) -> Result<Option<QuantilesResult>, Error> {
527 <Self as SampleQuantiles>::quantile(self, quantile)
528 }
529 }
530
531 impl SampleQuantiles for $ref_name<'_> {
532 fn quantiles(&self, quantiles: &[f64]) -> Result<Option<QuantilesResult>, Error> {
533 // validate all the quantiles
534 for q in quantiles {
535 if !(0.0..=1.0).contains(q) {
536 return Err(Error::InvalidQuantile);
537 }
538 }
539
540 // get the total count
541 let total_count: u128 = self.count.iter().map(|v| v.as_u128()).sum();
542
543 // empty histogram, no quantiles available
544 if total_count == 0 {
545 return Ok(None);
546 }
547
548 // sort the requested quantiles so we can find them in a single pass
549 let mut sorted: Vec<Quantile> = quantiles
550 .iter()
551 .map(|&q| Quantile::new(q).unwrap())
552 .collect();
553 sorted.sort();
554 sorted.dedup();
555
556 // min/max are the first and last entries in the sparse vectors
557 let min = Bucket {
558 count: self.count[0].as_u128() as u64,
559 range: self.config.index_to_range(self.index[0] as usize),
560 };
561 let last = self.index.len() - 1;
562 let max = Bucket {
563 count: self.count[last].as_u128() as u64,
564 range: self.config.index_to_range(self.index[last] as usize),
565 };
566
567 // single pass to find all quantile buckets
568 let mut idx = 0;
569 let mut partial_sum = self.count[0].as_u128();
570
571 let mut entries = BTreeMap::new();
572
573 for quantile in &sorted {
574 let count =
575 std::cmp::max(1, (quantile.as_f64() * total_count as f64).ceil() as u128);
576
577 loop {
578 if partial_sum >= count {
579 entries.insert(
580 *quantile,
581 Bucket {
582 count: self.count[idx].as_u128() as u64,
583 range: self.config.index_to_range(self.index[idx] as usize),
584 },
585 );
586 break;
587 }
588
589 if idx == (self.index.len() - 1) {
590 break;
591 }
592
593 idx += 1;
594 partial_sum += self.count[idx].as_u128();
595 }
596 }
597
598 Ok(Some(QuantilesResult::new(entries, total_count, min, max)))
599 }
600 }
601
602 impl<'a> From<&'a $name> for $ref_name<'a> {
603 fn from(h: &'a $name) -> Self {
604 Self::from_parts_unchecked(h.config(), h.index(), h.count())
605 }
606 }
607
608 impl<'a> IntoIterator for $ref_name<'a> {
609 type Item = Bucket;
610 type IntoIter = $iter<'a>;
611
612 fn into_iter(self) -> Self::IntoIter {
613 self.iter()
614 }
615 }
616
617 impl<'a, 'b> IntoIterator for &'a $ref_name<'b> {
618 type Item = Bucket;
619 type IntoIter = $iter<'b>;
620
621 fn into_iter(self) -> Self::IntoIter {
622 self.iter()
623 }
624 }
625 };
626 }
627
628 define_sparse_histogram!(
629 SparseHistogram,
630 SparseHistogramRef,
631 SparseIter,
632 Histogram,
633 u64
634 );
635 define_sparse_histogram!(
636 SparseHistogram32,
637 SparseHistogram32Ref,
638 SparseIter32,
639 Histogram32,
640 u32
641 );
642
643 // Deprecated forwarding methods — only on the u64 variant to avoid proliferating
644 // deprecated APIs onto the new u32 type.
645 impl SparseHistogram {
646 /// Return a collection of percentiles from this histogram.
647 ///
648 /// Each percentile should be in the inclusive range `0.0..=1.0`. For
649 /// example, the 50th percentile (median) can be found using `0.5`.
650 ///
651 /// The results will be sorted by the percentile.
652 #[deprecated(note = "Use the SampleQuantiles trait")]
653 #[allow(deprecated)]
654 pub fn percentiles(&self, percentiles: &[f64]) -> Result<Option<Vec<(f64, Bucket)>>, Error> {
655 Ok(SampleQuantiles::quantiles(self, percentiles)
656 .map_err(|e| match e {
657 Error::InvalidQuantile => Error::InvalidPercentile,
658 other => other,
659 })?
660 .map(|qr| {
661 qr.entries()
662 .iter()
663 .map(|(q, b)| (q.as_f64(), b.clone()))
664 .collect()
665 }))
666 }
667
668 /// Return a single percentile from this histogram.
669 ///
670 /// The percentile should be in the inclusive range `0.0..=1.0`. For
671 /// example, the 50th percentile (median) can be found using `0.5`.
672 #[deprecated(note = "Use the SampleQuantiles trait")]
673 pub fn percentile(&self, percentile: f64) -> Result<Option<Bucket>, Error> {
674 #[allow(deprecated)]
675 self.percentiles(&[percentile])
676 .map(|v| v.map(|x| x.first().unwrap().1.clone()))
677 }
678 }
679
680 #[cfg(test)]
681 mod tests {
682 use rand::RngExt;
683 use std::collections::HashMap;
684
685 use super::*;
686 use crate::standard::Histogram;
687
688 #[test]
689 fn checked_add() {
690 let config = Config::new(7, 32).unwrap();
691
692 let h1 = SparseHistogram::from_parts(config, vec![1, 3, 5], vec![6, 12, 7]).unwrap();
693 let h2 = SparseHistogram::from_parts(config, vec![2, 3], vec![5, 7]).unwrap();
694
695 let h = h1.checked_add(&h2).unwrap();
696 assert_eq!(h.index(), &[1, 2, 3, 5]);
697 assert_eq!(h.count(), &[6, 5, 19, 7]);
698
699 // overflow
700 let h_max = SparseHistogram::from_parts(config, vec![3], vec![u64::MAX]).unwrap();
701 assert_eq!(h1.checked_add(&h_max), Err(Error::Overflow));
702 }
703
704 #[test]
705 fn wrapping_add() {
706 let config = Config::new(7, 32).unwrap();
707
708 let h1 = SparseHistogram::from_parts(config, vec![1, 3, 5], vec![6, 12, 7]).unwrap();
709 let h2 = SparseHistogram::with_config(&config);
710 let h3 = SparseHistogram::from_parts(config, vec![2, 3, 6, 11, 13], vec![5, 7, 3, 15, 6])
711 .unwrap();
712
713 let hdiff = SparseHistogram::new(6, 16).unwrap();
714 let h = h1.wrapping_add(&hdiff);
715 assert_eq!(h, Err(Error::IncompatibleParameters));
716
717 let h = h1.wrapping_add(&h2).unwrap();
718 assert_eq!(h.index(), &[1, 3, 5]);
719 assert_eq!(h.count(), &[6, 12, 7]);
720
721 let h = h2.wrapping_add(&h3).unwrap();
722 assert_eq!(h.index(), &[2, 3, 6, 11, 13]);
723 assert_eq!(h.count(), &[5, 7, 3, 15, 6]);
724
725 let h = h1.wrapping_add(&h3).unwrap();
726 assert_eq!(h.index(), &[1, 2, 3, 5, 6, 11, 13]);
727 assert_eq!(h.count(), &[6, 5, 19, 7, 3, 15, 6]);
728 }
729
730 #[test]
731 fn checked_sub() {
732 let config = Config::new(7, 32).unwrap();
733
734 let h1 = SparseHistogram::from_parts(config, vec![1, 3, 5], vec![6, 12, 7]).unwrap();
735
736 let hparams = SparseHistogram::new(6, 16).unwrap();
737 let h = h1.checked_sub(&hparams);
738 assert_eq!(h, Err(Error::IncompatibleParameters));
739
740 let hempty = SparseHistogram::with_config(&config);
741 let h = h1.checked_sub(&hempty).unwrap();
742 assert_eq!(h.index(), &[1, 3, 5]);
743 assert_eq!(h.count(), &[6, 12, 7]);
744
745 let hclone = h1.clone();
746 let h = h1.checked_sub(&hclone).unwrap();
747 assert!(h.index().is_empty());
748 assert!(h.count().is_empty());
749
750 let hlarger = SparseHistogram::from_parts(config, vec![1, 3, 5], vec![4, 13, 7]).unwrap();
751 let h = h1.checked_sub(&hlarger);
752 assert_eq!(h, Err(Error::Underflow));
753
754 let hmore = SparseHistogram::from_parts(config, vec![1, 5, 7], vec![4, 7, 1]).unwrap();
755 let h = h1.checked_sub(&hmore);
756 assert_eq!(h, Err(Error::InvalidSubset));
757
758 let hdiff = SparseHistogram::from_parts(config, vec![1, 2, 5], vec![4, 1, 7]).unwrap();
759 let h = h1.checked_sub(&hdiff);
760 assert_eq!(h, Err(Error::InvalidSubset));
761
762 let hsubset = SparseHistogram::from_parts(config, vec![1, 3], vec![5, 9]).unwrap();
763 let h = h1.checked_sub(&hsubset).unwrap();
764 assert_eq!(h.index(), &[1, 3, 5]);
765 assert_eq!(h.count(), &[1, 3, 7]);
766 }
767
768 #[test]
769 fn wrapping_sub() {
770 let config = Config::new(7, 32).unwrap();
771
772 let h1 = SparseHistogram::from_parts(config, vec![1, 3, 5], vec![6, 12, 7]).unwrap();
773 let h2 = SparseHistogram::from_parts(config, vec![1, 3], vec![4, 5]).unwrap();
774
775 let h = h1.wrapping_sub(&h2).unwrap();
776 assert_eq!(h.index(), &[1, 3, 5]);
777 assert_eq!(h.count(), &[2, 7, 7]);
778
779 // wrapping underflow
780 let h3 = SparseHistogram::from_parts(config, vec![1], vec![10]).unwrap();
781 let h = h1.wrapping_sub(&h3).unwrap();
782 assert_eq!(h.count()[0], 6u64.wrapping_sub(10)); // wraps
783
784 // non-subset returns error
785 let h4 = SparseHistogram::from_parts(config, vec![2], vec![1]).unwrap();
786 assert_eq!(h1.wrapping_sub(&h4), Err(Error::InvalidSubset));
787 }
788
789 #[test]
790 fn wrapping_add_overflow() {
791 let config = Config::new(7, 32).unwrap();
792 let h1 = SparseHistogram::from_parts(config, vec![1], vec![u64::MAX]).unwrap();
793 let h2 = SparseHistogram::from_parts(config, vec![1], vec![1]).unwrap();
794 let h = h1.wrapping_add(&h2).unwrap();
795 // u64::MAX + 1 wraps to 0, add_bucket skips zero-count entries
796 assert!(h.index().is_empty());
797 }
798
799 #[allow(deprecated)]
800 #[test]
801 fn percentiles() {
802 let mut hstandard = Histogram::new(4, 10).unwrap();
803 let hempty = SparseHistogram::from(&hstandard);
804
805 for v in 1..1024 {
806 let _ = hstandard.increment(v);
807 }
808
809 let hsparse = SparseHistogram::from(&hstandard);
810 let percentiles = [0.01, 0.10, 0.25, 0.50, 0.75, 0.90, 0.99, 0.999];
811 for percentile in percentiles {
812 let bempty = hempty.percentile(percentile).unwrap();
813 // Use quantile() on hstandard (deprecated percentile() removed)
814 let bstandard = hstandard
815 .quantile(percentile)
816 .unwrap()
817 .map(|r| r.get(&Quantile::new(percentile).unwrap()).unwrap().clone());
818 let bsparse = hsparse.percentile(percentile).unwrap();
819
820 assert_eq!(bempty, None);
821 assert_eq!(bsparse, bstandard);
822 }
823
824 assert_eq!(hempty.percentiles(&percentiles), Ok(None));
825 // Compare sparse percentiles against standard quantiles
826 let sparse_result = hsparse.percentiles(&percentiles).unwrap().unwrap();
827 for (p, bucket) in &sparse_result {
828 let q = hstandard.quantile(*p).unwrap().unwrap();
829 let standard_bucket = q.get(&Quantile::new(*p).unwrap()).unwrap();
830 assert_eq!(bucket, standard_bucket);
831 }
832 }
833
834 #[allow(deprecated)]
835 #[test]
836 // Tests percentile used to find min
837 fn min() {
838 let mut histogram = Histogram::new(7, 64).unwrap();
839
840 let h = SparseHistogram::from(&histogram);
841 assert_eq!(h.percentile(0.0).unwrap(), None);
842
843 let _ = histogram.increment(10);
844 let h = SparseHistogram::from(&histogram);
845 assert_eq!(h.percentile(0.0).map(|b| b.unwrap().end()), Ok(10));
846
847 let _ = histogram.increment(4);
848 let h = SparseHistogram::from(&histogram);
849 assert_eq!(h.percentile(0.0).map(|b| b.unwrap().end()), Ok(4));
850 }
851
852 fn compare_histograms(hstandard: &Histogram, hsparse: &SparseHistogram) {
853 assert_eq!(hstandard.config(), hsparse.config());
854
855 let mut buckets: HashMap<u32, u64> = HashMap::new();
856 for (idx, count) in hsparse.index().iter().zip(hsparse.count().iter()) {
857 let _ = buckets.insert(*idx, *count);
858 }
859
860 for (idx, count) in hstandard.as_slice().iter().enumerate() {
861 if *count > 0 {
862 let v = buckets.get(&(idx as u32)).unwrap();
863 assert_eq!(*v, *count);
864 }
865 }
866 }
867
868 #[test]
869 fn snapshot() {
870 let mut hstandard = Histogram::new(5, 10).unwrap();
871
872 for v in 1..1024 {
873 let _ = hstandard.increment(v);
874 }
875
876 // Convert to sparse and store buckets in a hash for random lookup
877 let hsparse = SparseHistogram::from(&hstandard);
878 compare_histograms(&hstandard, &hsparse);
879 }
880
881 #[test]
882 fn downsample() {
883 let mut histogram = Histogram::new(8, 32).unwrap();
884 let mut rng = rand::rng();
885
886 // Generate 10,000 values to store in a sorted array and a histogram
887 for _ in 0..10000 {
888 let v: u64 = rng.random_range(1..2_u64.pow(histogram.config.max_value_power() as u32));
889 let _ = histogram.increment(v);
890 }
891
892 let hsparse = SparseHistogram::from(&histogram);
893 compare_histograms(&histogram, &hsparse);
894
895 // Downsample and check the percentiles lie within error margin
896 let grouping_power = histogram.config.grouping_power();
897 for factor in 1..grouping_power {
898 let reduced_gp = grouping_power - factor;
899 let h1 = histogram.downsample(reduced_gp).unwrap();
900 let h2 = hsparse.downsample(reduced_gp).unwrap();
901 compare_histograms(&h1, &h2);
902 }
903 }
904
905 // ===== new u32-targeted tests =====
906
907 #[test]
908 fn from_parts_u32() {
909 let config = Config::new(7, 32).unwrap();
910 let h = SparseHistogram32::from_parts(config, vec![1, 3, 5], vec![6u32, 12, 7]).unwrap();
911 assert_eq!(h.index(), &[1, 3, 5]);
912 assert_eq!(h.count(), &[6u32, 12, 7]);
913 }
914
915 #[test]
916 fn checked_add_u32_overflow() {
917 let config = Config::new(7, 32).unwrap();
918 let h1 = SparseHistogram32::from_parts(config, vec![1], vec![u32::MAX]).unwrap();
919 let h2 = SparseHistogram32::from_parts(config, vec![1], vec![1u32]).unwrap();
920 assert_eq!(h1.checked_add(&h2), Err(Error::Overflow));
921 }
922
923 #[test]
924 fn from_histogram_u32() {
925 use crate::standard::Histogram32;
926 let mut h = Histogram32::new(7, 64).unwrap();
927 h.increment(1).unwrap();
928 h.increment(5).unwrap();
929 h.increment(100).unwrap();
930 let s = SparseHistogram32::from(&h);
931 assert_eq!(s.count().len(), 3);
932 }
933
934 // ── Ref type tests ────────────────────────────────────────────────────────
935
936 #[test]
937 fn ref_validation_parity_u64() {
938 let config = Config::new(7, 32).unwrap();
939
940 // Mismatched lengths
941 assert_eq!(
942 SparseHistogramRef::from_parts(config, &[1u32, 2], &[1u64]),
943 Err(Error::IncompatibleParameters)
944 );
945
946 // Out of range index
947 assert_eq!(
948 SparseHistogramRef::from_parts(config, &[u32::MAX], &[1u64]),
949 Err(Error::OutOfRange)
950 );
951
952 // Non-ascending indices
953 assert_eq!(
954 SparseHistogramRef::from_parts(config, &[3u32, 1], &[1u64, 2]),
955 Err(Error::IncompatibleParameters)
956 );
957
958 // Duplicate indices
959 assert_eq!(
960 SparseHistogramRef::from_parts(config, &[1u32, 1], &[1u64, 2]),
961 Err(Error::IncompatibleParameters)
962 );
963
964 // Zero count
965 assert_eq!(
966 SparseHistogramRef::from_parts(config, &[1u32], &[0u64]),
967 Err(Error::IncompatibleParameters)
968 );
969
970 // Valid
971 assert!(SparseHistogramRef::from_parts(config, &[1u32, 3, 5], &[6u64, 12, 7]).is_ok());
972
973 // Empty
974 assert!(SparseHistogramRef::from_parts(config, &[], &[]).is_ok());
975 }
976
977 #[test]
978 fn ref_validation_parity_u32() {
979 let config = Config::new(7, 32).unwrap();
980
981 assert_eq!(
982 SparseHistogram32Ref::from_parts(config, &[1u32, 2], &[1u32]),
983 Err(Error::IncompatibleParameters)
984 );
985 assert_eq!(
986 SparseHistogram32Ref::from_parts(config, &[u32::MAX], &[1u32]),
987 Err(Error::OutOfRange)
988 );
989 assert_eq!(
990 SparseHistogram32Ref::from_parts(config, &[3u32, 1], &[1u32, 2]),
991 Err(Error::IncompatibleParameters)
992 );
993 assert_eq!(
994 SparseHistogram32Ref::from_parts(config, &[1u32], &[0u32]),
995 Err(Error::IncompatibleParameters)
996 );
997 assert!(SparseHistogram32Ref::from_parts(config, &[1u32, 3, 5], &[6u32, 12, 7]).is_ok());
998 }
999
1000 #[test]
1001 fn ref_quantile_parity_u64() {
1002 let config = Config::new(7, 32).unwrap();
1003 let owned = SparseHistogram::from_parts(config, vec![1, 3, 5], vec![6u64, 12, 7]).unwrap();
1004 let r = SparseHistogramRef::from_parts(config, owned.index(), owned.count()).unwrap();
1005
1006 let qs = &[0.0, 0.5, 0.99, 1.0];
1007 assert_eq!(owned.quantiles(qs).unwrap(), r.quantiles(qs).unwrap());
1008 }
1009
1010 #[test]
1011 fn ref_quantile_parity_u32() {
1012 let config = Config::new(7, 32).unwrap();
1013 let owned =
1014 SparseHistogram32::from_parts(config, vec![1, 3, 5], vec![6u32, 12, 7]).unwrap();
1015 let r = SparseHistogram32Ref::from_parts(config, owned.index(), owned.count()).unwrap();
1016
1017 let qs = &[0.0, 0.5, 0.99, 1.0];
1018 assert_eq!(owned.quantiles(qs).unwrap(), r.quantiles(qs).unwrap());
1019 }
1020
1021 #[test]
1022 fn ref_from_parts_unchecked_matches_owned() {
1023 let config = Config::new(7, 32).unwrap();
1024 let owned = SparseHistogram::from_parts(config, vec![1, 3, 5], vec![6u64, 12, 7]).unwrap();
1025 let r = SparseHistogramRef::from_parts_unchecked(config, owned.index(), owned.count());
1026
1027 let qs = &[0.25, 0.5, 0.75];
1028 assert_eq!(owned.quantiles(qs).unwrap(), r.quantiles(qs).unwrap());
1029 }
1030
1031 #[test]
1032 fn ref_from_owned_round_trip() {
1033 let config = Config::new(7, 32).unwrap();
1034 let owned = SparseHistogram::from_parts(config, vec![1, 3, 5], vec![6u64, 12, 7]).unwrap();
1035 let r = SparseHistogramRef::from(&owned);
1036
1037 let qs = &[0.0, 0.5, 1.0];
1038 assert_eq!(r.quantiles(qs).unwrap(), owned.quantiles(qs).unwrap());
1039 }
1040
1041 #[test]
1042 fn ref_iter_agrees_with_owned() {
1043 let config = Config::new(7, 32).unwrap();
1044 let owned = SparseHistogram::from_parts(config, vec![1, 3, 5], vec![6u64, 12, 7]).unwrap();
1045 let r = SparseHistogramRef::from(&owned);
1046
1047 let owned_buckets: Vec<_> = owned.iter().collect();
1048 let ref_buckets: Vec<_> = r.iter().collect();
1049 assert_eq!(owned_buckets, ref_buckets);
1050 }
1051
1052 #[test]
1053 fn ref_empty_edge_case() {
1054 let config = Config::new(7, 32).unwrap();
1055 let r = SparseHistogramRef::from_parts(config, &[], &[]).unwrap();
1056 assert!(r.is_empty());
1057 assert_eq!(r.len(), 0);
1058 assert_eq!(r.quantiles(&[0.5]).unwrap(), None);
1059 }
1060
1061 #[test]
1062 fn ref_single_sample_edge_case() {
1063 let config = Config::new(7, 32).unwrap();
1064 let owned = SparseHistogram::from_parts(config, vec![5], vec![1u64]).unwrap();
1065 let r = SparseHistogramRef::from(&owned);
1066
1067 assert_eq!(r.len(), 1);
1068 let result = r.quantile(0.5).unwrap().unwrap();
1069 let q = Quantile::new(0.5).unwrap();
1070 assert!(result.get(&q).is_some());
1071 }
1072
1073 #[test]
1074 fn ref_into_iterator() {
1075 let config = Config::new(7, 32).unwrap();
1076 let owned = SparseHistogram::from_parts(config, vec![1, 3, 5], vec![6u64, 12, 7]).unwrap();
1077 let r = SparseHistogramRef::from(&owned);
1078
1079 // IntoIterator for owned ref (consumes)
1080 let buckets_consumed: Vec<_> = r.into_iter().collect();
1081 // IntoIterator for &ref (borrows)
1082 let buckets_borrowed: Vec<_> = (&r).into_iter().collect();
1083 let owned_buckets: Vec<_> = owned.iter().collect();
1084
1085 assert_eq!(buckets_consumed, owned_buckets);
1086 assert_eq!(buckets_borrowed, owned_buckets);
1087 }
1088
1089 #[test]
1090 fn ref_u32_symmetry() {
1091 let config = Config::new(7, 32).unwrap();
1092 let owned =
1093 SparseHistogram32::from_parts(config, vec![1, 3, 5], vec![6u32, 12, 7]).unwrap();
1094 let r = SparseHistogram32Ref::from(&owned);
1095
1096 // Iter parity
1097 let owned_buckets: Vec<_> = owned.iter().collect();
1098 let ref_buckets: Vec<_> = r.iter().collect();
1099 assert_eq!(owned_buckets, ref_buckets);
1100
1101 // Quantile parity
1102 let qs = &[0.0, 0.5, 0.99, 1.0];
1103 assert_eq!(owned.quantiles(qs).unwrap(), r.quantiles(qs).unwrap());
1104 }
1105
1106 #[test]
1107 fn ref_as_ref_method() {
1108 let config = Config::new(7, 32).unwrap();
1109 let owned = SparseHistogram::from_parts(config, vec![1, 3, 5], vec![6u64, 12, 7]).unwrap();
1110 let r = owned.as_ref();
1111
1112 let qs = &[0.5, 0.99];
1113 assert_eq!(owned.quantiles(qs).unwrap(), r.quantiles(qs).unwrap());
1114 }
1115
1116 #[test]
1117 fn ref_sample_quantiles_trait() {
1118 use crate::quantile::SampleQuantiles;
1119 let config = Config::new(7, 32).unwrap();
1120 let owned = SparseHistogram::from_parts(config, vec![1, 3, 5], vec![6u64, 12, 7]).unwrap();
1121 let r = SparseHistogramRef::from(&owned);
1122
1123 let qs = &[0.25, 0.75];
1124 assert_eq!(
1125 SampleQuantiles::quantiles(&r, qs).unwrap(),
1126 SampleQuantiles::quantiles(&owned, qs).unwrap()
1127 );
1128 }
1129 }