based/src/format.rs
JMARyA 901af1c43c
All checks were successful
ci/woodpecker/push/test Pipeline was successful
update csrf
2025-01-08 20:46:01 +01:00

93 lines
2.6 KiB
Rust

/// Formats a `chrono::NaiveDate` into a representable `String`.
///
/// This function converts a `NaiveDate` object into a human-readable string representation.
///
/// # Arguments
/// * `date` - A reference to a `chrono::NaiveDate` instance.
///
/// # Returns
/// A `String` representation of the date.
///
/// # Example
/// ```
/// use based::format::format_date;
///
/// let date = chrono::NaiveDate::from_ymd(2023, 12, 18);
/// let formatted = format_date(&date);
/// assert_eq!(formatted, "2023-12-18");
/// ```
#[must_use]
pub fn format_date(date: &chrono::NaiveDate) -> String {
// TODO : Implement custom formatting
date.to_string()
}
/// Formats an integer into a representable `String`.
///
/// # Arguments
/// * `num` - An integer to format.
///
/// # Returns
/// A `String` representation of the number.
///
/// # Example
/// ```
/// use based::format::format_number;
///
/// let number = 12345;
/// let formatted = format_number(number);
/// assert_eq!(formatted, "12.345");
/// ```
#[must_use]
pub fn format_number(num: i32) -> String {
let mut str = num.to_string();
let mut result = String::new();
str = str.chars().rev().collect();
for (i, c) in str.chars().enumerate() {
if i != 0 && i % 3 == 0 {
result.push('.');
}
result.push(c);
}
result.chars().rev().collect()
}
/// Converts a number of seconds into a formatted string in `HH:MM:SS` or `MM:SS` format.
///
/// This function takes a floating-point number representing seconds and formats it
/// into a human-readable time string. If the duration is less than one hour, the
/// output is in `MM:SS` format. Otherwise, it is in `HH:MM:SS` format.
///
/// # Arguments
/// * `seconds` - A floating-point number representing the duration in seconds.
///
/// # Returns
/// A `String` formatted as `HH:MM:SS` or `MM:SS` depending on the input value.
///
/// # Example
/// ```
/// use based::format::format_seconds_to_hhmmss;
///
/// let duration = 3661.5; // 1 hour, 1 minute, and 1.5 seconds
/// let formatted = format_seconds_to_hhmmss(duration);
/// assert_eq!(formatted, "01:01:01");
///
/// let short_duration = 59.9; // Less than a minute
/// let formatted = format_seconds_to_hhmmss(short_duration);
/// assert_eq!(formatted, "00:59");
/// ```
#[must_use]
pub fn format_seconds_to_hhmmss(seconds: f64) -> String {
let total_seconds = seconds as u64;
let hours = total_seconds / 3600;
let minutes = (total_seconds % 3600) / 60;
let seconds = total_seconds % 60;
if hours != 0 {
format!("{hours:02}:{minutes:02}:{seconds:02}")
} else {
format!("{minutes:02}:{seconds:02}")
}
}