netem-trace 0.4.4

A library for for generating network emulation trace.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
//! This module contains some predefined delay per-packet trace models.
//!
//! Enabled with feature `delay-per-packet-model` or `model`.
//!
//! ## Predefined models
//!
//! - [`StaticDelayPerPacket`]: A trace model with static delay.
//! - [`RepeatedDelayPerPacketPattern`]: A trace model with a repeated delay pattern.
//! - [`NormalizedDelayPerPacket`]: A trace model whose delay subjects to a normal distribution (can set upper and lower bounds, and can configure it to be truncated with `truncated-normal` feature enabled).
//!
//! ## Examples
//!
//! An example to build model from configuration:
//!
//! ```
//! # use netem_trace::model::StaticDelayPerPacketConfig;
//! # use netem_trace::{Delay, DelayPerPacketTrace};
//! let mut static_delay = StaticDelayPerPacketConfig::new()
//!     .delay(Delay::from_millis(10))
//!     .count(2)
//!     .build();
//! assert_eq!(static_delay.next_delay(), Some(Delay::from_millis(10)));
//! assert_eq!(static_delay.next_delay(), Some(Delay::from_millis(10)));
//! assert_eq!(static_delay.next_delay(), None);
//! ```
//!
//! A more common use case is to build model from a configuration file (e.g. json file):
//!
//! ```
//! # use netem_trace::model::DelayPerPacketTraceConfig;
//! # use netem_trace::{Delay, DelayPerPacketTrace};
//! # #[cfg(feature = "human")]
//! # let config_file_content = "{\"RepeatedDelayPerPacketPatternConfig\":{\"pattern\":[{\"StaticDelayPerPacketConfig\":{\"delay\":\"10ms\",\"count\":1}},{\"StaticDelayPerPacketConfig\":{\"delay\":\"20ms\",\"count\":1}}],\"count\":2}}";
//! // The content would be "{\"RepeatedDelayPerPacketPatternConfig\":{\"pattern\":[{\"StaticDelayPerPacketConfig\":{\"delay\":{\"secs\":0,\"nanos\":10000000},\"count\":1}},{\"StaticDelayPerPacketConfig\":{\"delay\":{\"secs\":0,\"nanos\":20000000},\"count\":1}}],\"count\":2}}"
//! // if the `human` feature is not enabled.
//! # #[cfg(not(feature = "human"))]
//! let config_file_content = "{\"RepeatedDelayPerPacketPatternConfig\":{\"pattern\":[{\"StaticDelayPerPacketConfig\":{\"delay\":{\"secs\":0,\"nanos\":10000000},\"count\":1}},{\"StaticDelayPerPacketConfig\":{\"delay\":{\"secs\":0,\"nanos\":20000000},\"count\":1}}],\"count\":2}}";
//! let des: Box<dyn DelayPerPacketTraceConfig> = serde_json::from_str(config_file_content).unwrap();
//! let mut model = des.into_model();
//! assert_eq!(
//!     model.next_delay(),
//!     Some(Delay::from_millis(10))
//! );
//! assert_eq!(
//!     model.next_delay(),
//!     Some(Delay::from_millis(20))
//! );
//! assert_eq!(
//!     model.next_delay(),
//!     Some(Delay::from_millis(10))
//! );
//! assert_eq!(
//!     model.next_delay(),
//!     Some(Delay::from_millis(20))
//! );
//! assert_eq!(model.next_delay(), None);
//! ```
use crate::{Delay, DelayPerPacketTrace};
use dyn_clone::DynClone;

const DEFAULT_RNG_SEED: u64 = 42; // Some documentation will need corrections if this changes

/// This trait is used to convert a per-packet delay trace configuration into a per-packet delay trace model.
///
/// Since trace model is often configured with files and often has inner states which
/// is not suitable to be serialized/deserialized, this trait makes it possible to
/// separate the configuration part into a simple struct for serialization/deserialization, and
/// construct the model from the configuration.
#[cfg_attr(feature = "serde", typetag::serde)]
pub trait DelayPerPacketTraceConfig: DynClone + Send + std::fmt::Debug {
    fn into_model(self: Box<Self>) -> Box<dyn DelayPerPacketTrace>;
}

dyn_clone::clone_trait_object!(DelayPerPacketTraceConfig);

use rand::{rngs::StdRng, RngCore, SeedableRng};
use rand_distr::{Distribution, LogNormal, Normal};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

#[cfg(feature = "truncated-normal")]
use super::solve_truncate::solve;

/// The model of a static per-packet delay trace.
///
/// This model always returns the same delay for the given amount of packets.
///
/// If the `count` is 0, the delay will be repeated forever.
///
/// ## Examples
///
/// ```
/// # use netem_trace::model::StaticDelayPerPacketConfig;
/// # use netem_trace::{Delay, DelayPerPacketTrace};
/// let mut static_delay = StaticDelayPerPacketConfig::new()
///     .delay(Delay::from_millis(10))
///     .count(2)
///     .build();
/// assert_eq!(static_delay.next_delay(), Some(Delay::from_millis(10)));
/// assert_eq!(static_delay.next_delay(), Some(Delay::from_millis(10)));
/// assert_eq!(static_delay.next_delay(), None);
/// ```
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub struct StaticDelayPerPacket {
    pub delay: Delay,
    pub count: usize,
    current_count: usize,
}

/// The configuration struct for [`StaticDelayPerPacket`].
///
/// See [`StaticDelayPerPacket`] for more details.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(default))]
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub struct StaticDelayPerPacketConfig {
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    #[cfg_attr(
        all(feature = "serde", feature = "human"),
        serde(with = "humantime_serde")
    )]
    pub delay: Option<Delay>,
    pub count: usize,
}

/// The model contains an array of per-packet delay trace models.
///
/// Combine multiple per-packet delay trace models into one per-packet delay pattern,
/// and repeat the pattern for `count` times.
///
/// If `count` is 0, the pattern will be repeated forever.
///
/// ## Examples
///
/// The most common use case is to read from a configuration file and
/// deserialize it into a [`RepeatedDelayPerPacketPatternConfig`]:
///
/// ```
/// use netem_trace::model::{StaticDelayPerPacketConfig, DelayPerPacketTraceConfig};
/// use netem_trace::{Delay, DelayPerPacketTrace};
/// #[cfg(feature = "human")]
/// let config_file_content = "{\"RepeatedDelayPerPacketPatternConfig\":{\"pattern\":[{\"StaticDelayPerPacketConfig\":{\"delay\":\"10ms\",\"count\":1}},{\"StaticDelayPerPacketConfig\":{\"delay\":\"20ms\",\"count\":1}}],\"count\":2}}";
/// // The content would be "{\"RepeatedDelayPerPacketPatternConfig\":{\"pattern\":[{\"StaticDelayPerPacketConfig\":{\"delay\":{\"secs\":0,\"nanos\":10000000},\"count\":1}},{\"StaticDelayPerPacketConfig\":{\"delay\":{\"secs\":0,\"nanos\":20000000},\"count\":1}}],\"count\":2}}"
/// // if the `human` feature is not enabled.
/// #[cfg(not(feature = "human"))]
/// let config_file_content = "{\"RepeatedDelayPerPacketPatternConfig\":{\"pattern\":[{\"StaticDelayPerPacketConfig\":{\"delay\":{\"secs\":0,\"nanos\":10000000},\"count\":1}},{\"StaticDelayPerPacketConfig\":{\"delay\":{\"secs\":0,\"nanos\":20000000},\"count\":1}}],\"count\":2}}";
/// let des: Box<dyn DelayPerPacketTraceConfig> = serde_json::from_str(config_file_content).unwrap();
/// let mut model = des.into_model();
/// assert_eq!(
///     model.next_delay(),
///     Some(Delay::from_millis(10))
/// );
/// assert_eq!(
///     model.next_delay(),
///     Some(Delay::from_millis(20))
/// );
/// assert_eq!(
///     model.next_delay(),
///     Some(Delay::from_millis(10))
/// );
/// assert_eq!(
///     model.next_delay(),
///     Some(Delay::from_millis(20))
/// );
/// assert_eq!(model.next_delay(), None);
/// ```
///
/// You can also build manually:
///
/// ```
/// # use netem_trace::model::{StaticDelayPerPacketConfig, DelayPerPacketTraceConfig, RepeatedDelayPerPacketPatternConfig};
/// # use netem_trace::{Delay, DelayPerPacketTrace};
/// let pat = vec![
///     Box::new(
///         StaticDelayPerPacketConfig::new()
///             .delay(Delay::from_millis(10))
///             .count(1),
///     ) as Box<dyn DelayPerPacketTraceConfig>,
///     Box::new(
///         StaticDelayPerPacketConfig::new()
///             .delay(Delay::from_millis(20))
///             .count(1),
///     ) as Box<dyn DelayPerPacketTraceConfig>,
/// ];
/// let ser = Box::new(RepeatedDelayPerPacketPatternConfig::new().pattern(pat).count(2)) as Box<dyn DelayPerPacketTraceConfig>;
/// let ser_str = serde_json::to_string(&ser).unwrap();
/// #[cfg(feature = "human")]
/// let json_str = "{\"RepeatedDelayPerPacketPatternConfig\":{\"pattern\":[{\"StaticDelayPerPacketConfig\":{\"delay\":\"10ms\",\"count\":1}},{\"StaticDelayPerPacketConfig\":{\"delay\":\"20ms\",\"count\":1}}],\"count\":2}}";
/// // The content would be "{\"RepeatedDelayPerPacketPatternConfig\":{\"pattern\":[{\"StaticDelayPerPacketConfig\":{\"delay\":{\"secs\":0,\"nanos\":10000000},\"count\":1}},{\"StaticDelayPerPacketConfig\":{\"delay\":{\"secs\":0,\"nanos\":20000000},\"count\":1}}],\"count\":2}}"
/// // if the `human` feature is not enabled.
/// #[cfg(not(feature = "human"))]
/// let json_str = "{\"RepeatedDelayPerPacketPatternConfig\":{\"pattern\":[{\"StaticDelayPerPacketConfig\":{\"delay\":{\"secs\":0,\"nanos\":10000000},\"count\":1}},{\"StaticDelayPerPacketConfig\":{\"delay\":{\"secs\":0,\"nanos\":20000000},\"count\":1}}],\"count\":2}}";
/// assert_eq!(ser_str, json_str);
/// ```
#[derive(Default)]
pub struct RepeatedDelayPerPacketPattern {
    pub pattern: Vec<Box<dyn DelayPerPacketTraceConfig>>,
    pub count: usize,
    current_model: Option<Box<dyn DelayPerPacketTrace>>,
    current_cycle: usize,
    current_pattern: usize,
}

/// The configuration struct for [`RepeatedDelayPerPacketPattern`].
///
/// See [`RepeatedDelayPerPacketPattern`] for more details.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(default))]
#[derive(Default, Debug, Clone)]
pub struct RepeatedDelayPerPacketPatternConfig {
    pub pattern: Vec<Box<dyn DelayPerPacketTraceConfig>>,
    pub count: usize,
}

/// The model of a per-packet delay trace subjects to a normal distribution.
///
/// The delay will subject to N(mean, std_dev²), but bounded within [lower_bound, upper_bound] (optional)
///
/// If the `count` is 0, the delay will be repeated forever, else it will be repeated `count` times.
///
/// ## Examples
///
/// A simple example without any bound on delay:
///
/// ```
/// # use netem_trace::model::NormalizedDelayPerPacketConfig;
/// # use netem_trace::{Delay, DelayPerPacketTrace};
/// let mut normal_delay = NormalizedDelayPerPacketConfig::new()
///     .mean(Delay::from_millis(12))
///     .std_dev(Delay::from_millis(1))
///     .count(2)
///     .seed(42)
///     .build();
/// assert_eq!(normal_delay.next_delay(), Some(Delay::from_nanos(12069428)));
/// assert_eq!(normal_delay.next_delay(), Some(Delay::from_nanos(12132938)));
/// assert_eq!(normal_delay.next_delay(), None);
/// ```
///
/// A more complex example with bounds on delay:
///
/// ```
/// # use netem_trace::model::NormalizedDelayPerPacketConfig;
/// # use netem_trace::{Delay, DelayPerPacketTrace};
/// let mut normal_delay = NormalizedDelayPerPacketConfig::new()
///     .mean(Delay::from_millis(12))
///     .std_dev(Delay::from_millis(1))
///     .count(2)
///     .seed(42)
///     .upper_bound(Delay::from_micros(12100))
///     .lower_bound(Delay::from_micros(11900))
///     .build();
/// assert_eq!(normal_delay.next_delay(), Some(Delay::from_nanos(12069428)));
/// assert_eq!(normal_delay.next_delay(), Some(Delay::from_nanos(12100000)));
/// assert_eq!(normal_delay.next_delay(), None);
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct NormalizedDelayPerPacket<Rng = StdRng>
where
    Rng: RngCore,
{
    pub mean: Delay,
    pub std_dev: Delay,
    pub upper_bound: Option<Delay>,
    pub lower_bound: Delay,
    pub seed: u64,
    pub count: usize,
    current_count: usize,
    rng: Rng,
    normal: Normal<f64>,
}

/// The configuration struct for [`NormalizedDelayPerPacket`].
///
/// See [`NormalizedDelayPerPacket`] for more details.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(default))]
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub struct NormalizedDelayPerPacketConfig {
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    #[cfg_attr(
        all(feature = "serde", feature = "human"),
        serde(with = "humantime_serde")
    )]
    pub mean: Option<Delay>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    #[cfg_attr(
        all(feature = "serde", feature = "human"),
        serde(with = "humantime_serde")
    )]
    pub std_dev: Option<Delay>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    #[cfg_attr(
        all(feature = "serde", feature = "human"),
        serde(with = "humantime_serde")
    )]
    pub upper_bound: Option<Delay>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    #[cfg_attr(
        all(feature = "serde", feature = "human"),
        serde(with = "humantime_serde")
    )]
    pub lower_bound: Option<Delay>,
    #[cfg_attr(feature = "serde", serde(default))]
    pub count: usize,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub seed: Option<u64>,
}
/// The model of a per-packet delay trace subjects to a log-normal distribution.
///
/// The delay will subject to Lognormal(μ, σ²), but bounded within [lower_bound, upper_bound] (optional)
/// The provided mean and std_dev are the one of the log-normal law and not the one of the underlying normal law.
///
/// If the `count` is 0, the delay will be repeated forever, else it will be repeated `count` times.
///
/// ## Examples
///
/// A simple example without any bound on delay:
///
/// ```
/// # use netem_trace::model::LogNormalizedDelayPerPacketConfig;
/// # use netem_trace::{Delay, DelayPerPacketTrace};
/// let mut log_normal_delay = LogNormalizedDelayPerPacketConfig::new()
///     .mean(Delay::from_millis(12))
///     .std_dev(Delay::from_millis(1))
///     .count(2)
///     .seed(42)
///     .build();
/// assert_eq!(log_normal_delay.next_delay(), Some(Delay::from_nanos(12027817)));
/// assert_eq!(log_normal_delay.next_delay(), Some(Delay::from_nanos(12091533)));
/// assert_eq!(log_normal_delay.next_delay(), None);
/// ```
///
/// A more complex example with bounds on delay:
///
/// ```
/// # use netem_trace::model::LogNormalizedDelayPerPacketConfig;
/// # use netem_trace::{Delay, DelayPerPacketTrace};
/// let mut log_normal_delay = LogNormalizedDelayPerPacketConfig::new()
///     .mean(Delay::from_millis(12))
///     .std_dev(Delay::from_millis(1))
///     .count(3)
///     .seed(42)
///     .upper_bound(Delay::from_micros(12100))
///     .lower_bound(Delay::from_micros(11900))
///     .build();
/// assert_eq!(log_normal_delay.next_delay(), Some(Delay::from_nanos(12027817)));
/// assert_eq!(log_normal_delay.next_delay(), Some(Delay::from_nanos(12091533)));
/// assert_eq!(log_normal_delay.next_delay(), Some(Delay::from_nanos(12100000)));
/// assert_eq!(log_normal_delay.next_delay(), None);
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LogNormalizedDelayPerPacket<Rng = StdRng>
where
    Rng: RngCore,
{
    pub mean: Delay,
    pub std_dev: Delay,
    pub upper_bound: Option<Delay>,
    pub lower_bound: Delay,
    pub seed: u64,
    pub count: usize,
    current_count: usize,
    rng: Rng,
    log_normal: LogNormal<f64>,
}

/// The configuration struct for [`LogNormalizedDelayPerPacket`].
///
/// See [`LogNormalizedDelayPerPacket`] for more details.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(default))]
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub struct LogNormalizedDelayPerPacketConfig {
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    #[cfg_attr(
        all(feature = "serde", feature = "human"),
        serde(with = "humantime_serde")
    )]
    pub mean: Option<Delay>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    #[cfg_attr(
        all(feature = "serde", feature = "human"),
        serde(with = "humantime_serde")
    )]
    pub std_dev: Option<Delay>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    #[cfg_attr(
        all(feature = "serde", feature = "human"),
        serde(with = "humantime_serde")
    )]
    pub upper_bound: Option<Delay>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    #[cfg_attr(
        all(feature = "serde", feature = "human"),
        serde(with = "humantime_serde")
    )]
    pub lower_bound: Option<Delay>,
    #[cfg_attr(feature = "serde", serde(default))]
    pub count: usize,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub seed: Option<u64>,
}

impl DelayPerPacketTrace for StaticDelayPerPacket {
    fn next_delay(&mut self) -> Option<Delay> {
        if self.count != 0 && self.count == self.current_count {
            None
        } else {
            self.current_count += 1;
            Some(self.delay)
        }
    }
}

impl DelayPerPacketTrace for RepeatedDelayPerPacketPattern {
    fn next_delay(&mut self) -> Option<Delay> {
        if self.pattern.is_empty() || (self.count != 0 && self.current_cycle >= self.count) {
            None
        } else {
            if self.current_model.is_none() {
                self.current_model = Some(self.pattern[self.current_pattern].clone().into_model());
            }
            match self.current_model.as_mut().unwrap().next_delay() {
                Some(delay) => Some(delay),
                None => {
                    self.current_model = None;
                    self.current_pattern += 1;
                    if self.current_pattern >= self.pattern.len() {
                        self.current_pattern = 0;
                        self.current_cycle += 1;
                        if self.count != 0 && self.current_cycle >= self.count {
                            return None;
                        }
                    }
                    self.next_delay()
                }
            }
        }
    }
}

impl<Rng: RngCore + Send> DelayPerPacketTrace for NormalizedDelayPerPacket<Rng> {
    fn next_delay(&mut self) -> Option<Delay> {
        if self.count != 0 && self.count == self.current_count {
            None
        } else {
            self.current_count += 1;
            let delay = self.normal.sample(&mut self.rng).max(0.0);
            let mut delay = Delay::from_secs_f64(delay);
            delay = delay.max(self.lower_bound);
            if let Some(upper_bound) = self.upper_bound {
                delay = delay.min(upper_bound);
            }
            Some(delay)
        }
    }
}

impl<Rng: RngCore + Send> DelayPerPacketTrace for LogNormalizedDelayPerPacket<Rng> {
    fn next_delay(&mut self) -> Option<Delay> {
        if self.count != 0 && self.count == self.current_count {
            None
        } else {
            self.current_count += 1;
            let delay = self.log_normal.sample(&mut self.rng).max(0.0);
            let mut delay = Delay::from_secs_f64(delay);
            delay = delay.max(self.lower_bound);
            if let Some(upper_bound) = self.upper_bound {
                delay = delay.min(upper_bound);
            }
            Some(delay)
        }
    }
}

impl StaticDelayPerPacketConfig {
    pub fn new() -> Self {
        Self {
            delay: None,
            count: 0,
        }
    }

    pub fn delay(mut self, delay: Delay) -> Self {
        self.delay = Some(delay);
        self
    }

    pub fn count(mut self, count: usize) -> Self {
        self.count = count;
        self
    }

    pub fn build(self) -> StaticDelayPerPacket {
        StaticDelayPerPacket {
            delay: self.delay.unwrap_or_else(|| Delay::from_millis(10)),
            count: self.count,
            current_count: 0,
        }
    }
}

impl RepeatedDelayPerPacketPatternConfig {
    pub fn new() -> Self {
        Self {
            pattern: vec![],
            count: 0,
        }
    }

    pub fn pattern(mut self, pattern: Vec<Box<dyn DelayPerPacketTraceConfig>>) -> Self {
        self.pattern = pattern;
        self
    }

    pub fn count(mut self, count: usize) -> Self {
        self.count = count;
        self
    }

    pub fn build(self) -> RepeatedDelayPerPacketPattern {
        RepeatedDelayPerPacketPattern {
            pattern: self.pattern,
            count: self.count,
            current_model: None,
            current_cycle: 0,
            current_pattern: 0,
        }
    }
}

impl NormalizedDelayPerPacketConfig {
    /// Creates an uninitialized config
    pub fn new() -> Self {
        Self {
            mean: None,
            std_dev: None,
            upper_bound: None,
            lower_bound: None,
            count: 0,
            seed: None,
        }
    }

    /// Sets the mean
    ///
    /// If the mean is not set, 10ms will be used.
    pub fn mean(mut self, mean: Delay) -> Self {
        self.mean = Some(mean);
        self
    }

    /// Sets the standard deviation
    ///
    /// If the standard deviation is not set, 0ms will be used.
    pub fn std_dev(mut self, std_dev: Delay) -> Self {
        self.std_dev = Some(std_dev);
        self
    }

    /// Sets the upper bound
    ///
    /// If the upper bound is not set, the upper bound will be the one of [`Delay`].
    pub fn upper_bound(mut self, upper_bound: Delay) -> Self {
        self.upper_bound = Some(upper_bound);
        self
    }

    /// Sets the lower bound
    ///
    /// If the lower bound is not set, 0ms will be used.
    pub fn lower_bound(mut self, lower_bound: Delay) -> Self {
        self.lower_bound = Some(lower_bound);
        self
    }

    /// Sets the number of packets to repeat
    ///
    /// If the count is not set, it will be set to 0 (ie, infinite repeat).
    pub fn count(mut self, count: usize) -> Self {
        self.count = count;
        self
    }

    /// Set the seed for a random generator
    ///
    /// If the seed is not set, `42` will be used.
    pub fn seed(mut self, seed: u64) -> Self {
        self.seed = Some(seed);
        self
    }

    /// Allows to use a randomly generated seed
    ///
    /// This is equivalent to: `self.seed(rand::random())`
    pub fn random_seed(mut self) -> Self {
        self.seed = Some(rand::random());
        self
    }

    /// Creates a new [`NormalizedDelayPerPacket`] corresponding to this config.
    ///
    /// The created model will use [`StdRng`] as source of randomness (the call is equivalent to `self.build_with_rng::<StdRng>()`).
    /// It should be sufficient for most cases, but [`StdRng`] is not a portable random number generator,
    /// so one may want to use a portable random number generator like [`ChaCha`](https://crates.io/crates/rand_chacha),
    /// to this end one can use [`build_with_rng`](Self::build_with_rng).
    pub fn build(self) -> NormalizedDelayPerPacket {
        self.build_with_rng()
    }

    /// Creates a new [`NormalizedDelayPerPacket`] corresponding to this config.
    ///
    /// Unlike [`build`](Self::build), this method let you choose the random generator.
    ///
    /// # Example
    /// ```rust
    /// # use netem_trace::model::NormalizedDelayPerPacketConfig;
    /// # use netem_trace::{Delay, DelayPerPacketTrace};
    /// # use rand::rngs::StdRng;
    /// # use rand_chacha::ChaCha20Rng;
    ///
    /// let normal_delay = NormalizedDelayPerPacketConfig::new()
    ///     .mean(Delay::from_millis(12))
    ///     .std_dev(Delay::from_millis(1))
    ///     .count(3)
    ///     .seed(42);
    ///
    /// let mut default_build = normal_delay.clone().build();
    /// let mut std_build = normal_delay.clone().build_with_rng::<StdRng>();
    /// // ChaCha is deterministic and portable, unlike StdRng
    /// let mut chacha_build = normal_delay.clone().build_with_rng::<ChaCha20Rng>();
    ///
    /// for cha in [12044676, 11754367, 11253775] {
    ///     let default = default_build.next_delay();
    ///     let std = std_build.next_delay();
    ///     let chacha = chacha_build.next_delay();
    ///
    ///     assert!(default.is_some());
    ///     assert_eq!(default, std);
    ///     assert_ne!(default, chacha);
    ///     assert_eq!(chacha, Some(Delay::from_nanos(cha)));
    /// }
    ///
    /// assert_eq!(default_build.next_delay(), None);
    /// assert_eq!(std_build.next_delay(), None);
    /// assert_eq!(chacha_build.next_delay(), None);
    /// ```
    pub fn build_with_rng<Rng: RngCore + SeedableRng>(self) -> NormalizedDelayPerPacket<Rng> {
        let mean = self.mean.unwrap_or_else(|| Delay::from_millis(10));
        let std_dev = self.std_dev.unwrap_or(Delay::ZERO);
        let upper_bound = self.upper_bound;
        let lower_bound = self.lower_bound.unwrap_or(Delay::ZERO);
        let count = self.count;
        let seed = self.seed.unwrap_or(DEFAULT_RNG_SEED);
        let rng = Rng::seed_from_u64(seed);
        let delay_mean = mean.as_secs_f64();
        let delay_std_dev = std_dev.as_secs_f64();
        let normal: Normal<f64> = Normal::new(delay_mean, delay_std_dev).unwrap();
        NormalizedDelayPerPacket {
            mean,
            std_dev,
            upper_bound,
            lower_bound,
            count,
            current_count: 0,
            seed,
            rng,
            normal,
        }
    }
}

#[cfg(feature = "truncated-normal")]
impl NormalizedDelayPerPacketConfig {
    /// This is another implementation for converting NormalizedPerPacketConfig into NormalizedDelayPerPacket, where the impact
    /// of truncation (`lower_bound` and `upper_bound` field) on the mathematical expectation of the distribution
    /// is taking account by modifying the center of the distribution.
    ///
    /// ## Examples
    ///
    /// ```
    ///
    /// # use netem_trace::model::NormalizedDelayPerPacketConfig;
    /// # use netem_trace::{Delay, DelayPerPacketTrace};
    ///
    /// let normal_delay = NormalizedDelayPerPacketConfig::new()
    ///     .mean(Delay::from_millis(12))
    ///     .std_dev(Delay::from_millis(12))
    ///     .count(1_000_000)
    ///     .seed(42);
    ///
    /// let mut default_build = normal_delay.clone().build();
    /// let mut truncate_build = normal_delay.clone().build_truncated();
    ///
    /// fn avg_delay(mut model: impl DelayPerPacketTrace) -> Delay {
    ///     let mut count = 0;
    ///     std::iter::from_fn( move ||{
    ///         model.next_delay()
    ///     }).inspect(|_| count += 1).sum::<Delay>() / count
    /// }
    ///
    /// assert_eq!(avg_delay(default_build), Delay::from_nanos(12998335)); // significantly higher than the expected mean
    /// assert_eq!(avg_delay(truncate_build), Delay::from_nanos(11998818));
    ///
    /// let normal_delay = NormalizedDelayPerPacketConfig::new()
    ///     .mean(Delay::from_millis(12))
    ///     .std_dev(Delay::from_millis(12))
    ///     .lower_bound(Delay::from_millis(8))
    ///     .upper_bound(Delay::from_millis(20))
    ///     .count(1_000_000)
    ///     .seed(42);
    ///
    /// let mut default_build = normal_delay.clone().build();
    /// let mut truncate_build = normal_delay.clone().build_truncated();
    ///
    /// assert_eq!(avg_delay(default_build),  Delay::from_nanos(13234261)); // significantly higher than the expected mean
    /// assert_eq!(avg_delay(truncate_build), Delay::from_nanos(11999151));
    ///
    /// ```
    pub fn build_truncated(self) -> NormalizedDelayPerPacket {
        self.build_truncated_with_rng()
    }

    /// Similar to [`build_truncated`](Self::build_truncated) but let you choose the random generator.
    ///
    /// See [`build`](Self::build) for details about the reason for using another random number generator than [`StdRng`].
    pub fn build_truncated_with_rng<Rng: SeedableRng + RngCore>(
        mut self,
    ) -> NormalizedDelayPerPacket<Rng> {
        let mean = self
            .mean
            .unwrap_or_else(|| Delay::from_millis(12))
            .as_secs_f64();
        let sigma = self.std_dev.unwrap_or(Delay::ZERO).as_secs_f64() / mean;
        let lower = self.lower_bound.unwrap_or(Delay::ZERO).as_secs_f64() / mean;
        let upper = self.upper_bound.map(|upper| upper.as_secs_f64() / mean);
        let new_mean = mean * solve(1f64, sigma, Some(lower), upper).unwrap_or(1f64);
        self.mean = Some(Delay::from_secs_f64(new_mean));
        self.build_with_rng()
    }
}

impl LogNormalizedDelayPerPacketConfig {
    /// Creates an uninitialized config
    pub fn new() -> Self {
        Self {
            mean: None,
            std_dev: None,
            upper_bound: None,
            lower_bound: None,
            count: 0,
            seed: None,
        }
    }

    /// Sets the mean
    ///
    /// If the mean is not set, 10ms will be used.
    pub fn mean(mut self, mean: Delay) -> Self {
        self.mean = Some(mean);
        self
    }

    /// Sets the standard deviation
    ///
    /// If the standard deviation is not set, 0ms will be used.
    pub fn std_dev(mut self, std_dev: Delay) -> Self {
        self.std_dev = Some(std_dev);
        self
    }

    /// Sets the upper bound
    ///
    /// If the upper bound is not set, the upper bound will be the one of [`Delay`].
    pub fn upper_bound(mut self, upper_bound: Delay) -> Self {
        self.upper_bound = Some(upper_bound);
        self
    }

    /// Sets the lower bound
    ///
    /// If the lower bound is not set, 0ms will be used.
    pub fn lower_bound(mut self, lower_bound: Delay) -> Self {
        self.lower_bound = Some(lower_bound);
        self
    }

    /// Sets the number of packets to repeat
    ///
    /// If the count is not set, it will be set to 0 (ie, infinite repeat).
    pub fn count(mut self, count: usize) -> Self {
        self.count = count;
        self
    }

    /// Set the seed for a random generator
    ///
    /// If the seed is not set, `42` will be used.
    pub fn seed(mut self, seed: u64) -> Self {
        self.seed = Some(seed);
        self
    }

    /// Allows to use a randomly generated seed
    ///
    /// This is equivalent to: `self.seed(rand::random())`
    pub fn random_seed(mut self) -> Self {
        self.seed = Some(rand::random());
        self
    }

    /// Creates a new [`LogNormalizedDelayPerPacket`] corresponding to this config.
    ///
    /// The created model will use [`StdRng`] as source of randomness (the call is equivalent to `self.build_with_rng::<StdRng>()`).
    /// It should be sufficient for most cases, but [`StdRng`] is not a portable random number generator,
    /// so one may want to use a portable random number generator like [`ChaCha`](https://crates.io/crates/rand_chacha),
    /// to this end one can use [`build_with_rng`](Self::build_with_rng).
    pub fn build(self) -> LogNormalizedDelayPerPacket {
        self.build_with_rng()
    }

    /// Creates a new [`LogNormalizedDelayPerPacket`] corresponding to this config.
    ///
    /// Unlike [`build`](Self::build), this method let you choose the random generator.
    ///
    /// # Example
    /// ```rust
    /// # use netem_trace::model::LogNormalizedDelayPerPacketConfig;
    /// # use netem_trace::{Delay, DelayPerPacketTrace};
    /// # use rand::rngs::StdRng;
    /// # use rand_chacha::ChaCha20Rng;
    ///
    /// let log_normal_delay = LogNormalizedDelayPerPacketConfig::new()
    ///     .mean(Delay::from_millis(12))
    ///     .std_dev(Delay::from_millis(1))
    ///     .count(3)
    ///     .seed(42);
    ///
    /// let mut default_build = log_normal_delay.clone().build();
    /// let mut std_build = log_normal_delay.clone().build_with_rng::<StdRng>();
    /// // ChaCha is deterministic and portable, unlike StdRng
    /// let mut chacha_build = log_normal_delay.clone().build_with_rng::<ChaCha20Rng>();
    ///
    /// for cha in [12003077, 11716668, 11238761] {
    ///     let default = default_build.next_delay();
    ///     let std = std_build.next_delay();
    ///     let chacha = chacha_build.next_delay();
    ///
    ///     assert!(default.is_some());
    ///     assert_eq!(default, std);
    ///     assert_ne!(default, chacha);
    ///     assert_eq!(chacha, Some(Delay::from_nanos(cha)));
    /// }
    ///
    /// assert_eq!(default_build.next_delay(), None);
    /// assert_eq!(std_build.next_delay(), None);
    /// assert_eq!(chacha_build.next_delay(), None);
    /// ```
    pub fn build_with_rng<Rng: SeedableRng + RngCore>(self) -> LogNormalizedDelayPerPacket<Rng> {
        let mean = self.mean.unwrap_or_else(|| Delay::from_millis(10));
        let std_dev = self.std_dev.unwrap_or(Delay::ZERO);
        let upper_bound = self.upper_bound;
        let lower_bound = self.lower_bound.unwrap_or(Delay::ZERO);
        let count = self.count;
        let seed = self.seed.unwrap_or(DEFAULT_RNG_SEED);
        let rng = Rng::seed_from_u64(seed);
        let delay_mean = mean.as_secs_f64();
        let delay_std_dev = std_dev.as_secs_f64();

        // Computing the mean and standard deviation of underlying normal Law
        // Because Lognormal(μ , σ²) has a mean of exp(μ + σ²/2) and a standard deviation of sqrt((exp(σ²) - 1) exp(2μ + σ²))
        // So we need to comput μ and σ, given the mean and standard deviation of the log-normal law
        let normal_std_dev = f64::sqrt(f64::ln(
            1.0 + (delay_std_dev.powi(2)) / (delay_mean.powi(2)),
        ));
        let normal_mean = f64::ln(delay_mean) - normal_std_dev.powi(2) / 2.;
        let log_normal: LogNormal<f64> = LogNormal::new(normal_mean, normal_std_dev).unwrap();

        LogNormalizedDelayPerPacket {
            mean,
            std_dev,
            upper_bound,
            lower_bound,
            count,
            current_count: 0,
            seed,
            rng,
            log_normal,
        }
    }
}

macro_rules! impl_delay_per_packet_trace_config {
    ($name:ident) => {
        #[cfg_attr(feature = "serde", typetag::serde)]
        impl DelayPerPacketTraceConfig for $name {
            fn into_model(self: Box<$name>) -> Box<dyn DelayPerPacketTrace> {
                Box::new(self.build())
            }
        }
    };
}

impl_delay_per_packet_trace_config!(StaticDelayPerPacketConfig);
impl_delay_per_packet_trace_config!(NormalizedDelayPerPacketConfig);
impl_delay_per_packet_trace_config!(LogNormalizedDelayPerPacketConfig);
impl_delay_per_packet_trace_config!(RepeatedDelayPerPacketPatternConfig);

impl<Model: DelayPerPacketTrace + 'static> From<Model> for Box<dyn DelayPerPacketTrace> {
    fn from(model: Model) -> Self {
        Box::new(model)
    }
}

/// Turn a [`DelayPerPacketTraceConfig`] into a forever repeated [`RepeatedDelayPerPacketPatternConfig`].
pub trait Forever: DelayPerPacketTraceConfig {
    fn forever(self) -> RepeatedDelayPerPacketPatternConfig;
}

/// Implement the [`Forever`] trait for the per-packet delay trace model config (any struct implements [`DelayPerPacketTraceConfig`]).
#[macro_export]
macro_rules! impl_forever_delay_per_packet {
    ($name:ident) => {
        impl Forever for $name {
            fn forever(self) -> RepeatedDelayPerPacketPatternConfig {
                RepeatedDelayPerPacketPatternConfig::new()
                    .pattern(vec![Box::new(self)])
                    .count(0)
            }
        }
    };
}

impl_forever_delay_per_packet!(StaticDelayPerPacketConfig);
impl_forever_delay_per_packet!(NormalizedDelayPerPacketConfig);

impl Forever for RepeatedDelayPerPacketPatternConfig {
    fn forever(self) -> RepeatedDelayPerPacketPatternConfig {
        self.count(0)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::model::StaticDelayPerPacketConfig;
    use crate::DelayPerPacketTrace;

    #[test]
    fn test_static_delay_model() {
        let mut static_delay = StaticDelayPerPacketConfig::new()
            .delay(Delay::from_millis(10))
            .count(1)
            .build();
        assert_eq!(static_delay.next_delay(), Some(Delay::from_millis(10)));
        assert_eq!(static_delay.next_delay(), None);
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_serde() {
        let a = vec![
            Box::new(
                StaticDelayPerPacketConfig::new()
                    .delay(Delay::from_millis(10))
                    .count(1),
            ) as Box<dyn DelayPerPacketTraceConfig>,
            Box::new(
                StaticDelayPerPacketConfig::new()
                    .delay(Delay::from_millis(20))
                    .count(1),
            ) as Box<dyn DelayPerPacketTraceConfig>,
        ];
        let ser = Box::new(
            RepeatedDelayPerPacketPatternConfig::new()
                .pattern(a)
                .count(2),
        ) as Box<dyn DelayPerPacketTraceConfig>;
        let ser_str = serde_json::to_string(&ser).unwrap();
        #[cfg(feature = "human")]
        let des_str = "{\"RepeatedDelayPerPacketPatternConfig\":{\"pattern\":[{\"StaticDelayPerPacketConfig\":{\"delay\":\"10ms\",\"count\":1}},{\"StaticDelayPerPacketConfig\":{\"delay\":\"20ms\",\"count\":1}}],\"count\":2}}";
        #[cfg(not(feature = "human"))]
        let des_str = "{\"RepeatedDelayPerPacketPatternConfig\":{\"pattern\":[{\"StaticDelayPerPacketConfig\":{\"delay\":{\"secs\":0,\"nanos\":10000000},\"count\":1}},{\"StaticDelayPerPacketConfig\":{\"delay\":{\"secs\":0,\"nanos\":20000000},\"count\":1}}],\"count\":2}}";
        assert_eq!(ser_str, des_str);
        let des: Box<dyn DelayPerPacketTraceConfig> = serde_json::from_str(des_str).unwrap();
        let mut model = des.into_model();
        assert_eq!(model.next_delay(), Some(Delay::from_millis(10)));
    }
}