milli_core/facet/
facet_value.rs

1use ordered_float::OrderedFloat;
2use serde::{Serialize, Serializer};
3
4#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
5pub enum FacetValue {
6    String(String),
7    Number(OrderedFloat<f64>),
8}
9
10impl From<String> for FacetValue {
11    fn from(string: String) -> FacetValue {
12        FacetValue::String(string)
13    }
14}
15
16impl From<&str> for FacetValue {
17    fn from(string: &str) -> FacetValue {
18        FacetValue::String(string.to_owned())
19    }
20}
21
22impl From<f64> for FacetValue {
23    fn from(float: f64) -> FacetValue {
24        FacetValue::Number(OrderedFloat(float))
25    }
26}
27
28impl From<OrderedFloat<f64>> for FacetValue {
29    fn from(float: OrderedFloat<f64>) -> FacetValue {
30        FacetValue::Number(float)
31    }
32}
33
34impl From<i64> for FacetValue {
35    fn from(integer: i64) -> FacetValue {
36        FacetValue::Number(OrderedFloat(integer as f64))
37    }
38}
39
40/// We implement Serialize ourselves because we need to always serialize it as a string,
41/// JSON object keys must be strings not numbers.
42// TODO remove this impl and convert them into string, by hand, when required.
43impl Serialize for FacetValue {
44    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
45    where
46        S: Serializer,
47    {
48        match self {
49            FacetValue::String(string) => serializer.serialize_str(string),
50            FacetValue::Number(number) => {
51                let string = number.to_string();
52                serializer.serialize_str(&string)
53            }
54        }
55    }
56}