Function writeable::cmp_bytes

source ·
pub fn cmp_bytes(writeable: &impl Writeable, other: &[u8]) -> Ordering
Expand description

Compares the contents of a Writeable to the given bytes without allocating a String to hold the Writeable contents.

This returns a lexicographical comparison, the same as if the Writeable were first converted to a String and then compared with Ord. For a string ordering suitable for display to end users, use a localized collation crate, such as icu_collator.

§Examples

use core::cmp::Ordering;
use core::fmt;
use writeable::Writeable;

struct WelcomeMessage<'s> {
    pub name: &'s str,
}

impl<'s> Writeable for WelcomeMessage<'s> {
    // see impl in Writeable docs
}

let message = WelcomeMessage { name: "Alice" };
let message_str = message.write_to_string();

assert_eq!(Ordering::Equal, writeable::cmp_bytes(&message, b"Hello, Alice!"));

assert_eq!(Ordering::Greater, writeable::cmp_bytes(&message, b"Alice!"));
assert_eq!(Ordering::Greater, (*message_str).cmp("Alice!"));

assert_eq!(Ordering::Less, writeable::cmp_bytes(&message, b"Hello, Bob!"));
assert_eq!(Ordering::Less, (*message_str).cmp("Hello, Bob!"));