114 lines
3.2 KiB
Rust
114 lines
3.2 KiB
Rust
/// Structure to store time data in DDMMSS.SS format
|
|
#[derive(Debug, PartialEq)]
|
|
pub struct Time {
|
|
pub hours: u8, // Hours (00-23)
|
|
pub minutes: u8, // Minutes (00-59)
|
|
pub seconds: u8, // Seconds (00-59)
|
|
pub centiseconds: u8, // Centiseconds (00-99)
|
|
}
|
|
|
|
impl Time {
|
|
/// Constructor for Time struct, initializes all fields to 0
|
|
pub fn new() -> Self {
|
|
Time {
|
|
hours: 0,
|
|
minutes: 0,
|
|
seconds: 0,
|
|
centiseconds: 0,
|
|
}
|
|
}
|
|
|
|
/// Parse time from string in format "HHMMSS.SS"
|
|
pub fn parse(time_str: &str) -> Result<Self, &'static str> {
|
|
let mut time = Time::new();
|
|
|
|
if time_str.is_empty() {
|
|
return Ok(time);
|
|
}
|
|
|
|
// Split the time string into hours, minutes, seconds, and centiseconds
|
|
if time_str.len() >= 6 {
|
|
// Parse hours (first 2 characters)
|
|
time.hours = time_str[0..2]
|
|
.parse::<u8>()
|
|
.map_err(|_| "Invalid hours format")?;
|
|
|
|
// Parse minutes (next 2 characters)
|
|
time.minutes = time_str[2..4]
|
|
.parse::<u8>()
|
|
.map_err(|_| "Invalid minutes format")?;
|
|
|
|
// Parse seconds (next 2 characters)
|
|
time.seconds = time_str[4..6]
|
|
.parse::<u8>()
|
|
.map_err(|_| "Invalid seconds format")?;
|
|
|
|
// Parse centiseconds if available (after the decimal point)
|
|
if time_str.len() >= 9 && time_str.contains('.') {
|
|
time.centiseconds = time_str[7..9]
|
|
.parse::<u8>()
|
|
.map_err(|_| "Invalid centiseconds format")?;
|
|
}
|
|
} else {
|
|
return Err("Invalid time format: too short");
|
|
}
|
|
|
|
Ok(time)
|
|
}
|
|
|
|
/// Format time as a string in "HHMMSS.SS" format
|
|
pub fn to_string(&self) -> String {
|
|
format!(
|
|
"{:02}{:02}{:02}.{:02}",
|
|
self.hours, self.minutes, self.seconds, self.centiseconds
|
|
)
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn test_time_new() {
|
|
let time = Time::new();
|
|
assert_eq!(time.hours, 0);
|
|
assert_eq!(time.minutes, 0);
|
|
assert_eq!(time.seconds, 0);
|
|
assert_eq!(time.centiseconds, 0);
|
|
}
|
|
|
|
#[test]
|
|
fn test_time_parse() {
|
|
// Test with a valid time string
|
|
let time = Time::parse("123456.78").unwrap();
|
|
assert_eq!(time.hours, 12);
|
|
assert_eq!(time.minutes, 34);
|
|
assert_eq!(time.seconds, 56);
|
|
assert_eq!(time.centiseconds, 78);
|
|
|
|
// Test with an empty string
|
|
let time = Time::parse("").unwrap();
|
|
assert_eq!(time.hours, 0);
|
|
assert_eq!(time.minutes, 0);
|
|
assert_eq!(time.seconds, 0);
|
|
assert_eq!(time.centiseconds, 0);
|
|
|
|
// Test with an invalid string
|
|
let result = Time::parse("ABC");
|
|
assert!(result.is_err());
|
|
assert_eq!(result.unwrap_err(), "Invalid time format: too short");
|
|
}
|
|
|
|
#[test]
|
|
fn test_time_to_string() {
|
|
let time = Time {
|
|
hours: 12,
|
|
minutes: 34,
|
|
seconds: 56,
|
|
centiseconds: 78,
|
|
};
|
|
assert_eq!(time.to_string(), "123456.78");
|
|
}
|
|
}
|