serde_hashkey/float/
mod.rs

1cfg_ordered_float! {
2    pub use self::ordered_float::{to_key_with_ordered_float, OrderedFloat, OrderedFloatPolicy};
3}
4
5use crate::error::Error;
6use serde::de;
7
8mod float_policy;
9mod float_repr;
10
11cfg_ordered_float! {
12    mod ordered_float;
13}
14
15pub use self::float_policy::FloatPolicy;
16pub use self::float_repr::FloatRepr;
17
18/// An uninhabitable type for float policies that cannot produce a value of the
19/// corresponding type. This is used by [RejectFloatPolicy].
20#[derive(Debug, Clone, Copy, Ord, PartialOrd, Eq, PartialEq, Hash)]
21pub enum NeverFloat {}
22
23impl FloatRepr<f32> for NeverFloat {
24    fn serialize(_: f32) -> Result<Self, Error> {
25        Err(Error::UnsupportedType("f32"))
26    }
27
28    fn visit<'de, V>(&self, _: V) -> Result<V::Value, Error>
29    where
30        V: de::Visitor<'de>,
31    {
32        Err(Error::UnsupportedType("f32"))
33    }
34}
35
36impl FloatRepr<f64> for NeverFloat {
37    fn serialize(_: f64) -> Result<Self, Error> {
38        Err(Error::UnsupportedType("f64"))
39    }
40
41    fn visit<'de, V>(&self, _: V) -> Result<V::Value, Error>
42    where
43        V: de::Visitor<'de>,
44    {
45        Err(Error::UnsupportedType("f64"))
46    }
47}
48
49impl serde::Serialize for NeverFloat {
50    fn serialize<S>(&self, _: S) -> Result<S::Ok, S::Error>
51    where
52        S: serde::Serializer,
53    {
54        // Note: type is uninhabitable, so this impl can never be reached.
55        unreachable!()
56    }
57}
58
59/// A float serialization policy which rejects any attempt to serialize a float
60/// with an error. This policy is used by the [to_key] function.
61///
62/// [to_key]: crate::to_key
63///
64/// # Examples
65///
66/// ```
67/// use serde_hashkey::{Key, Float, to_key};
68///
69/// # fn main() -> Result<(), serde_hashkey::Error> {
70/// assert!(to_key(&"John Doe").is_ok());
71/// assert!(to_key(&42.42f32).is_err());
72/// # Ok(()) }
73/// ```
74#[derive(Debug, Clone, Copy, Ord, PartialOrd, Eq, PartialEq, Hash)]
75pub struct RejectFloatPolicy(());
76
77impl FloatPolicy for RejectFloatPolicy {
78    type F32 = NeverFloat;
79    type F64 = NeverFloat;
80}