cmp_wrap/lib.rs
1//!
2//! Have you ever needed to compare the same data by different fields, depending on context?
3//! If so, this crate is for you!
4//!
5//! The main feature of this crate is a lightweight wrapper around types which lets you compare
6//! them after a mappeing (keying) function, meaning the parital_cmp operators ( < , > , == ...)
7//! are applied on the result of the keying function.
8//!
9//! There are two main modules in this crate: [permissive] and [strict].
10//! The permissive lets you compare different types as long as the keying function returns
11//! comparable types.
12//!
13//! The strict implementation woun't let you compare different types, and will save you from
14//! comparing by two different contexts.
15//!
16//! # Examples
17//!
18//! ## Using context
19//! You probably have some kind of context in which you would like to compare your values, such as
20//! length of vectors or the first value.
21//!
22//!
23//! ```
24//! use cmp_wrap::permissive::KeyCmpContext;
25//!
26//! let by_length = KeyCmpContext::new(|v: &Vec<_>| v.len());
27//!
28//! let long_vec = by_length.wrap(vec![1,2,3,4]);
29//! let short_vec = by_length.wrap(vec![1,2]);
30//!
31//! assert!(long_vec > short_vec, "The vec {:?} is longer then {:?}", long_vec, short_vec);
32//!
33//! ```
34//!
35//! One might want to use multiple contexts for the same data
36//!
37//! ```
38//! use cmp_wrap::strict::KeyCmpContext;
39//!
40//!
41//! let long_vec = vec![1,2,3,4];
42//! let short_vec = vec![4,2];
43//!
44//! let by_length = KeyCmpContext::new(|v: &&Vec<_>| v.len());
45//! let by_first_element = KeyCmpContext::new(|v: &&Vec<_>| v[0]);
46//!
47//! let by_length_long = by_length.wrap(&long_vec);
48//! let by_length_short = by_length.wrap(&short_vec);
49//!
50//! let by_first_element_long = by_first_element.wrap(&long_vec);
51//! let by_first_element_short = by_first_element.wrap(&short_vec);
52//!
53//! assert!(by_length_long > by_length_short,
54//! "The vec {:?} is longer then {:?}", long_vec, short_vec);
55//! assert!(by_first_element_long < by_first_element_short,
56//! "The vec's {:?} first element is smaller then {:?}'s", long_vec, short_vec);
57//!
58//! ```
59//!
60//! ## By direct creation
61//! you can define the key function on a "case by case" basis. This is not recommended.
62//! ```
63//! use cmp_wrap::permissive::CmpByKey;
64//!
65//! let len_as_key = |v: &Vec<_>| v.len();
66//!
67//! let long_vec = CmpByKey::new(vec![1,2,3,4], &len_as_key);
68//! let short_vec = CmpByKey::new(vec![1,2], &len_as_key);
69//!
70//! assert!(long_vec > short_vec, "The vector {:?} is longer then {:?}", long_vec, short_vec);
71//! ```
72
73pub mod strict;
74pub mod permissive;
75