use core::fmt::Debug;
#[derive(Debug, PartialEq)]
pub struct ParsedUnitValue<T: Eq + Debug = u8, U: Eq + Debug = u64> {
pub unit: T,
pub total: U,
}
#[inline]
pub fn parse_secs(total_secs: u64) -> ParsedUnitValue<u8, u64> {
ParsedUnitValue {
unit: (total_secs % 60) as u8,
total: total_secs / 60,
}
}
#[inline]
pub fn parse_mins(total_mins: u64) -> ParsedUnitValue<u8, u64> {
ParsedUnitValue {
unit: (total_mins % 60) as u8,
total: total_mins / 60,
}
}
#[inline]
pub fn parse_hours(total_hours: u64) -> ParsedUnitValue<u8, u64> {
ParsedUnitValue {
unit: (total_hours % 24) as u8,
total: total_hours / 24,
}
}
#[inline]
pub fn parse_days(total_days: u64) -> ParsedUnitValue<u16, u64> {
ParsedUnitValue {
unit: (total_days % 365) as u16,
total: total_days / 365,
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec;
#[test]
fn should_parse_seconds_and_minutes() {
let cases = vec![
(0, ParsedUnitValue { unit: 0, total: 0 }),
(1, ParsedUnitValue { unit: 1, total: 0 }),
(59, ParsedUnitValue { unit: 59, total: 0 }),
(60, ParsedUnitValue { unit: 0, total: 1 }),
(61, ParsedUnitValue { unit: 1, total: 1 }),
(119, ParsedUnitValue { unit: 59, total: 1 }),
(120, ParsedUnitValue { unit: 0, total: 2 }),
(121, ParsedUnitValue { unit: 1, total: 2 }),
(
3599,
ParsedUnitValue {
unit: 59,
total: 59,
},
),
(3600, ParsedUnitValue { unit: 0, total: 60 }),
(3601, ParsedUnitValue { unit: 1, total: 60 }),
];
for (actual, expected) in cases {
let sec_res = parse_secs(actual);
let min_res = parse_mins(actual);
assert_eq!(
sec_res, expected,
"Seconds -> Expected:{:?} Got:{:?}",
expected, sec_res
);
assert_eq!(
min_res, expected,
"Minutes -> Expected:{:?} Got:{:?}",
expected, min_res
);
}
}
#[test]
fn should_parse_hours() {
let cases = vec![
(0, ParsedUnitValue { unit: 0, total: 0 }),
(1, ParsedUnitValue { unit: 1, total: 0 }),
(23, ParsedUnitValue { unit: 23, total: 0 }),
(24, ParsedUnitValue { unit: 0, total: 1 }),
(25, ParsedUnitValue { unit: 1, total: 1 }),
(47, ParsedUnitValue { unit: 23, total: 1 }),
(48, ParsedUnitValue { unit: 0, total: 2 }),
(49, ParsedUnitValue { unit: 1, total: 2 }),
(
575,
ParsedUnitValue {
unit: 23,
total: 23,
},
),
(576, ParsedUnitValue { unit: 0, total: 24 }),
(577, ParsedUnitValue { unit: 1, total: 24 }),
];
for (actual, expected) in cases {
let res = parse_hours(actual);
assert_eq!(res, expected);
}
}
#[test]
fn should_parse_days() {
let cases = vec![
(0, ParsedUnitValue { unit: 0, total: 0 }),
(1, ParsedUnitValue { unit: 1, total: 0 }),
(
364,
ParsedUnitValue {
unit: 364,
total: 0,
},
),
(365, ParsedUnitValue { unit: 0, total: 1 }),
(366, ParsedUnitValue { unit: 1, total: 1 }),
];
for (actual, expected) in cases {
let res = parse_days(actual);
assert_eq!(res, expected);
}
}
}