protoflow_blocks/types/
delay_type.rs

1// This is free and unencumbered software released into the public domain.
2
3use crate::prelude::{Duration, FromStr, Range, String};
4
5/// The type of delay (fixed or random) to apply to message relay.
6#[derive(Clone, Debug, Eq, Hash, PartialEq)]
7#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
8pub enum DelayType {
9    #[cfg_attr(
10        feature = "serde",
11        serde(deserialize_with = "duration_str::deserialize_duration")
12    )]
13    Fixed(Duration),
14
15    Random(Range<Duration>),
16}
17
18impl Default for DelayType {
19    fn default() -> Self {
20        Self::Fixed(Duration::from_secs(1))
21    }
22}
23
24impl FromStr for DelayType {
25    type Err = InvalidDelayType;
26
27    fn from_str(input: &str) -> Result<Self, Self::Err> {
28        // TODO: parse random range parameters as well
29        Ok(match input.trim() {
30            "" => Self::default(),
31            "random" | "rand" => Self::Random(Range {
32                start: Duration::from_secs_f64(0.),
33                end: Duration::from_secs_f64(1.),
34            }),
35            input => duration_str::parse_std(input).map(Self::Fixed)?,
36        })
37    }
38}
39
40#[derive(Clone, Debug, Eq, PartialEq)]
41pub enum InvalidDelayType {
42    InvalidDuration(String),
43}
44
45impl From<String> for InvalidDelayType {
46    fn from(input: String) -> Self {
47        InvalidDelayType::InvalidDuration(input)
48    }
49}