pdc-core 0.1.2

A network load testing library
Documentation
use super::Scenario;
use std::time::Duration;

/// Composite scenario takes in a list of scenarios and concatenates them together
#[derive(Clone)]
pub struct CompositeScenario {
    pub scenarios: Vec<Box<dyn Scenario>>,
    start_times: Vec<u128>,
    duration: u128,
}

impl CompositeScenario {
    pub fn append_scenario(&mut self, scene: Box<dyn Scenario>) {
        self.start_times.push(self.duration);
        self.duration += scene.duration();
        self.scenarios.push(scene);
    }

    pub fn new(scenarios: Vec<Box<dyn Scenario>>) -> Self {
        let mut duration = 0;
        let mut start_time = 0;
        let mut start_times = Vec::new();
        for scene in scenarios.iter() {
            start_times.push(start_time);
            duration += scene.duration();
            start_time = duration;
        }

        CompositeScenario {
            scenarios,
            start_times,
            duration,
        }
    }
}

impl Scenario for CompositeScenario {
    fn rate(&self, time_elasped: Duration) -> f32 {
        let time = time_elasped.as_millis();
        let idx: usize;
        match self
            .start_times
            .iter()
            .filter(|x| **x <= time_elasped.as_millis())
            .max()
        {
            Some(i) => match self.start_times.iter().position(|&x| x == *i) {
                Some(i) => idx = i,
                _ => return 0.,
            },
            None => return 0.,
        }
        let scene = self.scenarios.get(idx).unwrap();
        let scene_time = time - self.start_times[idx];
        scene.rate(Duration::from_millis(scene_time.try_into().unwrap()))
    }

    fn duration(&self) -> u128 {
        self.duration
    }

    fn max_rate(&self) -> f32 {
        let mut max = 0.;
        for s in self.scenarios.iter() {
            let r = s.max_rate();
            if r > max {
                max = r;
            }
        }
        max
    }
}