use serde::{Deserialize, Serialize};
use crate::tag::{Tag, Tagged};
const TYPE_NAME: &str = "duration";
const SECONDS_IN_MINUTE: f64 = 60.0;
const MINUTES_IN_HOUR: f64 = 60.0;
const HOURS_IN_DAY: f64 = 24.0;
const DAYS_IN_WEEK: f64 = 7.0;
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
#[serde(from = "DurationTypst", into = "DurationTypst")]
pub struct Duration {
seconds: f64,
}
impl Duration {
pub const fn new(seconds: f64) -> Self {
Self { seconds }
}
pub const fn builder() -> DurationBuilder {
DurationBuilder {
seconds: 0.0,
minutes: 0.0,
hours: 0.0,
days: 0.0,
weeks: 0.0,
}
}
pub const fn seconds(&self) -> f64 {
self.seconds
}
pub const fn minutes(&self) -> f64 {
self.seconds() / SECONDS_IN_MINUTE
}
pub const fn hours(&self) -> f64 {
self.minutes() / MINUTES_IN_HOUR
}
pub const fn days(&self) -> f64 {
self.hours() / HOURS_IN_DAY
}
pub const fn weeks(&self) -> f64 {
self.days() / DAYS_IN_WEEK
}
}
pub struct DurationBuilder {
seconds: f64,
minutes: f64,
hours: f64,
days: f64,
weeks: f64,
}
impl DurationBuilder {
pub const fn seconds(mut self, seconds: f64) -> Self {
self.seconds = seconds;
self
}
pub const fn minutes(mut self, minutes: f64) -> Self {
self.minutes = minutes;
self
}
pub const fn hours(mut self, hours: f64) -> Self {
self.hours = hours;
self
}
pub const fn days(mut self, days: f64) -> Self {
self.days = days;
self
}
pub const fn weeks(mut self, weeks: f64) -> Self {
self.weeks = weeks;
self
}
pub const fn build(self) -> Duration {
Duration::new(
self.seconds
+ self.minutes * SECONDS_IN_MINUTE
+ self.hours * MINUTES_IN_HOUR * SECONDS_IN_MINUTE
+ self.days * HOURS_IN_DAY * MINUTES_IN_HOUR * SECONDS_IN_MINUTE
+ self.weeks * DAYS_IN_WEEK * HOURS_IN_DAY * MINUTES_IN_HOUR * SECONDS_IN_MINUTE,
)
}
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
struct DurationTypst {
typwire_type: Tag<Duration>,
seconds: f64,
}
impl Tagged for Duration {
const TYPE_NAME: &'static str = TYPE_NAME;
}
impl From<Duration> for DurationTypst {
fn from(value: Duration) -> Self {
Self {
typwire_type: Tag::new(),
seconds: value.seconds,
}
}
}
impl From<DurationTypst> for Duration {
fn from(value: DurationTypst) -> Self {
Self {
seconds: value.seconds,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builder() {
let duration = Duration::builder()
.seconds(4.0)
.minutes(2.0)
.hours(1.0)
.build();
assert_eq!(Duration { seconds: 3724.0 }, duration)
}
}