netem-trace 0.5.0

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
//! This module contains some predefined packet delivery opportunity (PDO) trace models.
//!
//! Enabled with feature `pdo-model` or `model`.
//!
//! These traces have no concept of bandwidth. They say when bytes can be delivered,
//! like a mahimahi trace or the traces recorded by CellReplay.
//!
//! ## Predefined models
//!
//! - [`StaticHeavyPdo`]: A heavy PDO trace model with a fixed interval and size.
//! - [`TraceHeavyPdo`]: A heavy PDO trace model replaying a list of `(interval, bytes)`.
//! - [`RepeatedHeavyPdoPattern`]: A heavy PDO trace model with a repeated pattern.
//! - [`TraceLightPdo`]: A light PDO trace model replaying a list of [`LightPdo`] records,
//!   which can be loaded from a CellReplay light PDO trace with [`load_cellreplay_light_pdo_trace`].
//!
//! ## Examples
//!
//! ```
//! # use netem_trace::model::StaticHeavyPdoConfig;
//! # use netem_trace::{Duration, HeavyPdoTrace};
//! let mut static_pdo = StaticHeavyPdoConfig::new()
//!     .interval(Duration::from_millis(1))
//!     .bytes(1500)
//!     .count(2)
//!     .build();
//! assert_eq!(static_pdo.next_heavy_pdo(), Some((Duration::from_millis(1), 1500)));
//! assert_eq!(static_pdo.next_heavy_pdo(), Some((Duration::from_millis(1), 1500)));
//! assert_eq!(static_pdo.next_heavy_pdo(), None);
//! ```
//!
//! A more common use case is to build model from a configuration file (e.g. json file):
//!
//! ```
//! # use netem_trace::model::HeavyPdoTraceConfig;
//! # use netem_trace::{Duration, HeavyPdoTrace};
//! # #[cfg(feature = "human")]
//! # let config_file_content = "{\"RepeatedHeavyPdoPatternConfig\":{\"pattern\":[{\"TraceHeavyPdoConfig\":{\"pattern\":[[\"1ms\",1500],[\"0s\",1500]]}}],\"count\":2}}";
//! // The content would be "{\"RepeatedHeavyPdoPatternConfig\":{\"pattern\":[{\"TraceHeavyPdoConfig\":{\"pattern\":[[{\"secs\":0,\"nanos\":1000000},1500],[{\"secs\":0,\"nanos\":0},1500]]}}],\"count\":2}}"
//! // if the `human` feature is not enabled.
//! # #[cfg(not(feature = "human"))]
//! let config_file_content = "{\"RepeatedHeavyPdoPatternConfig\":{\"pattern\":[{\"TraceHeavyPdoConfig\":{\"pattern\":[[{\"secs\":0,\"nanos\":1000000},1500],[{\"secs\":0,\"nanos\":0},1500]]}}],\"count\":2}}";
//! let des: Box<dyn HeavyPdoTraceConfig> = serde_json::from_str(config_file_content).unwrap();
//! let mut model = des.into_model();
//! assert_eq!(model.next_heavy_pdo(), Some((Duration::from_millis(1), 1500)));
//! assert_eq!(model.next_heavy_pdo(), Some((Duration::ZERO, 1500)));
//! assert_eq!(model.next_heavy_pdo(), Some((Duration::from_millis(1), 1500)));
//! assert_eq!(model.next_heavy_pdo(), Some((Duration::ZERO, 1500)));
//! assert_eq!(model.next_heavy_pdo(), None);
//! ```
use crate::{Delay, Duration, HeavyPdoTrace, LightPdo, LightPdoTrace};
use dyn_clone::DynClone;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// This trait is used to convert a heavy PDO trace configuration into a heavy PDO 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 HeavyPdoTraceConfig: DynClone + Send + std::fmt::Debug {
    fn into_model(self: Box<Self>) -> Box<dyn HeavyPdoTrace>;
}

dyn_clone::clone_trait_object!(HeavyPdoTraceConfig);

/// This trait is used to convert a light PDO trace configuration into a light PDO trace model.
///
/// See [`HeavyPdoTraceConfig`] for why the configuration and the model are separated.
#[cfg_attr(feature = "serde", typetag::serde)]
pub trait LightPdoTraceConfig: DynClone + Send + std::fmt::Debug {
    fn into_model(self: Box<Self>) -> Box<dyn LightPdoTrace>;
}

dyn_clone::clone_trait_object!(LightPdoTraceConfig);

/// How many bytes one PDO can deliver in CellReplay (both heavy and light PDO traces).
///
/// It is the default PDO size of [`StaticHeavyPdo`] and [`TraceLightPdo`].
/// For mahimahi traces, use `MAHIMAHI_PDO_BYTES` (1504 bytes) instead.
pub const CELLREPLAY_PDO_SIZE: u64 = 1400;

/// The model of a static heavy PDO trace.
///
/// This model always returns the same `(interval, bytes)` for `count` times.
///
/// If the `count` is 0, it will be repeated forever.
///
/// If `bytes` is not set, it defaults to [`CELLREPLAY_PDO_SIZE`].
///
/// ## Examples
///
/// ```
/// # use netem_trace::model::StaticHeavyPdoConfig;
/// # use netem_trace::{Duration, HeavyPdoTrace};
/// let mut static_pdo = StaticHeavyPdoConfig::new()
///     .interval(Duration::from_millis(1))
///     .bytes(1500)
///     .count(1)
///     .build();
/// assert_eq!(static_pdo.next_heavy_pdo(), Some((Duration::from_millis(1), 1500)));
/// assert_eq!(static_pdo.next_heavy_pdo(), None);
/// ```
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub struct StaticHeavyPdo {
    pub interval: Duration,
    pub bytes: u64,
    pub count: usize,
    current_count: usize,
}

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

/// The model of a heavy PDO trace replaying a list of `(interval, bytes)`.
///
/// Each item is returned once, in order. Use [`RepeatedHeavyPdoPattern`] to repeat it.
///
/// ## Examples
///
/// ```
/// # use netem_trace::model::TraceHeavyPdoConfig;
/// # use netem_trace::{Duration, HeavyPdoTrace};
/// let mut trace_pdo = TraceHeavyPdoConfig::new()
///     .pattern(vec![
///         (Duration::from_millis(1), 3000),
///         (Duration::from_millis(2), 1500),
///     ])
///     .build();
/// assert_eq!(trace_pdo.next_heavy_pdo(), Some((Duration::from_millis(1), 3000)));
/// assert_eq!(trace_pdo.next_heavy_pdo(), Some((Duration::from_millis(2), 1500)));
/// assert_eq!(trace_pdo.next_heavy_pdo(), None);
/// ```
#[derive(Default, Debug, Clone, PartialEq)]
pub struct TraceHeavyPdo {
    pub pattern: Vec<(Duration, u64)>,
    pub index: usize,
}

/// The configuration struct for [`TraceHeavyPdo`].
///
/// See [`TraceHeavyPdo`] for more details.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(default))]
#[derive(Default, Debug, Clone, PartialEq)]
pub struct TraceHeavyPdoConfig {
    #[cfg_attr(
        all(feature = "serde", feature = "human"),
        serde(with = "heavy_pattern_serde")
    )]
    pub pattern: Vec<(Duration, u64)>,
}

/// The model contains an array of heavy PDO trace models.
///
/// Combine multiple heavy PDO trace models into one pattern,
/// and repeat the pattern for `count` times.
///
/// If `count` is 0, the pattern will be repeated forever.
///
/// ## Examples
///
/// ```
/// # use netem_trace::model::{HeavyPdoTraceConfig, RepeatedHeavyPdoPatternConfig, StaticHeavyPdoConfig};
/// # use netem_trace::{Duration, HeavyPdoTrace};
/// let pat = vec![
///     Box::new(
///         StaticHeavyPdoConfig::new()
///             .interval(Duration::from_millis(1))
///             .bytes(1500)
///             .count(1),
///     ) as Box<dyn HeavyPdoTraceConfig>,
///     Box::new(
///         StaticHeavyPdoConfig::new()
///             .interval(Duration::from_millis(2))
///             .bytes(3000)
///             .count(1),
///     ) as Box<dyn HeavyPdoTraceConfig>,
/// ];
/// let mut model = RepeatedHeavyPdoPatternConfig::new().pattern(pat).count(2).build();
/// assert_eq!(model.next_heavy_pdo(), Some((Duration::from_millis(1), 1500)));
/// assert_eq!(model.next_heavy_pdo(), Some((Duration::from_millis(2), 3000)));
/// assert_eq!(model.next_heavy_pdo(), Some((Duration::from_millis(1), 1500)));
/// assert_eq!(model.next_heavy_pdo(), Some((Duration::from_millis(2), 3000)));
/// assert_eq!(model.next_heavy_pdo(), None);
/// ```
#[derive(Default)]
pub struct RepeatedHeavyPdoPattern {
    pub pattern: Vec<Box<dyn HeavyPdoTraceConfig>>,
    pub count: usize,
    current_model: Option<Box<dyn HeavyPdoTrace>>,
    current_cycle: usize,
    current_pattern: usize,
}

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

/// The model of a light PDO trace replaying a list of [`LightPdo`] records.
///
/// Each record is returned once, in order. Every light PDO can deliver `pdo_size` bytes,
/// which defaults to [`CELLREPLAY_PDO_SIZE`].
///
/// ## Examples
///
/// ```
/// # use netem_trace::model::TraceLightPdoConfig;
/// # use netem_trace::{Delay, Duration, LightPdo, LightPdoTrace};
/// let record = LightPdo {
///     timestamp: Duration::from_millis(0),
///     base_delay: Delay::from_millis(30),
///     opportunities: vec![Duration::from_millis(0), Duration::from_millis(2)],
/// };
/// let mut trace_pdo = TraceLightPdoConfig::new()
///     .pattern(vec![record.clone()])
///     .pdo_size(1200)
///     .build();
/// assert_eq!(trace_pdo.pdo_size(), 1200);
/// assert_eq!(trace_pdo.next_light_pdo(), Some(record));
/// assert_eq!(trace_pdo.next_light_pdo(), None);
/// ```
#[derive(Default, Debug, Clone, PartialEq)]
pub struct TraceLightPdo {
    pub pattern: Vec<LightPdo>,
    pub pdo_size: u64,
    pub index: usize,
}

/// The configuration struct for [`TraceLightPdo`].
///
/// See [`TraceLightPdo`] for more details.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(default))]
#[derive(Default, Debug, Clone, PartialEq)]
pub struct TraceLightPdoConfig {
    pub pattern: Vec<LightPdo>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub pdo_size: Option<u64>,
}

impl HeavyPdoTrace for StaticHeavyPdo {
    fn next_heavy_pdo(&mut self) -> Option<(Duration, u64)> {
        if self.count != 0 && self.count == self.current_count {
            None
        } else {
            self.current_count += 1;
            Some((self.interval, self.bytes))
        }
    }
}

impl HeavyPdoTrace for TraceHeavyPdo {
    fn next_heavy_pdo(&mut self) -> Option<(Duration, u64)> {
        let pdo = self.pattern.get(self.index).copied();
        if pdo.is_some() {
            self.index += 1;
        }
        pdo
    }
}

impl HeavyPdoTrace for RepeatedHeavyPdoPattern {
    fn next_heavy_pdo(&mut self) -> Option<(Duration, u64)> {
        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_heavy_pdo() {
                Some(pdo) => Some(pdo),
                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_heavy_pdo()
                }
            }
        }
    }
}

impl LightPdoTrace for TraceLightPdo {
    fn next_light_pdo(&mut self) -> Option<LightPdo> {
        let record = self.pattern.get(self.index).cloned();
        if record.is_some() {
            self.index += 1;
        }
        record
    }

    fn pdo_size(&self) -> u64 {
        self.pdo_size
    }
}

impl StaticHeavyPdoConfig {
    pub fn new() -> Self {
        Self {
            interval: None,
            bytes: None,
            count: 0,
        }
    }

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

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

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

    pub fn build(self) -> StaticHeavyPdo {
        StaticHeavyPdo {
            interval: self.interval.unwrap_or_else(|| Duration::from_millis(1)),
            bytes: self.bytes.unwrap_or(CELLREPLAY_PDO_SIZE),
            count: self.count,
            current_count: 0,
        }
    }
}

impl TraceHeavyPdoConfig {
    pub fn new() -> Self {
        Self { pattern: vec![] }
    }

    pub fn pattern(mut self, pattern: Vec<(Duration, u64)>) -> Self {
        self.pattern = pattern;
        self
    }

    pub fn build(self) -> TraceHeavyPdo {
        TraceHeavyPdo {
            pattern: self.pattern,
            index: 0,
        }
    }
}

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

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

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

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

impl TraceLightPdoConfig {
    pub fn new() -> Self {
        Self {
            pattern: vec![],
            pdo_size: None,
        }
    }

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

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

    pub fn build(self) -> TraceLightPdo {
        TraceLightPdo {
            pattern: self.pattern,
            pdo_size: self.pdo_size.unwrap_or(CELLREPLAY_PDO_SIZE),
            index: 0,
        }
    }
}

/// Load a CellReplay light PDO (packet train) trace to a [`TraceLightPdoConfig`].
///
/// Each line of the trace is `timestamp base_delay pdo_0 pdo_1 ...`, separated by spaces,
/// all in milliseconds. The PDO times are measured from the start of the active period.
///
/// Returns `Err` string if the trace is invalid.
///
/// ## Examples
///
/// ```
/// # use netem_trace::model::load_cellreplay_light_pdo_trace;
/// # use netem_trace::{Delay, Duration, LightPdo, LightPdoTrace};
/// let mut trace = load_cellreplay_light_pdo_trace("0 30 0 2 2\n100 32 0 1")
///     .unwrap()
///     .build();
/// assert_eq!(
///     trace.next_light_pdo(),
///     Some(LightPdo {
///         timestamp: Duration::from_millis(0),
///         base_delay: Delay::from_millis(30),
///         opportunities: vec![
///             Duration::from_millis(0),
///             Duration::from_millis(2),
///             Duration::from_millis(2),
///         ],
///     })
/// );
/// ```
pub fn load_cellreplay_light_pdo_trace(trace: &str) -> Result<TraceLightPdoConfig, &'static str> {
    let mut pattern: Vec<LightPdo> = vec![];
    for line in trace.lines() {
        let mut words = line.split_whitespace();
        let mut next_ms = || -> Result<Option<Duration>, &'static str> {
            match words.next() {
                Some(word) => word
                    .parse::<u64>()
                    .map(|ms| Some(Duration::from_millis(ms)))
                    .map_err(|_| "values must be nonnegative integers in milliseconds"),
                None => Ok(None),
            }
        };
        let timestamp = next_ms()?.ok_or("invalid empty line")?;
        let base_delay: Delay = next_ms()?.ok_or("each line must have a base delay")?;
        let mut opportunities = vec![];
        while let Some(opportunity) = next_ms()? {
            if opportunities.last().is_some_and(|last| opportunity < *last) {
                return Err("PDO times must be monotonically nondecreasing");
            }
            opportunities.push(opportunity);
        }
        if pattern
            .last()
            .is_some_and(|last| timestamp < last.timestamp)
        {
            return Err("timestamps must be monotonically nondecreasing");
        }
        pattern.push(LightPdo {
            timestamp,
            base_delay,
            opportunities,
        });
    }
    if pattern.is_empty() {
        return Err("trace must have at least one line");
    }
    Ok(TraceLightPdoConfig::new().pattern(pattern))
}

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

impl_heavy_pdo_trace_config!(StaticHeavyPdoConfig);
impl_heavy_pdo_trace_config!(TraceHeavyPdoConfig);
impl_heavy_pdo_trace_config!(RepeatedHeavyPdoPatternConfig);

#[cfg_attr(feature = "serde", typetag::serde)]
impl LightPdoTraceConfig for TraceLightPdoConfig {
    fn into_model(self: Box<TraceLightPdoConfig>) -> Box<dyn LightPdoTrace> {
        Box::new(self.build())
    }
}

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

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

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

/// Implement the [`Forever`] trait for the heavy PDO trace model config (any struct implements [`HeavyPdoTraceConfig`]).
#[macro_export]
macro_rules! impl_forever_heavy_pdo {
    ($name:ident) => {
        impl Forever for $name {
            fn forever(self) -> RepeatedHeavyPdoPatternConfig {
                RepeatedHeavyPdoPatternConfig::new()
                    .pattern(vec![Box::new(self)])
                    .count(0)
            }
        }
    };
}

impl_forever_heavy_pdo!(StaticHeavyPdoConfig);
impl_forever_heavy_pdo!(TraceHeavyPdoConfig);

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

#[cfg(all(feature = "serde", feature = "human"))]
mod heavy_pattern_serde {
    use super::Duration;
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    pub fn serialize<S: Serializer>(
        v: &[(Duration, u64)],
        serializer: S,
    ) -> Result<S::Ok, S::Error> {
        v.iter()
            .map(|(interval, bytes)| (humantime_serde::Serde::from(interval), bytes))
            .collect::<Vec<_>>()
            .serialize(serializer)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(
        deserializer: D,
    ) -> Result<Vec<(Duration, u64)>, D::Error> {
        let v: Vec<(humantime_serde::Serde<Duration>, u64)> = Vec::deserialize(deserializer)?;
        Ok(v.into_iter()
            .map(|(interval, bytes)| (interval.into_inner(), bytes))
            .collect())
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_static_heavy_pdo() {
        let mut model = StaticHeavyPdoConfig::new()
            .interval(Duration::from_millis(2))
            .bytes(1400)
            .count(2)
            .build();
        assert_eq!(
            model.next_heavy_pdo(),
            Some((Duration::from_millis(2), 1400))
        );
        assert_eq!(
            model.next_heavy_pdo(),
            Some((Duration::from_millis(2), 1400))
        );
        assert_eq!(model.next_heavy_pdo(), None);
    }

    #[test]
    fn test_default_pdo_size() {
        let mut heavy = StaticHeavyPdoConfig::new().count(1).build();
        assert_eq!(
            heavy.next_heavy_pdo(),
            Some((Duration::from_millis(1), CELLREPLAY_PDO_SIZE))
        );

        let light = TraceLightPdoConfig::new().build();
        assert_eq!(light.pdo_size(), CELLREPLAY_PDO_SIZE);
        let light = load_cellreplay_light_pdo_trace("0 30 0").unwrap().build();
        assert_eq!(light.pdo_size(), CELLREPLAY_PDO_SIZE);
        let light = TraceLightPdoConfig::new().pdo_size(1500).build();
        assert_eq!(light.pdo_size(), 1500);
    }

    #[test]
    fn test_forever() {
        let mut model = TraceHeavyPdoConfig::new()
            .pattern(vec![(Duration::from_millis(1), 1500)])
            .forever()
            .build();
        for _ in 0..5 {
            assert_eq!(
                model.next_heavy_pdo(),
                Some((Duration::from_millis(1), 1500))
            );
        }
    }

    #[test]
    fn test_empty_repeated() {
        let mut model = RepeatedHeavyPdoPatternConfig::new().build();
        assert_eq!(model.next_heavy_pdo(), None);
    }

    #[test]
    fn test_load_cellreplay_light_pdo() {
        assert_eq!(
            load_cellreplay_light_pdo_trace(""),
            Err("trace must have at least one line")
        );
        assert_eq!(
            load_cellreplay_light_pdo_trace("0 30\n\n10 30"),
            Err("invalid empty line")
        );
        assert_eq!(
            load_cellreplay_light_pdo_trace("0"),
            Err("each line must have a base delay")
        );
        assert_eq!(
            load_cellreplay_light_pdo_trace("0 30 0 x"),
            Err("values must be nonnegative integers in milliseconds")
        );
        assert_eq!(
            load_cellreplay_light_pdo_trace("0 30 0 3 2"),
            Err("PDO times must be monotonically nondecreasing")
        );
        assert_eq!(
            load_cellreplay_light_pdo_trace("10 30 0\n5 30 0"),
            Err("timestamps must be monotonically nondecreasing")
        );

        // a line with no PDO is fine, it means no light PDO for that period
        let mut trace = load_cellreplay_light_pdo_trace("0 30 0 1 1 4\n100 25\n")
            .unwrap()
            .build();
        assert_eq!(
            trace.next_light_pdo(),
            Some(LightPdo {
                timestamp: Duration::ZERO,
                base_delay: Delay::from_millis(30),
                opportunities: [0, 1, 1, 4].map(Duration::from_millis).to_vec(),
            })
        );
        assert_eq!(
            trace.next_light_pdo(),
            Some(LightPdo {
                timestamp: Duration::from_millis(100),
                base_delay: Delay::from_millis(25),
                opportunities: vec![],
            })
        );
        assert_eq!(trace.next_light_pdo(), None);
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_serde() {
        let heavy = Box::new(
            RepeatedHeavyPdoPatternConfig::new()
                .pattern(vec![Box::new(TraceHeavyPdoConfig::new().pattern(vec![
                    (Duration::from_millis(1), 1500),
                    (Duration::ZERO, 1500),
                ])) as Box<dyn HeavyPdoTraceConfig>])
                .count(2),
        ) as Box<dyn HeavyPdoTraceConfig>;
        let ser_str = serde_json::to_string(&heavy).unwrap();
        #[cfg(feature = "human")]
        let des_str = "{\"RepeatedHeavyPdoPatternConfig\":{\"pattern\":[{\"TraceHeavyPdoConfig\":{\"pattern\":[[\"1ms\",1500],[\"0s\",1500]]}}],\"count\":2}}";
        #[cfg(not(feature = "human"))]
        let des_str = "{\"RepeatedHeavyPdoPatternConfig\":{\"pattern\":[{\"TraceHeavyPdoConfig\":{\"pattern\":[[{\"secs\":0,\"nanos\":1000000},1500],[{\"secs\":0,\"nanos\":0},1500]]}}],\"count\":2}}";
        assert_eq!(ser_str, des_str);
        let des: Box<dyn HeavyPdoTraceConfig> = serde_json::from_str(des_str).unwrap();
        let mut model = des.into_model();
        assert_eq!(
            model.next_heavy_pdo(),
            Some((Duration::from_millis(1), 1500))
        );

        let light = Box::new(load_cellreplay_light_pdo_trace("5 30 0 2").unwrap())
            as Box<dyn LightPdoTraceConfig>;
        let ser_str = serde_json::to_string(&light).unwrap();
        #[cfg(feature = "human")]
        let des_str = "{\"TraceLightPdoConfig\":{\"pattern\":[{\"timestamp\":\"5ms\",\"base_delay\":\"30ms\",\"opportunities\":[\"0s\",\"2ms\"]}]}}";
        #[cfg(not(feature = "human"))]
        let des_str = "{\"TraceLightPdoConfig\":{\"pattern\":[{\"timestamp\":{\"secs\":0,\"nanos\":5000000},\"base_delay\":{\"secs\":0,\"nanos\":30000000},\"opportunities\":[{\"secs\":0,\"nanos\":0},{\"secs\":0,\"nanos\":2000000}]}]}}";
        assert_eq!(ser_str, des_str);
        let des: Box<dyn LightPdoTraceConfig> = serde_json::from_str(des_str).unwrap();
        let mut model = des.into_model();
        assert_eq!(
            model.next_light_pdo().unwrap().opportunities,
            vec![Duration::ZERO, Duration::from_millis(2)]
        );
        assert_eq!(model.pdo_size(), CELLREPLAY_PDO_SIZE);

        // pdo_size is kept in the config when it is set
        let light = Box::new(
            TraceLightPdoConfig::new()
                .pattern(vec![LightPdo::default()])
                .pdo_size(1500),
        ) as Box<dyn LightPdoTraceConfig>;
        let ser_str = serde_json::to_string(&light).unwrap();
        assert!(ser_str.ends_with(",\"pdo_size\":1500}}"));
        let des: Box<dyn LightPdoTraceConfig> = serde_json::from_str(&ser_str).unwrap();
        assert_eq!(des.into_model().pdo_size(), 1500);
    }
}