1use crate::functions::{EdgeKind, count_edges, extremum, instant_delta, kahan_inc};
22use crate::go_sort;
23use crate::range_eval::{BatchKernel, FloatWindow, FloatWindows, RangeModifier, WindowKernel};
24
25#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
27pub enum RangeFunction {
28 Rate,
29 Increase,
30 Delta,
31 Irate,
32 Idelta,
33 AvgOverTime,
34 MinOverTime,
35 MaxOverTime,
36 SumOverTime,
37 CountOverTime,
38 LastOverTime,
39 PresentOverTime,
40 StddevOverTime,
41 StdvarOverTime,
42 QuantileOverTime(f64),
44 Resets,
45 Changes,
46 Deriv,
47 PredictLinear(f64),
49 DoubleExponentialSmoothing {
52 smoothing: f64,
53 trend: f64,
54 },
55 FirstOverTime,
56 MadOverTime,
58 TsOfFirstOverTime,
60 TsOfLastOverTime,
62 TsOfMinOverTime,
64 TsOfMaxOverTime,
66}
67
68impl RangeFunction {
69 pub fn drops_metric_name(self) -> bool {
72 !matches!(self, Self::LastOverTime | Self::FirstOverTime)
73 }
74
75 pub(crate) fn yields_histograms(self) -> bool {
78 matches!(
79 self,
80 Self::Rate
81 | Self::Increase
82 | Self::Delta
83 | Self::Irate
84 | Self::Idelta
85 | Self::AvgOverTime
86 | Self::SumOverTime
87 | Self::LastOverTime
88 | Self::FirstOverTime
89 )
90 }
91
92 pub(crate) fn indexes_counter_resets(self) -> bool {
104 matches!(self, Self::Rate | Self::Increase)
105 }
106
107 pub(crate) fn batch_kernel(self) -> Option<BatchKernel> {
113 match self {
114 Self::Rate => Some(Box::new(extrapolated_rate_batch::<true, true>)),
115 Self::Increase => Some(Box::new(extrapolated_rate_batch::<true, false>)),
116 _ => None,
117 }
118 }
119
120 pub(crate) fn kernel(self, offset_ms: i64) -> WindowKernel {
122 match self {
123 Self::Rate => Box::new(extrapolated_rate::<true, true>),
124 Self::Increase => Box::new(extrapolated_rate::<true, false>),
125 Self::Delta => Box::new(extrapolated_rate::<false, false>),
126 Self::Irate => Box::new(last_two::<true>),
127 Self::Idelta => Box::new(last_two::<false>),
128 Self::AvgOverTime => Box::new(|window| Some(avg(window.values))),
129 Self::MinOverTime => Box::new(|window| extremum(window.values.iter().copied(), true)),
130 Self::MaxOverTime => Box::new(|window| extremum(window.values.iter().copied(), false)),
131 Self::SumOverTime => Box::new(|window| Some(sum(window.values))),
132 Self::CountOverTime => Box::new(|window| Some(window.values.len() as f64)),
133 Self::LastOverTime => Box::new(|window| window.values.last().copied()),
134 Self::PresentOverTime => Box::new(|_| Some(1.0)),
135 Self::StddevOverTime => Box::new(|window| Some(variance(window.values).sqrt())),
136 Self::StdvarOverTime => Box::new(|window| Some(variance(window.values))),
137 Self::QuantileOverTime(q) => {
138 let mut scratch = Vec::new();
139 Box::new(move |window| Some(quantile(q, window.values, &mut scratch)))
140 }
141 Self::Resets => {
142 Box::new(|window| Some(count_edges(window.values, EdgeKind::Resets) as f64))
143 }
144 Self::Changes => {
145 Box::new(|window| Some(count_edges(window.values, EdgeKind::Changes) as f64))
146 }
147 Self::Deriv => Box::new(|window| {
148 (window.values.len() >= 2)
149 .then(|| linear_regression(&window, window.timestamps[0]).0)
150 }),
151 Self::PredictLinear(duration) => Box::new(move |window| {
154 if window.values.len() < 2 {
155 return None;
156 }
157 let (slope, intercept) =
158 linear_regression(&window, window.eval_ts.checked_add(offset_ms)?);
159 Some(slope * duration + intercept)
160 }),
161 Self::DoubleExponentialSmoothing { smoothing, trend } => Box::new(move |window| {
162 double_exponential_smoothing(window.values, smoothing, trend)
163 }),
164 Self::FirstOverTime => Box::new(|window| window.values.first().copied()),
165 Self::MadOverTime => {
166 let (mut deviations, mut scratch) = (Vec::new(), Vec::new());
167 Box::new(move |window| {
168 Some(median_absolute_deviation(
169 window.values,
170 &mut deviations,
171 &mut scratch,
172 ))
173 })
174 }
175 Self::TsOfFirstOverTime => {
177 Box::new(move |window| Some(seconds(window.timestamps[0] - offset_ms)))
178 }
179 Self::TsOfLastOverTime => Box::new(move |window| {
182 let last = window.timestamps[window.timestamps.len() - 1] - offset_ms;
183 Some(seconds(last.max(0)))
184 }),
185 Self::TsOfMinOverTime => Box::new(move |window| {
186 Some(seconds(timestamp_of_extremum(&window, false) - offset_ms))
187 }),
188 Self::TsOfMaxOverTime => Box::new(move |window| {
189 Some(seconds(timestamp_of_extremum(&window, true) - offset_ms))
190 }),
191 }
192 }
193}
194
195impl RangeFunction {
196 pub(crate) fn modified_kernel(self, modifier: RangeModifier) -> WindowKernel {
202 let smoothed = matches!(modifier, RangeModifier::Smoothed { .. });
203 match self {
204 Self::Rate => Box::new(move |window| extended_rate(&window, smoothed, true, true)),
205 Self::Increase => Box::new(move |window| extended_rate(&window, smoothed, true, false)),
206 Self::Delta => Box::new(move |window| extended_rate(&window, smoothed, false, false)),
207 Self::Resets => Box::new(|window| {
208 anchored_values(&window).map(|values| count_edges(values, EdgeKind::Resets) as f64)
209 }),
210 Self::Changes => Box::new(|window| {
211 anchored_values(&window).map(|values| count_edges(values, EdgeKind::Changes) as f64)
212 }),
213 _ => unreachable!("RangeEvaluator::try_new rejects {self:?} with a range modifier"),
214 }
215 }
216}
217
218fn search(n: usize, predicate: impl Fn(usize) -> bool) -> usize {
220 (0..n).find(|&i| predicate(i)).unwrap_or(n)
221}
222
223fn extended_rate(
228 window: &FloatWindow<'_>,
229 smoothed: bool,
230 is_counter: bool,
231 is_rate: bool,
232) -> Option<f64> {
233 let (timestamps, values) = (window.timestamps, window.values);
234 let range_start = window.eval_ts - window.range_ms;
235 let range_end = window.eval_ts;
236 let mut last = timestamps.len() - 1;
237 let first = search(last, |i| timestamps[i] > range_start).saturating_sub(1);
238 if smoothed {
239 last = search(last, |i| timestamps[i] >= range_end);
240 }
241 if timestamps[last] <= range_start || (smoothed && timestamps[first] > range_end) {
242 return None;
243 }
244 let left = if smoothed && timestamps[first] < range_start {
245 interpolate(window, first, range_start, is_counter)
246 } else {
247 values[first]
248 };
249 let right = if smoothed && last > 0 && timestamps[last] > range_end {
250 interpolate(window, last - 1, range_end, is_counter)
251 } else {
252 values[last]
253 };
254 let mut result = right - left;
255 if is_counter {
256 let inner_start = first + usize::from(timestamps[first] <= range_start);
259 let inner_end = last + 1 - usize::from(timestamps[last] >= range_end);
260 let mut correction = 0.0;
261 let mut previous = left;
262 for &value in &values[inner_start..inner_end] {
263 if value < previous {
264 correction += previous;
265 }
266 previous = value;
267 }
268 if right < previous {
269 correction += previous;
270 }
271 result += correction;
272 }
273 if is_rate {
274 result /= window.range_ms as f64 / 1000.0;
275 }
276 Some(result)
277}
278
279fn interpolate(window: &FloatWindow<'_>, index: usize, t: i64, is_counter: bool) -> f64 {
282 let (t1, t2) = (window.timestamps[index], window.timestamps[index + 1]);
283 let (mut y1, y2) = (window.values[index], window.values[index + 1]);
284 if is_counter && y2 < y1 {
285 y1 = 0.0;
286 }
287 y1 + (y2 - y1) * (t - t1) as f64 / (t2 - t1) as f64
288}
289
290fn anchored_values<'a>(window: &FloatWindow<'a>) -> Option<&'a [f64]> {
293 let range_start = window.eval_ts - window.range_ms;
294 let after = window
295 .timestamps
296 .partition_point(|×tamp| timestamp <= range_start);
297 if after >= window.timestamps.len() {
298 return None;
299 }
300 Some(&window.values[after.saturating_sub(1)..])
301}
302
303fn sum(values: &[f64]) -> f64 {
305 let (sum, c) = values
306 .iter()
307 .fold((0.0, 0.0), |(sum, c), &value| kahan_inc(value, sum, c));
308 sum + c
309}
310
311fn avg(values: &[f64]) -> f64 {
314 let (mut sum, mut count) = (values[0], 1.0);
315 let (mut mean, mut kahan_c) = (0.0, 0.0);
316 let mut incremental_mean = false;
317 for (i, &value) in values[1..].iter().enumerate() {
318 count = (i + 2) as f64;
319 if !incremental_mean {
320 let (new_sum, new_c) = kahan_inc(value, sum, kahan_c);
321 if !new_sum.is_infinite() {
322 (sum, kahan_c) = (new_sum, new_c);
323 continue;
324 }
325 incremental_mean = true;
326 mean = sum / (count - 1.0);
327 kahan_c /= count - 1.0;
328 }
329 let q = (count - 1.0) / count;
330 (mean, kahan_c) = kahan_inc(value / count, q * mean, q * kahan_c);
331 }
332 if incremental_mean {
333 mean + kahan_c
334 } else {
335 sum / count + kahan_c / count
336 }
337}
338
339fn variance(values: &[f64]) -> f64 {
341 let mut count = 0.0;
342 let (mut mean, mut c_mean) = (0.0, 0.0);
343 let (mut aux, mut c_aux) = (0.0, 0.0);
344 for &value in values {
345 count += 1.0;
346 let delta = value - (mean + c_mean);
347 (mean, c_mean) = kahan_inc(delta / count, mean, c_mean);
348 (aux, c_aux) = kahan_inc(delta * (value - (mean + c_mean)), aux, c_aux);
349 }
350 (aux + c_aux) / count
351}
352
353pub(crate) fn quantile(q: f64, values: &[f64], sorted: &mut Vec<f64>) -> f64 {
355 if q.is_nan() {
356 return f64::NAN;
357 }
358 if q < 0.0 {
359 return f64::NEG_INFINITY;
360 }
361 if q > 1.0 {
362 return f64::INFINITY;
363 }
364 sorted.clear();
365 sorted.extend_from_slice(values);
366 go_sort::sort_by(sorted, |a, b| a.is_nan() || a < b);
369 let n = sorted.len() as f64;
370 let rank = q * (n - 1.0);
371 let lower = rank.floor().max(0.0);
372 let upper = (n - 1.0).min(lower + 1.0);
373 let weight = rank - rank.floor();
374 sorted[lower as usize] * (1.0 - weight) + sorted[upper as usize] * weight
375}
376
377fn extrapolated_rate<const IS_COUNTER: bool, const IS_RATE: bool>(
379 window: FloatWindow<'_>,
380) -> Option<f64> {
381 let FloatWindow {
382 timestamps,
383 values,
384 counter_resets,
385 eval_ts,
386 range_ms,
387 } = window;
388 let end = values.len().checked_sub(1).filter(|n| *n > 0)?;
389 extrapolated_rate_of(
390 (timestamps[0], timestamps[end]),
391 (values[0], values[end]),
392 end,
393 counter_resets.iter().map(|reset| reset.previous_value),
394 eval_ts,
395 range_ms,
396 (IS_COUNTER, IS_RATE),
397 )
398}
399
400fn extrapolated_rate_of(
407 (first_t, last_t): (i64, i64),
408 (first, last): (f64, f64),
409 samples_minus_one: usize,
410 resets: impl Iterator<Item = f64>,
411 eval_ts: i64,
412 range_ms: i64,
413 (is_counter, is_rate): (bool, bool),
414) -> Option<f64> {
415 let mut result = last - first;
416 if is_counter {
417 result = resets.fold(result, |result, previous_value| result + previous_value);
420 }
421 let zero_point = (is_counter && result > 0.0 && first >= 0.0).then(|| first / result);
422 let factor = extrapolation_factor(
423 ExtrapolationSpan {
424 sampled_from: first_t,
427 average_from: first_t,
428 last: last_t,
429 samples_minus_one,
430 },
431 eval_ts,
432 range_ms,
433 is_counter,
434 is_rate,
435 zero_point,
436 );
437 Some(result * factor)
438}
439
440pub(crate) fn extrapolated_rate_batch<const IS_COUNTER: bool, const IS_RATE: bool>(
447 batch: &FloatWindows<'_>,
448 out: &mut Vec<Option<f64>>,
449) {
450 out.clear();
451 out.reserve(batch.windows.len());
452 for (index, span) in batch.windows.iter().enumerate() {
453 let Some(samples_minus_one) = span.len().checked_sub(1).filter(|n| *n > 0) else {
454 out.push(None);
455 continue;
456 };
457 let (start, last) = (span.start, span.end - 1);
458 out.push(extrapolated_rate_of(
459 (batch.timestamps[start], batch.timestamps[last]),
460 (batch.values[start], batch.values[last]),
461 samples_minus_one,
462 batch
463 .resets_of(index)
464 .iter()
465 .map(|reset| reset.previous_value),
466 batch.eval_ts[index],
467 batch.range_ms,
468 (IS_COUNTER, IS_RATE),
469 ));
470 }
471}
472
473pub(super) struct ExtrapolationSpan {
480 pub sampled_from: i64,
482 pub average_from: i64,
484 pub last: i64,
486 pub samples_minus_one: usize,
489}
490
491pub(super) fn extrapolation_factor(
504 span: ExtrapolationSpan,
505 eval_ts: i64,
506 range_ms: i64,
507 is_counter: bool,
508 is_rate: bool,
509 zero_point: Option<f64>,
510) -> f64 {
511 let ExtrapolationSpan {
512 sampled_from,
513 average_from,
514 last,
515 samples_minus_one,
516 } = span;
517 let range_start = eval_ts.wrapping_sub(range_ms);
523 let mut duration_to_start = average_from.wrapping_sub(range_start) as f64 / 1000.0;
524 let mut duration_to_end = eval_ts.wrapping_sub(last) as f64 / 1000.0;
525 let sampled_interval = last.wrapping_sub(sampled_from) as f64 / 1000.0;
526 let average_interval = if samples_minus_one == 0 {
527 0.0
528 } else {
529 last.wrapping_sub(average_from) as f64 / 1000.0 / samples_minus_one as f64
530 };
531 let threshold = average_interval * 1.1;
532 if duration_to_start >= threshold {
533 duration_to_start = average_interval / 2.0;
534 }
535 if is_counter {
536 let mut duration_to_zero = duration_to_start;
537 if let Some(zero_point) = zero_point {
538 duration_to_zero = sampled_interval * zero_point;
539 }
540 if duration_to_zero < duration_to_start {
541 duration_to_start = duration_to_zero;
542 }
543 }
544 if duration_to_end >= threshold {
545 duration_to_end = average_interval / 2.0;
546 }
547 let mut factor = 1.0;
548 if sampled_interval != 0.0 {
549 factor = (sampled_interval + duration_to_start + duration_to_end) / sampled_interval;
550 }
551 if is_rate {
552 factor /= range_ms as f64 / 1000.0;
553 }
554 factor
555}
556
557fn last_two<const IS_RATE: bool>(window: FloatWindow<'_>) -> Option<f64> {
558 let [.., prev_ts, last_ts] = window.timestamps else {
559 return None;
560 };
561 let [.., prev, last] = window.values else {
562 return None;
563 };
564 instant_delta::<IS_RATE>((*prev_ts, *prev), (*last_ts, *last))
565}
566
567fn linear_regression(window: &FloatWindow<'_>, intercept_time: i64) -> (f64, f64) {
570 let init_y = window.values[0];
571 let mut const_y = true;
572 let mut n = 0.0;
573 let (mut sum_x, mut c_x) = (0.0, 0.0);
574 let (mut sum_y, mut c_y) = (0.0, 0.0);
575 let (mut sum_xy, mut c_xy) = (0.0, 0.0);
576 let (mut sum_x2, mut c_x2) = (0.0, 0.0);
577 for (i, (&t, &y)) in window.timestamps.iter().zip(window.values).enumerate() {
578 if const_y && i > 0 && y != init_y {
579 const_y = false;
580 }
581 n += 1.0;
582 let x = (i128::from(t) - i128::from(intercept_time)) as f64 / 1e3;
583 (sum_x, c_x) = kahan_inc(x, sum_x, c_x);
584 (sum_y, c_y) = kahan_inc(y, sum_y, c_y);
585 (sum_xy, c_xy) = kahan_inc(x * y, sum_xy, c_xy);
586 (sum_x2, c_x2) = kahan_inc(x * x, sum_x2, c_x2);
587 }
588 if const_y {
589 if init_y.is_infinite() {
590 return (f64::NAN, f64::NAN);
591 }
592 return (0.0, init_y);
593 }
594 sum_x += c_x;
595 sum_y += c_y;
596 sum_xy += c_xy;
597 sum_x2 += c_x2;
598 let cov_xy = sum_xy - sum_x * sum_y / n;
599 let var_x = sum_x2 - sum_x * sum_x / n;
600 let slope = cov_xy / var_x;
601 let intercept = sum_y / n - slope * sum_x / n;
602 (slope, intercept)
603}
604
605fn double_exponential_smoothing(values: &[f64], sf: f64, tf: f64) -> Option<f64> {
607 if values.len() < 2 {
608 return None;
609 }
610 let (mut s0, mut s1) = (0.0, values[0]);
611 let mut b = values[1] - values[0];
612 for (i, &value) in values.iter().enumerate().skip(1) {
613 let x = sf * value;
614 b = if i == 1 {
615 b
616 } else {
617 tf * (s1 - s0) + (1.0 - tf) * b
618 };
619 let y = (1.0 - sf) * (s1 + b);
620 (s0, s1) = (s1, x + y);
621 }
622 Some(s1)
623}
624
625pub(super) fn seconds(timestamp_ms: i64) -> f64 {
626 timestamp_ms as f64 / 1000.0
627}
628
629fn timestamp_of_extremum(window: &FloatWindow<'_>, max: bool) -> i64 {
632 let (mut best, mut timestamp) = (window.values[0], window.timestamps[0]);
633 for (&value, &ts) in window.values.iter().zip(window.timestamps) {
634 let replace = if max { value >= best } else { value <= best };
635 if replace || best.is_nan() {
636 (best, timestamp) = (value, ts);
637 }
638 }
639 timestamp
640}
641
642fn median_absolute_deviation(
645 values: &[f64],
646 deviations: &mut Vec<f64>,
647 sorted: &mut Vec<f64>,
648) -> f64 {
649 if values.iter().any(|value| value.is_nan()) {
650 return f64::NAN;
651 }
652 let median = quantile(0.5, values, sorted);
653 deviations.clear();
654 deviations.extend(values.iter().map(|value| (value - median).abs()));
655 quantile(0.5, deviations, sorted)
656}
657
658impl PartialEq for RangeFunction {
659 fn eq(&self, o: &Self) -> bool {
660 match (self, o) {
661 (Self::QuantileOverTime(a), Self::QuantileOverTime(b))
662 | (Self::PredictLinear(a), Self::PredictLinear(b)) => a.to_bits() == b.to_bits(),
663 (
664 Self::DoubleExponentialSmoothing {
665 smoothing: a,
666 trend: b,
667 },
668 Self::DoubleExponentialSmoothing {
669 smoothing: c,
670 trend: d,
671 },
672 ) => a.to_bits() == c.to_bits() && b.to_bits() == d.to_bits(),
673 _ => std::mem::discriminant(self) == std::mem::discriminant(o),
674 }
675 }
676}
677impl Eq for RangeFunction {}
678impl std::hash::Hash for RangeFunction {
679 fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
680 std::mem::discriminant(self).hash(h);
681 match self {
682 Self::QuantileOverTime(x) | Self::PredictLinear(x) => x.to_bits().hash(h),
683 Self::DoubleExponentialSmoothing { smoothing, trend } => {
684 smoothing.to_bits().hash(h);
685 trend.to_bits().hash(h)
686 }
687 _ => (),
688 }
689 }
690}
691
692#[cfg(test)]
693mod tests {
694 use super::{ExtrapolationSpan, extrapolation_factor};
695
696 #[derive(Clone, Copy, Debug)]
701 struct Window {
702 sampled_from: i64,
703 average_from: i64,
704 last: i64,
705 samples_minus_one: usize,
706 eval_ts: i64,
707 range_ms: i64,
708 is_counter: bool,
709 is_rate: bool,
710 zero_point: Option<f64>,
711 }
712
713 impl Window {
714 fn as_float(self) -> f64 {
717 extrapolation_factor(
718 ExtrapolationSpan {
719 sampled_from: self.average_from,
720 average_from: self.average_from,
721 last: self.last,
722 samples_minus_one: self.samples_minus_one,
723 },
724 self.eval_ts,
725 self.range_ms,
726 self.is_counter,
727 self.is_rate,
728 self.zero_point,
729 )
730 }
731
732 fn as_histogram(self) -> f64 {
735 extrapolation_factor(
736 ExtrapolationSpan {
737 sampled_from: self.sampled_from,
738 average_from: self.average_from,
739 last: self.last,
740 samples_minus_one: self.samples_minus_one,
741 },
742 self.eval_ts,
743 self.range_ms,
744 self.is_counter,
745 self.is_rate,
746 self.zero_point,
747 )
748 }
749 }
750
751 #[test]
757 fn both_routes_compute_one_extrapolation_factor() {
758 let windows = [
761 Window {
762 sampled_from: 2_000,
763 average_from: 2_000,
764 last: 5_000,
765 samples_minus_one: 1,
766 eval_ts: 6_500,
767 range_ms: 6_000,
768 is_counter: true,
769 is_rate: false,
770 zero_point: None,
771 },
772 Window {
773 sampled_from: 2_000,
774 average_from: 2_000,
775 last: 5_000,
776 samples_minus_one: 2,
777 eval_ts: 6_500,
778 range_ms: 6_000,
779 is_counter: true,
780 is_rate: true,
781 zero_point: None,
782 },
783 Window {
784 sampled_from: 2_000,
785 average_from: 2_000,
786 last: 5_000,
787 samples_minus_one: 2,
788 eval_ts: 6_500,
789 range_ms: 6_000,
790 is_counter: false,
791 is_rate: false,
792 zero_point: None,
793 },
794 Window {
797 sampled_from: 4_000,
798 average_from: 4_000,
799 last: 4_500,
800 samples_minus_one: 1,
801 eval_ts: 6_500,
802 range_ms: 6_000,
803 is_counter: true,
804 is_rate: true,
805 zero_point: None,
806 },
807 Window {
809 sampled_from: 5_000,
810 average_from: 5_000,
811 last: 5_000,
812 samples_minus_one: 0,
813 eval_ts: 6_500,
814 range_ms: 6_000,
815 is_counter: true,
816 is_rate: false,
817 zero_point: None,
818 },
819 ];
820 for window in windows {
821 for zero_point in [None, Some(0.0), Some(0.25), Some(1.5)] {
822 let window = Window {
823 zero_point,
824 ..window
825 };
826 assert_eq!(
827 window.as_float().to_bits(),
828 window.as_histogram().to_bits(),
829 "{window:?}"
830 );
831 }
832 }
833
834 let two_anchor = Window {
844 sampled_from: 2_000,
845 average_from: 2_500,
846 last: 4_500,
847 samples_minus_one: 1,
848 eval_ts: 7_000,
849 range_ms: 6_000,
850 is_counter: true,
851 is_rate: false,
852 zero_point: Some(0.0),
853 };
854 assert_eq!(two_anchor.as_histogram().to_bits(), 1.4f64.to_bits());
855 assert_eq!(two_anchor.as_float().to_bits(), 1.5f64.to_bits());
856 assert_eq!(
865 Window {
866 sampled_from: two_anchor.average_from,
867 ..two_anchor
868 }
869 .as_histogram()
870 .to_bits(),
871 1.5f64.to_bits()
872 );
873 assert_eq!(
874 Window {
875 average_from: two_anchor.sampled_from,
876 ..two_anchor
877 }
878 .as_histogram()
879 .to_bits(),
880 2.0f64.to_bits()
881 );
882 }
883
884 #[test]
890 fn a_synthetic_zero_moves_only_the_sampled_anchor() {
891 let window = Window {
900 sampled_from: 1_000,
901 average_from: 2_000,
902 last: 3_000,
903 samples_minus_one: 1,
904 eval_ts: 4_500,
905 range_ms: 4_000,
906 is_counter: true,
907 is_rate: false,
908 zero_point: Some(0.0),
909 };
910 assert_eq!(window.as_histogram().to_bits(), 1.25f64.to_bits());
911 assert_eq!(
912 Window {
913 is_rate: true,
914 ..window
915 }
916 .as_histogram()
917 .to_bits(),
918 (1.25f64 / 4.0).to_bits()
919 );
920 assert_eq!(
923 Window {
924 average_from: 1_000,
925 ..window
926 }
927 .as_histogram()
928 .to_bits(),
929 1.75f64.to_bits()
930 );
931 assert_eq!(window.as_float().to_bits(), 1.5f64.to_bits());
934
935 let single = Window {
938 sampled_from: 1_000,
939 average_from: 2_000,
940 last: 2_000,
941 samples_minus_one: 0,
942 ..window
943 };
944 assert_eq!(single.as_histogram().to_bits(), 1.0f64.to_bits());
945 assert_eq!(
946 Window {
947 is_rate: true,
948 ..single
949 }
950 .as_histogram()
951 .to_bits(),
952 (1.0f64 / 4.0).to_bits()
953 );
954 }
955}