Skip to content

Instantly share code, notes, and snippets.

@mickvangelderen
Last active December 6, 2017 11:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mickvangelderen/551bf3c0a6da767447759eaabc9fc19e to your computer and use it in GitHub Desktop.
Save mickvangelderen/551bf3c0a6da767447759eaabc9fc19e to your computer and use it in GitHub Desktop.
Super convoluted linear map/interpolate implementation
#![feature(fn_must_use)]
#[cfg(test)]
mod tests {
use std::ops::{Sub, Add, Mul, Div};
trait Unit {
type Value;
fn value(&self) -> Self::Value;
fn from(value: Self::Value) -> Self;
}
#[must_use]
fn linear_map<X, Y, V>(x0: X, x1: X, y0: Y, y1: Y, x: X) -> Y
where
X: Unit<Value = V>,
Y: Unit<Value = V>,
V: Sub<Output = V> + Add<Output = V> + Mul<Output = V> + Div<Output = V>,
{
// y0 + (x - x0)/(x1 - x0) * (y1 - y0);
// y0 + (x - x0)*(y1 - y0)/(x1 - x0);
// (y0(x1 - x0) + (x - x0)*(y1 - y0))/(x1 - x0);
// (x1*y0 - x0*y0 + x*y1 - x*y0 - x0*y1 + x0*y0)/(x1 - x0);
// (x1*y0 + x*y1 - x*y0 - x0*y1)/(x1 - x0);
Y::from(
((x1.value() - x.value()) * y0.value() + (x.value() - x0.value()) * y1.value()) /
(x1.value() - x0.value()),
)
}
#[derive(Clone, Copy, PartialEq, Debug)]
struct Trees(f32);
impl Unit for Trees {
type Value = f32;
fn value(&self) -> Self::Value {
self.0
}
fn from(value: Self::Value) -> Self {
Trees(value)
}
}
#[derive(Clone, Copy, PartialEq, Debug)]
struct Apples(f32);
impl Unit for Apples {
type Value = f32;
fn value(&self) -> Self::Value {
self.0
}
fn from(value: Self::Value) -> Self {
Apples(value)
}
}
#[test]
fn trees_to_apples() {
assert_eq!(
Apples(5.0),
linear_map(Trees(0.0), Trees(10.0), Apples(-5.0), Apples(95.0), Trees(1.0)),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment