56 lines
1.3 KiB
Rust
56 lines
1.3 KiB
Rust
pub mod libdit {
|
|
use std::str::FromStr;
|
|
|
|
/// Represents a time in a StarDIT day
|
|
pub struct Dit {
|
|
pub deca: u16,
|
|
pub decim: u16,
|
|
pub desec: u16,
|
|
}
|
|
|
|
impl FromStr for Dit {
|
|
type Err = std::num::ParseIntError;
|
|
|
|
fn from_str(dit: &str) -> Result<Self, Self::Err> {
|
|
return Ok(Dit {
|
|
deca: u16::from_str_radix(&dit[0..1], 10)?,
|
|
decim: u16::from_str_radix(&dit[2..4], 10)?,
|
|
desec: u16::from_str_radix(&dit[5..7], 10)?,
|
|
});
|
|
}
|
|
}
|
|
|
|
/// Returns relative progress in the day, between 0 and 1 corresponding to `unix`
|
|
pub fn unix_to_dit(unix: f64) -> f64 {
|
|
return (unix - (12.0 * 3600.0)) % 86400.0 / 86400.0;
|
|
}
|
|
|
|
/// Returns a struct containing deca, decim and desec corresponding to `unix`
|
|
pub fn unix_to_dit_struct(unix: f64) -> Dit {
|
|
let dit = unix_to_dit(unix);
|
|
return Dit {
|
|
deca: (dit * 10.0 % 10.0) as u16,
|
|
decim: (dit * 1000.0 % 100.0) as u16,
|
|
desec: (dit * 100000.0 % 100.0) as u16,
|
|
};
|
|
}
|
|
|
|
/// Returns a string containing "deca.decim.desec" corresponding to `unix`
|
|
///
|
|
/// # Examples
|
|
///
|
|
/// ```
|
|
/// use libdit::libdit::unix_to_dit_string;
|
|
/// assert_eq!("9.99.99", unix_to_dit_string(1672574399.9999));
|
|
/// ```
|
|
pub fn unix_to_dit_string(unix: f64) -> String {
|
|
let dit = unix_to_dit_struct(unix);
|
|
return format!(
|
|
"{}.{}.{}",
|
|
dit.deca,
|
|
format!("{:0>2}", dit.decim),
|
|
format!("{:0>2}", dit.desec)
|
|
);
|
|
}
|
|
}
|