Skip to main content

token_value_map/
position.rs

1/// Normalized position in [0, 1] for curve domains.
2///
3/// Used as the key type for curve data maps (e.g., `KeyDataMap<Position, Real>`
4/// for real-valued curves).
5
6#[cfg(feature = "rkyv")]
7use rkyv::{Archive, Deserialize as RkyvDeserialize, Serialize as RkyvSerialize};
8#[cfg(feature = "serde")]
9use serde::{Deserialize, Serialize};
10use std::cmp::Ordering;
11use std::hash::{Hash, Hasher};
12
13/// A normalized position in [0, 1] for curve stop domains.
14#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
15#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
16#[cfg_attr(feature = "rkyv", derive(Archive, RkyvSerialize, RkyvDeserialize))]
17#[cfg_attr(
18    feature = "rkyv",
19    rkyv(attr(derive(Debug, Clone, Copy, PartialEq, PartialOrd)))
20)]
21pub struct Position(pub f32);
22
23impl Eq for Position {}
24
25impl Ord for Position {
26    fn cmp(&self, other: &Self) -> Ordering {
27        self.0.total_cmp(&other.0)
28    }
29}
30
31impl Hash for Position {
32    fn hash<H: Hasher>(&self, state: &mut H) {
33        self.0.to_bits().hash(state);
34    }
35}
36
37impl From<Position> for f32 {
38    fn from(p: Position) -> f32 {
39        p.0
40    }
41}
42
43impl From<f32> for Position {
44    fn from(v: f32) -> Position {
45        Position(v)
46    }
47}
48
49// Manual trait impls for ArchivedPosition (f32 doesn't impl Ord/Eq/Hash).
50#[cfg(feature = "rkyv")]
51impl Eq for ArchivedPosition {}
52
53#[cfg(feature = "rkyv")]
54impl Ord for ArchivedPosition {
55    fn cmp(&self, other: &Self) -> Ordering {
56        let a = f32::from(self.0);
57        let b = f32::from(other.0);
58        a.total_cmp(&b)
59    }
60}
61
62#[cfg(feature = "rkyv")]
63impl Hash for ArchivedPosition {
64    fn hash<H: Hasher>(&self, state: &mut H) {
65        f32::from(self.0).to_bits().hash(state);
66    }
67}
68
69impl std::fmt::Display for Position {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        write!(f, "{}", self.0)
72    }
73}