1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
// Copyright 2024 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//! Statistics and sample aggregation.

use num::{Num, NumCast, Zero};
use std::cmp;
use std::fmt::Debug;
use std::num::NonZeroUsize;
use thiserror::Error;

use crate::experimental::series::buffer::BufferStrategy;
use crate::experimental::series::interpolation::Interpolation;
use crate::experimental::series::{BitSet, Counter, DataSemantic, Fill, Gauge, Sampler};

pub mod recipe {
    //! Type definitions and respellings of common or interesting statistic types.

    use crate::experimental::series::statistic::{ArithmeticMean, Transform};

    pub type ArithmeticMeanTransform<T, A> = Transform<ArithmeticMean<T>, A>;
}

/// Statistic overflow error.
///
/// Describes overflow errors in statistic computations.
#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
#[error("overflow in statistic computation")]
pub struct OverflowError;

/// A `Sampler` that folds samples into a statistical aggregation.
pub trait Statistic: Clone + Fill<Self::Sample> {
    /// The type of data semantic associated with samples.
    type Semantic: DataSemantic;
    /// The type of samples.
    type Sample: Clone;
    /// The type of the statistical aggregation.
    type Aggregation: Clone;

    /// Resets the state (and aggregation) of the statistic.
    ///
    /// The state of a statistic after a reset is arbitrary, but most types reset to a reasonable
    /// initial state via `Default`. Some types do nothing, such as [`LatchMax`], which operates
    /// across [`SamplingInterval`]s.
    ///
    /// Statistics can be configured to reset to any given state via [`Reset`].
    ///
    /// [`LatchMax`] crate::experimental::series::statistic::LatchMax
    /// [`Reset`] crate::experimental::series::statistic::Reset
    fn reset(&mut self);

    /// Gets the statistical aggregation.
    ///
    /// Returns `None` if no aggregation is ready.
    fn aggregation(&self) -> Option<Self::Aggregation>;
}

/// The associated data semantic type of a `Statistic`.
pub type Semantic<F> = <F as Statistic>::Semantic;

/// The associated sample type of a `Statistic`.
pub type Sample<F> = <F as Statistic>::Sample;

/// The associated aggregation type of a `Statistic`.
pub type Aggregation<F> = <F as Statistic>::Aggregation;

// The buffer strategy of a `Statistic` is determined by the strategy of its data semantic.
impl<F, P> BufferStrategy<F::Aggregation, P> for F
where
    F: Statistic,
    F::Semantic: BufferStrategy<F::Aggregation, P>,
    P: Interpolation,
{
    type Buffer = <F::Semantic as BufferStrategy<F::Aggregation, P>>::Buffer;
}

pub trait StatisticFor<P>: BufferStrategy<Self::Aggregation, P> + Statistic
where
    P: Interpolation<FillSample<Self> = Self::Sample>,
{
}

impl<F, P> StatisticFor<P> for F
where
    F: BufferStrategy<Self::Aggregation, P> + Statistic,
    P: Interpolation<FillSample<Self> = Self::Sample>,
{
}

/// Extension methods for `Statistic`s.
pub trait StatisticExt: Statistic {
    /// Gets the statistical aggregation and resets the statistic.
    fn get_aggregation_and_reset(&mut self) -> Option<Self::Aggregation> {
        let aggregation = self.aggregation();
        self.reset();
        aggregation
    }
}

impl<F> StatisticExt for F where F: Statistic {}

/// Arithmetic mean statistic.
///
/// The arithmetic mean sums samples within their domain and computes the mean as a real number
/// represented using floating-point. For floating-point samples, `NaN`s are discarded and the sum
/// saturates to infinity without error.
///
/// This statistic is sensitive to overflow in the count of samples.
#[derive(Clone, Debug)]
pub struct ArithmeticMean<T> {
    /// The sum of samples.
    sum: T,
    /// The count of samples.
    n: u64,
}

impl<T> ArithmeticMean<T> {
    pub fn with_sum(sum: T) -> Self {
        ArithmeticMean { sum, n: 0 }
    }

    fn increment(&mut self, m: u64) -> Result<(), OverflowError> {
        // TODO(https://fxbug.dev/351848566): On overflow, either saturate `self.n` or leave both
        //                                    `self.sum` and `self.n` unchanged (here and in
        //                                    `Sampler::fold` and `Fill::fill` implementations; see
        //                                    below).
        self.n.checked_add(m).inspect(|sum| self.n = *sum).map(|_| ()).ok_or(OverflowError)
    }
}

impl<T> Default for ArithmeticMean<T>
where
    T: Zero,
{
    fn default() -> Self {
        ArithmeticMean::with_sum(T::zero())
    }
}

impl<T> Fill<T> for ArithmeticMean<T>
where
    Self: Sampler<T, Error = OverflowError>,
    T: Clone + Num + NumCast,
{
    fn fill(&mut self, sample: T, n: NonZeroUsize) -> Result<(), Self::Error> {
        Ok(match num::cast::<_, T>(n.get()) {
            Some(m) => {
                self.fold(sample * m)?;
                self.increment((n.get() as u64) - 1)?;
            }
            _ => {
                for _ in 0..n.get() {
                    self.fold(sample.clone())?;
                }
            }
        })
    }
}

impl Sampler<f32> for ArithmeticMean<f32> {
    type Error = OverflowError;

    fn fold(&mut self, sample: f32) -> Result<(), Self::Error> {
        // Discard `NaN` terms and avoid some floating-point exceptions.
        self.sum = match sample {
            _ if sample.is_nan() => self.sum,
            sample if sample.is_infinite() => sample,
            // Because neither term is `NaN` and `sample` is finite, this saturates at negative or
            // positive infinity.
            sample => self.sum + sample,
        };
        self.increment(1)
    }
}

impl Statistic for ArithmeticMean<f32> {
    type Semantic = Gauge;
    type Sample = f32;
    type Aggregation = f32;

    fn reset(&mut self) {
        *self = Default::default();
    }

    fn aggregation(&self) -> Option<Self::Aggregation> {
        // This is lossy and lossiness correlates to the magnitude of `n`. See details of
        // `u64 as f32` casts.
        let aggregation = (self.n > 0).then(|| self.sum / (self.n as f32));
        aggregation
    }
}

/// Sum statistic.
///
/// The sum directly computes the aggregation in the domain of samples.
///
/// This statistic is sensitive to overflow in the sum of samples.
#[derive(Clone, Debug)]
pub struct Sum<T> {
    /// The sum of samples.
    sum: T,
}

impl<T> Sum<T> {
    pub fn with_sum(sum: T) -> Self {
        Sum { sum }
    }
}

impl<T> Default for Sum<T>
where
    T: Zero,
{
    fn default() -> Self {
        Sum::with_sum(T::zero())
    }
}

impl<T> Fill<T> for Sum<T>
where
    Self: Sampler<T>,
    T: Clone + Num + NumCast,
{
    fn fill(&mut self, sample: T, n: NonZeroUsize) -> Result<(), Self::Error> {
        if let Some(n) = num::cast::<_, T>(n.get()) {
            self.fold(sample * n)
        } else {
            Ok(for _ in 0..n.get() {
                self.fold(sample.clone())?;
            })
        }
    }
}

impl Sampler<u64> for Sum<u64> {
    type Error = OverflowError;

    fn fold(&mut self, sample: u64) -> Result<(), Self::Error> {
        // TODO(https://fxbug.dev/351848566): Saturate `self.sum` on overflow.
        self.sum.checked_add(sample).inspect(|sum| self.sum = *sum).map(|_| ()).ok_or(OverflowError)
    }
}

impl Statistic for Sum<u64> {
    type Semantic = Gauge;
    type Sample = u64;
    type Aggregation = u64;

    fn reset(&mut self) {
        *self = Default::default();
    }

    fn aggregation(&self) -> Option<Self::Aggregation> {
        let sum = self.sum;
        Some(sum)
    }
}

/// Maximum statistic.
#[derive(Clone, Debug, Default)]
pub struct Max<T> {
    /// The maximum of samples.
    max: Option<T>,
}

impl<T> Max<T> {
    pub fn with_max(max: T) -> Self {
        Max { max: Some(max) }
    }
}

impl<T> Fill<T> for Max<T>
where
    Self: Sampler<T, Error = OverflowError>,
    T: Num + NumCast,
{
    fn fill(&mut self, sample: T, _n: NonZeroUsize) -> Result<(), Self::Error> {
        self.fold(sample)
    }
}

impl<T> Sampler<T> for Max<T>
where
    T: Ord + Copy + Num,
{
    type Error = OverflowError;

    fn fold(&mut self, sample: T) -> Result<(), Self::Error> {
        self.max = Some(match self.max {
            Some(max) => cmp::max(max, sample),
            _ => sample,
        });
        Ok(())
    }
}

impl<T> Statistic for Max<T>
where
    T: Ord + Copy + Zero + Num + NumCast + Default,
{
    type Semantic = Gauge;
    type Sample = T;
    type Aggregation = T;

    fn reset(&mut self) {
        *self = Default::default();
    }

    fn aggregation(&self) -> Option<Self::Aggregation> {
        self.max
    }
}

#[derive(Clone, Debug)]
pub struct Union<T> {
    bits: T,
}

impl<T> Union<T> {
    pub fn with_bits(bits: T) -> Self {
        Union { bits }
    }
}

impl<T> Default for Union<T>
where
    T: Zero,
{
    fn default() -> Self {
        Union::with_bits(T::zero())
    }
}

impl<T> Fill<T> for Union<T>
where
    Self: Sampler<T, Error = OverflowError>,
    T: Num + NumCast,
{
    fn fill(&mut self, sample: T, _n: NonZeroUsize) -> Result<(), Self::Error> {
        self.fold(sample)
    }
}

impl Sampler<u64> for Union<u64> {
    type Error = OverflowError;

    fn fold(&mut self, sample: u64) -> Result<(), Self::Error> {
        self.bits = self.bits | sample;
        Ok(())
    }
}

impl Statistic for Union<u64> {
    type Semantic = BitSet;
    type Sample = u64;
    type Aggregation = u64;

    fn reset(&mut self) {
        *self = Default::default();
    }

    fn aggregation(&self) -> Option<Self::Aggregation> {
        Some(self.bits)
    }
}

/// Maximum statistic that sums non-monotonic samples into the maximum.
///
/// This statistic is sensitive to overflow in the sum of samples with the non-monotonic sum.
#[derive(Clone, Debug)]
pub struct LatchMax<T> {
    /// The last observed sample.
    last: Option<T>,
    /// The maximum of samples and the non-monotonic sum.
    max: Option<T>,
    /// The sum of non-monotonic samples.
    sum: T,
}

impl<T> LatchMax<T> {
    pub fn with_max(max: T) -> Self
    where
        T: Zero,
    {
        LatchMax::with_max_and_sum(max, T::zero())
    }

    pub fn with_max_and_sum(max: T, sum: T) -> Self {
        LatchMax { last: None, max: Some(max), sum }
    }
}

impl<T> Default for LatchMax<T>
where
    T: Zero,
{
    fn default() -> Self {
        LatchMax { last: None, max: None, sum: T::zero() }
    }
}

impl<T> Fill<T> for LatchMax<T>
where
    Self: Sampler<T>,
{
    fn fill(&mut self, sample: T, _n: NonZeroUsize) -> Result<(), Self::Error> {
        self.fold(sample)
    }
}

impl Sampler<u64> for LatchMax<u64> {
    type Error = OverflowError;

    fn fold(&mut self, sample: u64) -> Result<(), Self::Error> {
        match self.last {
            Some(last) if sample < last => {
                // TODO(https://fxbug.dev/351848566): Saturate `self.sum` on overflow.
                self.sum = self.sum.checked_add(last).ok_or(OverflowError)?;
            }
            _ => {}
        }
        self.last = Some(sample);

        let sum = sample.checked_add(self.sum).ok_or(OverflowError)?;
        self.max = Some(match self.max {
            Some(max) => cmp::max(max, sum),
            _ => sum,
        });
        Ok(())
    }
}

impl Statistic for LatchMax<u64> {
    type Semantic = Counter;
    type Sample = u64;
    type Aggregation = u64;

    fn reset(&mut self) {}

    fn aggregation(&self) -> Option<Self::Aggregation> {
        self.max
    }
}

/// Post-aggregation transform.
///
/// A post-aggregation composes a [`Statistic`] and arbitrarily maps its aggregation. For example,
/// a transform may discretize the continuous aggregation of a statistic.
///
/// [`Statistic`]: crate::experimental::series::statistic::Statistic
#[derive(Clone, Copy, Debug)]
pub struct PostAggregation<F, R> {
    statistic: F,
    transform: R,
}

/// A post-aggregation of a function pointer.
///
/// This type definition describes a stateless and pure transform with a type name that can be
/// spelled in any context (i.e., no closure or other unnameable types occur).
pub type Transform<F, A> = PostAggregation<F, fn(Aggregation<F>) -> A>;

impl<F, R> PostAggregation<F, R>
where
    F: Default,
{
    /// Constructs a `PostAggregation` from a transform function.
    ///
    /// The default statistic is composed.
    pub fn from_transform(transform: R) -> Self {
        PostAggregation { statistic: F::default(), transform }
    }
}

impl<T, F, R> Fill<T> for PostAggregation<F, R>
where
    F: Fill<T>,
{
    fn fill(&mut self, sample: T, n: NonZeroUsize) -> Result<(), Self::Error> {
        self.statistic.fill(sample, n)
    }
}

impl<T, F, R> Sampler<T> for PostAggregation<F, R>
where
    F: Sampler<T>,
{
    type Error = F::Error;

    fn fold(&mut self, sample: T) -> Result<(), Self::Error> {
        self.statistic.fold(sample)
    }
}

impl<A, F, R> Statistic for PostAggregation<F, R>
where
    F: Statistic,
    R: Clone + Fn(F::Aggregation) -> A,
    A: Clone,
{
    type Semantic = F::Semantic;
    type Sample = F::Sample;
    type Aggregation = A;

    fn reset(&mut self) {
        self.statistic.reset()
    }

    fn aggregation(&self) -> Option<Self::Aggregation> {
        self.statistic.aggregation().map(|aggregation| (self.transform)(aggregation))
    }
}

/// Applies an arbitrary [reset function][`reset`] to a [`Statistic`].
///
/// [`reset`]: crate::experimental::series::statistic::Statistic::reset
/// [`Statistic`]: crate::experimental::series::statistic::Statistic
#[derive(Clone, Copy, Debug)]
pub struct Reset<F, R> {
    statistic: F,
    reset: R,
}

impl<F, R> Reset<F, R>
where
    F: Statistic,
    R: FnMut() -> F,
{
    pub fn with(statistic: F, reset: R) -> Self {
        Reset { statistic, reset }
    }
}

impl<F, R, T> Fill<T> for Reset<F, R>
where
    F: Fill<T>,
{
    fn fill(&mut self, sample: T, n: NonZeroUsize) -> Result<(), Self::Error> {
        self.statistic.fill(sample, n)
    }
}

impl<F, R, T> Sampler<T> for Reset<F, R>
where
    F: Sampler<T>,
{
    type Error = F::Error;

    fn fold(&mut self, sample: T) -> Result<(), Self::Error> {
        self.statistic.fold(sample)
    }
}

impl<F, R> Statistic for Reset<F, R>
where
    F: Statistic,
    R: Clone + FnMut() -> F,
{
    type Semantic = F::Semantic;
    type Sample = F::Sample;
    type Aggregation = F::Aggregation;

    fn reset(&mut self) {
        self.statistic = (self.reset)();
    }

    fn aggregation(&self) -> Option<Self::Aggregation> {
        self.statistic.aggregation()
    }
}

#[cfg(test)]
mod tests {
    use std::num::NonZeroUsize;

    use crate::experimental::series::statistic::{
        ArithmeticMean, LatchMax, Max, OverflowError, PostAggregation, Reset, Statistic, Sum, Union,
    };
    use crate::experimental::series::{Fill, Sampler};

    #[test]
    fn arithmetic_mean_aggregation() {
        let mut mean = ArithmeticMean::<f32>::default();
        mean.fold(1.0).unwrap();
        mean.fold(1.0).unwrap();
        mean.fold(1.0).unwrap();
        let aggregation = mean.aggregation().unwrap();
        assert!(aggregation > 0.99 && aggregation < 1.01); // ~ 1.0

        let mut mean = ArithmeticMean::<f32>::default();
        mean.fold(0.0).unwrap();
        mean.fold(1.0).unwrap();
        mean.fold(2.0).unwrap();
        let aggregation = mean.aggregation().unwrap();
        assert!(aggregation > 0.99 && aggregation < 1.01); // ~ 1.0
    }

    #[test]
    fn arithmetic_mean_aggregation_fill() {
        let mut mean = ArithmeticMean::<f32>::default();
        mean.fill(1.0, NonZeroUsize::new(1000).unwrap()).unwrap();
        let aggregation = mean.aggregation().unwrap();
        assert!(aggregation > 0.99 && aggregation < 1.01); // ~ 1.0
    }

    #[test]
    fn arithmetic_mean_count_overflow() {
        let mut mean = ArithmeticMean::<f32> { sum: 1.0, n: u64::MAX };
        let result = mean.fold(1.0);
        assert_eq!(result, Err(OverflowError));
    }

    #[test]
    fn sum_aggregation() {
        let mut sum = Sum::<u64>::default();
        sum.fold(1).unwrap();
        sum.fold(1).unwrap();
        sum.fold(1).unwrap();
        let aggregation = sum.aggregation().unwrap();
        assert_eq!(aggregation, 3);

        let mut sum = Sum::<u64>::default();
        sum.fold(0).unwrap();
        sum.fold(1).unwrap();
        sum.fold(2).unwrap();
        let aggregation = sum.aggregation().unwrap();
        assert_eq!(aggregation, 3);
    }

    #[test]
    fn sum_aggregation_fill() {
        let mut sum = Sum::<u64>::default();
        sum.fill(10, NonZeroUsize::new(1000).unwrap()).unwrap();
        let aggregation = sum.aggregation().unwrap();
        assert_eq!(aggregation, 10_000);
    }

    #[test]
    fn sum_overflow() {
        let mut sum = Sum::<u64> { sum: u64::MAX };
        let result = sum.fold(1);
        assert_eq!(result, Err(OverflowError));
    }

    #[test]
    fn max_aggregation() {
        let mut max = Max::<u64>::default();
        max.fold(0).unwrap();
        max.fold(1337).unwrap();
        max.fold(42).unwrap();
        let aggregation = max.aggregation().unwrap();
        assert_eq!(aggregation, 1337);
    }

    #[test]
    fn max_aggregation_fill() {
        let mut max = Max::<u64>::default();
        max.fill(42, NonZeroUsize::new(1000).unwrap()).unwrap();
        let aggregation = max.aggregation().unwrap();
        assert_eq!(aggregation, 42);
    }

    #[test]
    fn union_aggregation() {
        let mut value = Union::<u64>::default();
        value.fold(1 << 1).unwrap();
        value.fold(1 << 3).unwrap();
        value.fold(1 << 5).unwrap();
        let aggregation = value.aggregation().unwrap();
        assert_eq!(aggregation, 0b101010);
    }

    #[test]
    fn union_aggregation_fill() {
        let mut value = Union::<u64>::default();
        value.fill(1 << 2, NonZeroUsize::new(1000).unwrap()).unwrap();
        let aggregation = value.aggregation().unwrap();
        assert_eq!(aggregation, 0b100);
    }

    #[test]
    fn latch_max_aggregation() {
        let mut max = LatchMax::<u64>::default();
        max.fold(1).unwrap();
        max.fold(1).unwrap();
        max.fold(1).unwrap();
        let aggregation = max.aggregation().unwrap();
        assert_eq!(aggregation, 1);

        let mut max = LatchMax::<u64>::default();
        max.fold(0).unwrap();
        max.fold(1).unwrap();
        max.fold(2).unwrap();
        let aggregation = max.aggregation().unwrap();
        assert_eq!(aggregation, 2);

        let mut max = LatchMax::<u64>::default();
        max.fold(1).unwrap();
        max.fold(5).unwrap();
        max.fold(6).unwrap();
        max.fold(2).unwrap(); // Non-monotonic sum is six.
        max.fold(9).unwrap();
        max.fold(3).unwrap(); // Non-monotonic sum is 15 (6 + 9).
        max.fold(5).unwrap();
        let aggregation = max.aggregation().unwrap();
        assert_eq!(aggregation, 20);
    }

    #[test]
    fn latch_max_aggregation_fill() {
        let mut max = LatchMax::<u64>::default();
        max.fill(10, NonZeroUsize::new(1000).unwrap()).unwrap();
        let aggregation = max.aggregation().unwrap();
        assert_eq!(aggregation, 10);
    }

    #[test]
    fn latch_max_overflow_max() {
        let mut max = LatchMax::<u64>::default();
        max.fold(1).unwrap();
        max.fold(0).unwrap(); // Non-monotonic sum is one.
        let result = max.fold(u64::MAX); // Non-monotonic sum of one is added to `u64::MAX`.
        assert_eq!(result, Err(OverflowError));
    }

    #[test]
    fn post_sum_aggregation() {
        let mut sum = PostAggregation::<Sum<u64>, _>::from_transform(|sum| sum + 1);
        sum.fold(0).unwrap();
        sum.fold(1).unwrap();
        sum.fold(2).unwrap();
        let aggregation = sum.aggregation().unwrap();
        assert_eq!(aggregation, 4);
    }

    #[test]
    fn reset_with_function() {
        let mut sum = Reset::with(Sum::<u64>::default(), || Sum::with_sum(3));

        assert_eq!(sum.aggregation().unwrap(), 0);
        sum.fold(1).unwrap();
        assert_eq!(sum.aggregation().unwrap(), 1);

        sum.reset();
        assert_eq!(sum.aggregation().unwrap(), 3);
        sum.fold(1).unwrap();
        assert_eq!(sum.aggregation().unwrap(), 4);
    }
}