use core::{
cmp::PartialOrd,
fmt::{self, Debug, Display, Formatter},
result,
time::Duration,
};
pub fn clamp<T>(value: T, min: T, max: T) -> T
where
T: PartialOrd,
{
assert!(min <= max);
if value < min {
min
} else if value > max {
max
} else {
value
}
}
pub enum SlotTime {
UserSpecified(Duration),
AutoGenerated(Duration),
}
#[derive(PartialEq)]
pub enum Error {
NoCommandGiven,
ChildProcessTerminatedWithSignal,
}
impl Debug for Error {
fn fmt(&self, f: &mut Formatter) -> result::Result<(), fmt::Error> {
write!(
f,
"{}",
match self {
Self::NoCommandGiven => "no command given",
Self::ChildProcessTerminatedWithSignal => "child process terminated with signal",
}
)
}
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter) -> result::Result<(), fmt::Error> {
Debug::fmt(self, f)
}
}
impl std::error::Error for Error {}
pub type Result<T> = result::Result<T, Error>;
pub type ExecutionResult = Result<()>;
#[cfg(test)]
mod tests {
use super::*;
mod clamp {
use super::clamp;
mod i32 {
use super::clamp;
#[test]
fn inside_range() {
assert_eq!(clamp(1_i32, 0_i32, 2_i32), 1_i32);
}
#[test]
fn below_range() {
assert_eq!(clamp(-1_i32, 0_i32, 2_i32), 0_i32);
}
#[test]
fn above_range() {
assert_eq!(clamp(3_i32, 0_i32, 2_i32), 2_i32);
}
}
#[test]
#[should_panic]
fn panics_if_not_ordered_properly() {
clamp(1_i32, 2_i32, 0_i32);
}
}
}