Skip to main content

nil_server_types/
round.rs

1// Copyright (C) Call of Nil contributors
2// SPDX-License-Identifier: AGPL-3.0-only
3
4use serde::{Deserialize, Serialize};
5use std::time::Duration;
6
7/// Round duration, in minutes.
8#[derive(Copy, Debug, Deserialize, Serialize)]
9#[derive_const(Clone, PartialEq, Eq, PartialOrd, Ord)]
10#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
11pub struct RoundDuration(u16);
12
13impl RoundDuration {
14  pub const MIN: RoundDuration = Self(5);
15  pub const MAX: RoundDuration = Self(60 * 12);
16}
17
18impl RoundDuration {
19  pub const fn new(mins: u16) -> Self {
20    Self(mins.clamp(Self::MIN.0, Self::MAX.0))
21  }
22}
23
24impl const Default for RoundDuration {
25  fn default() -> Self {
26    Self::MIN
27  }
28}
29
30impl const From<u16> for RoundDuration {
31  fn from(value: u16) -> Self {
32    Self::new(value)
33  }
34}
35
36impl const From<Duration> for RoundDuration {
37  fn from(value: Duration) -> Self {
38    let mins = value.as_secs() / 60;
39    u16::try_from(mins)
40      .map(Self::new)
41      .unwrap_or(Self::MAX)
42  }
43}
44
45impl const From<RoundDuration> for Duration {
46  fn from(value: RoundDuration) -> Self {
47    Duration::from_mins(u64::from(value.0))
48  }
49}