plabble-codec 0.1.0

Plabble Transport Protocol codec
Documentation
use crate::abstractions::EPOCH;
use time::OffsetDateTime;

/// Convert a date to a Plabble timestamp
///
/// # Arguments
///
/// * `date` - the date to convert
///
/// # Returns
///
/// The Plabble timestamp
///
/// # Panics
///
/// Panics if the timestamp is too large to fit in a u32
pub fn to_timestamp(date: &OffsetDateTime) -> u32 {
    (date.unix_timestamp() - EPOCH)
        .try_into()
        .expect("Failed to fit timestamp into u32")
}

/// Convert a Plabble timestamp to a date
///
/// # Arguments
///
/// * `timestamp` - the timestamp to convert
///
/// # Returns
///
/// The date
///
/// # Panics
///
/// Panics if the timestamp is not valid
pub fn from_timestamp(timestamp: u32) -> OffsetDateTime {
    OffsetDateTime::from_unix_timestamp(timestamp as i64 + EPOCH).expect("Timestamp is not valid")
}

#[cfg(test)]
mod test {
    use time_macros::datetime;

    #[test]
    fn can_convert_date_to_timestamp() {
        let d1 = datetime!(2020-01-01 00:00:00 UTC);
        let d2 = datetime!(2020-01-01 00:01:00 UTC);
        let d3 = datetime!(2020-01-01 01:00:00 UTC);
        let d4 = datetime!(2023-03-21 18:41:30 UTC);

        assert_eq!(super::to_timestamp(&d1), 0);
        assert_eq!(super::to_timestamp(&d2), 60);
        assert_eq!(super::to_timestamp(&d3), 3600);
        assert_eq!(super::to_timestamp(&d4), 101587290);
    }

    #[test]
    fn can_convert_timestamp_to_date() {
        let d1 = datetime!(2020-01-01 00:00:00 UTC);
        let d2 = datetime!(2020-01-01 00:01:00 UTC);
        let d3 = datetime!(2020-01-01 01:00:00 UTC);
        let d4 = datetime!(2023-03-21 18:41:30 UTC);

        assert_eq!(super::from_timestamp(0), d1);
        assert_eq!(super::from_timestamp(60), d2);
        assert_eq!(super::from_timestamp(3600), d3);
        assert_eq!(super::from_timestamp(101587290), d4);
    }
}