zng_unit/
distance_key.rs
1use crate::{Px, PxPoint};
2
3use serde::{Deserialize, Serialize};
4
5#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, bytemuck::Zeroable, bytemuck::Pod)]
9#[repr(transparent)]
10#[serde(transparent)]
11pub struct DistanceKey(u64);
12impl DistanceKey {
13 pub const NONE_MAX: DistanceKey = DistanceKey(u64::MAX);
15
16 pub const NONE_MIN: DistanceKey = DistanceKey(0);
18
19 pub const MAX: DistanceKey = DistanceKey((Px::MAX.0 as u64).pow(2));
21
22 pub const MIN: DistanceKey = DistanceKey(1);
24
25 pub fn from_points(a: PxPoint, b: PxPoint) -> Self {
27 let pa = ((a.x - b.x).0.unsigned_abs() as u64).pow(2);
28 let pb = ((a.y - b.y).0.unsigned_abs() as u64).pow(2);
29
30 Self((pa + pb) + 1)
31 }
32
33 pub fn from_distance(d: Px) -> Self {
39 let p = (d.0.unsigned_abs() as u64).pow(2);
40 Self(p + 1)
41 }
42
43 pub fn is_none(self) -> bool {
48 self == Self::NONE_MAX || self == Self::NONE_MIN
49 }
50
51 pub fn distance(self) -> Option<Px> {
53 if self.is_none() {
54 None
55 } else {
56 let p = self.0 - 1;
57 let d = (p as f64).sqrt();
58
59 Some(Px(d.round() as i32))
60 }
61 }
62}