PartialOrdBy

Trait PartialOrdBy 

Source
pub trait PartialOrdBy<T>: PartialEq {
    // Required method
    fn partial_cmp_by(&self, a: &T, b: &T) -> Option<Ordering>;
}
Expand description

Trait used by UseSorter to sort a struct by a specific field. This must be implemented on the field enum. Type T represents the struct (table row) that is being sorted.

The implementation should use the PartialOrd::partial_cmp trait to compare the field values and return the result. For example:

struct MyStruct {
    first: String,
    second: f64, // <- Note: can return None if f64::NAN
}

enum MyStructField {
    First,
    Second,
}

impl PartialOrdBy<MyStruct> for MyStructField {
    fn partial_cmp_by(&self, a: &MyStruct, b: &MyStruct) -> Option<std::cmp::Ordering> {
        match self {
            MyStructField::First => a.first.partial_cmp(&b.first),
            MyStructField::Second => a.second.partial_cmp(&b.second),
        }
    }
}

Be careful when using Option::None or a custom enum to represent missing data (NULL values). As partial_cmp as None is less than Some:

assert_eq!(Ordering::Less, None.cmp(&Some(0)));

Required Methods§

Source

fn partial_cmp_by(&self, a: &T, b: &T) -> Option<Ordering>

Compare two values of type T by the field’s enum. Return values of None are treated as NULL values. See Sortable for more information.

Be careful when comparing types like Option which implement Ord. This means that None and Some have an order where we might use them as unknown / NULL values. This can be a surprise.

Another issue is f64 only implements PartialOrd and not Ord because a value can hold f64::NAN. In this situation partial_cmp will return None and we’ll treat these values as NULL as expected.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§