ckey 0.4.3

CKey is a consistent hash key library.
Documentation
// Copyright (C) 2024 Christian Mauduit <ufoot@ufoot.org>

use crate::key::CKey;
use std::fmt::Formatter;

impl std::fmt::Debug for CKey {
    /// Debug-print a key.
    ///
    /// The representation we use is an hex dump, the way you
    /// would write down the 2^256 integer corresponding to the key.
    ///
    /// # Examples
    /// ```
    /// use ckey::CKey;
    /// use std::convert::TryFrom;
    ///
    /// let k = CKey::parse("12345678ffffffff01234567fffffffff00123456ffffffff0012345ffffffff").unwrap();
    /// assert_eq!("12345678ffffffff01234567fffffffff00123456ffffffff0012345ffffffff", format!("{:?}", k));
    /// ```
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
        write!(
            f,
            "{:016x}{:016x}{:016x}{:016x}",
            self.data[0], self.data[1], self.data[2], self.data[3]
        )
    }
}

impl std::fmt::Display for CKey {
    /// Pretty-print a key.
    ///
    /// The representation we use is a 9-digits decimal float number,
    /// 11 chars in total, including a leading "0.".
    ///
    /// The reason for this is -> 1 billion keys is enough to tell
    /// them apart, there *CAN* be collisions, but it should remain rare.
    /// To check for equality, use == operator, do not compare string reprs.
    ///
    /// At the same time, decimals between 0 and 1 are easier to reason
    /// about when debugging, much more than 64 chars hexa dumps.
    ///
    /// # Examples
    /// ```
    /// use ckey::CKey;
    /// use std::convert::TryFrom;
    ///
    /// let k = CKey::parse("12345678ffffffff01234567fffffffff00123456ffffffff0012345ffffffff").unwrap();
    /// assert_eq!("0.071111111", format!("{}", k));
    /// ```
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:0.9}", f64::from(*self))
    }
}

#[cfg(test)]
mod tests {
    use super::CKey;

    #[test]
    fn test_fmt_debug() {
        assert_eq!(
            "0000000000000000000000000000000000000000000000000000000000000000",
            format!("{:?}", CKey::zero())
        );
        assert_eq!(
            "0000000000000000000000000000000000000000000000000000000000000001",
            format!("{:?}", CKey::unit())
        );
        assert_eq!(
            "8000000000000000000000000000000000000000000000000000000000000000",
            format!("{:?}", CKey::halfway())
        );
        assert_eq!(
            "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
            format!("{:?}", CKey::last())
        );
    }

    #[test]
    fn test_fmt_display() {
        assert_eq!("0.000000000", format!("{}", CKey::zero()));
        assert_eq!("0.000000000", format!("{}", CKey::unit()));
        assert_eq!("0.500000000", format!("{}", CKey::halfway()));
        assert_eq!("1.000000000", format!("{}", CKey::last()));
    }
}