pub trait Cost:
Copy
+ Ord
+ Add<Output = Self> {
const ZERO: Self;
// Required methods
fn saturating_add(self, other: Self) -> Self;
fn saturating_times(self, factor: u32) -> Self;
}Expand description
A non-negative scalar edge or path cost.
Searches add costs along a path and compare the sums. The default cost type of this
ecosystem is u32.
§Contract
- Non-negative. Every value is
>=Cost::ZERO, so extending a path never makes it cheaper. This is why only unsigned integers implement the trait: a negative edge cost silently voids the optimality of Dijkstra, A* and their relatives. - Total order.
Ordis the cost order; smaller is cheaper. +follows the underlying integer. For the integer types andDecimal, an overflowing+panics in debug builds and wraps in release builds, exactly like the primitive. Pick a type wide enough for the longest path, or useCost::saturating_addwhere a sum only serves as a priority.NonNegF64never overflows; it reaches infinity instead.
Implemented for u8, u16, u32, u64, u128, usize, Decimal, the pair
Lexicographic and (feature float) NonNegF64.
§Examples
A function generic over the cost type:
use search_core::Cost;
fn path_cost<C: Cost>(edges: &[C]) -> C {
edges.iter().fold(C::ZERO, |sum, &edge| sum + edge)
}
assert_eq!(path_cost(&[3_u32, 4, 5]), 12);
assert_eq!(path_cost::<u8>(&[]), 0);Required Associated Constants§
Required Methods§
Sourcefn saturating_add(self, other: Self) -> Self
fn saturating_add(self, other: Self) -> Self
Adds two costs, saturating at the largest value instead of overflowing.
Used where a sum only serves as a priority, such as a weighted A* key.
Sourcefn saturating_times(self, factor: u32) -> Self
fn saturating_times(self, factor: u32) -> Self
Multiplies the cost by a small integer factor, saturating at the largest value.
Used to compare weighted sums such as den * g + num * h without division. A factor
of 0 always yields Cost::ZERO.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".