weighted_list/
weighted_item.rs

1use std::{
2    fmt
3};
4
5use crate::root::*;
6
7
8pub type WItem<V,W> = WeightedItem<V,W>;
9
10
11/// An item in a `WeightedList`, with a `value` of type `V` and a `weight` of numerical type `W`.
12/// 
13/// For consistency and layout, `weight` always comes before `value` when ordering is relevant.
14/// 
15/// You should rarely find yourself constructing a `WeightedItem` by hand – instead, you'll usually interact with existing instances from a `WeightedList`.
16#[derive(Debug, Clone, Eq, PartialEq, Hash)]
17pub struct WeightedItem<V, W: Weight>
18{
19    /// The weight of the item. A non-negative number. `0` is technically valid, but not advised.
20    pub weight: W,
21
22    /// The value stored in the item.
23    pub value: V,
24}
25
26// == CONSTRUCTORS == //
27impl<V, W: Weight> WeightedItem<V,W>
28{
29    /// Construct a `WeightedItem` with `value` and a weight of `1`.
30    pub fn unit(value: V) -> Self
31    {
32        Self {
33            weight: W::one(),
34            value
35        }
36    }
37
38    /// Construct a `WeightedItem` with `value` and `weight`.
39    pub fn new(weight: W, value: V) -> Self
40    {
41        Self { weight, value }
42    }
43
44    /// Construct a `WeightedItem` from a `(weight, value)` pair.
45    pub fn from((weight, value): (W, V)) -> Self
46    {
47        Self { weight, value }
48    }
49}
50
51/// Construct a `WeightedItem` from a `(weight, value)` pair.
52/// 
53/// # Usage
54/// 
55/// ```
56/// # use weighted_list::*;
57/// let item = wit!(2.0, "sup");
58/// assert_eq!(item, WeightedItem::new(2.0, "sup"));
59/// ```
60#[macro_export]
61macro_rules! wit {
62    ( $weight: expr, $value: expr ) => {
63        WeightedItem::new($weight, $value)
64    };
65}
66
67// == CONVERSIONS == //
68impl<V, W: Weight> From<WeightedItem<V,W>> for (W, V)
69{
70    fn from(item: WeightedItem<V,W>) -> Self {
71        (item.weight, item.value)
72    }
73}
74
75// == TRAITS == //
76impl<V: fmt::Display, W: Weight> fmt::Display for WeightedItem<V,W>
77{
78    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
79    {
80        write!(f, "{{ {}, {} }}", self.weight, self.value)
81    }
82}
83
84impl<V: Eq, W: Weight + Ord> Ord for WeightedItem<V,W>
85{
86    fn cmp(&self, other: &Self) -> std::cmp::Ordering
87    {
88        self.weight.cmp(&other.weight)
89        // .then(self.value.cmp(&other.value))
90    }
91}
92
93impl<V: Eq, W: Weight> PartialOrd for WeightedItem<V,W>
94{
95    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering>
96    {
97        self.weight.partial_cmp(&other.weight)
98    }
99}