#near #match #values #enough #difference #finding #set

near_enough

Utilities for finding the difference between two values, and for getting the closest match from a set

1 unstable release

0.1.0 Mar 23, 2024

#695 in Algorithms

Download history 133/week @ 2024-03-19 14/week @ 2024-03-26 20/week @ 2024-04-02

167 downloads per month

MIT/Apache

15KB
458 lines

near_enough

Rust

Occasionally, returning a result that is 'near enough' is more useful than returning no result at all. This crate provides utilities for finding the difference between two values, and for getting the closest match from a set.

It is currently very much of a work in progress, and is almost certainly not the most efficient implementation.


lib.rs:

Sometimes, in programming as in life, it's more useful to return the closest match to a given search key than it is to return no result at all. This crate provides a (small) selection of traits and default implementations to facilitate this.

Providing complex diffing algorithms is not a goal of this crate, but simple utilities (for example finding the closest integer in a set of values) are.

Simple example with usize:

use near_enough::Closest;

let values: [usize; 5] = [0, 1, 3, 5, 9];
assert_eq!(values.closest(&2), Some(&1));

More complex example with custom type:

use near_enough::Closest;
use near_enough::Diff;

#[derive(Debug, Eq, PartialEq)]
struct LengthString(String);

impl Diff for LengthString {
    type Output = usize;

    fn diff(&self, other: &Self) -> usize {
        self.0.len().diff(&other.0.len())
    }
}

let values: [LengthString; 3] = [
    LengthString("a".to_string()),
    LengthString("bb".to_string()),
    LengthString("dddd".to_string()),
];
assert_eq!(
    values.closest(&LengthString("ccc".to_string())),
    Some(&LengthString("bb".to_string()))
);

No runtime deps