Skip to main content

finlight/
field.rs

1use serde::{Deserialize, Deserializer, Serialize, Serializer};
2
3/// A key with three states: absent, `null` or a value.
4///
5/// Used for `content` and `sentiment`, whose presence depends on your plan and on `include`:
6///
7/// - [`Field::Absent`]: the key was not in the JSON (not entitled, not requested, or raw).
8/// - [`Field::Null`]: the key was there with `null` (entitled and requested, but no value).
9/// - [`Field::Value`]: the key carried a value.
10///
11/// When written back with serde, an absent field stays absent and `null` stays `null`.
12#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
13pub enum Field<T> {
14    /// The key was not in the JSON.
15    #[default]
16    Absent,
17    /// The key was in the JSON with `null`.
18    Null,
19    /// The key carried a value.
20    Value(T),
21}
22
23impl<T> Field<T> {
24    /// `true` when the key was in the JSON, `null` included.
25    pub fn is_present(&self) -> bool {
26        !matches!(self, Field::Absent)
27    }
28
29    /// `true` when the key was not in the JSON.
30    pub fn is_absent(&self) -> bool {
31        matches!(self, Field::Absent)
32    }
33
34    /// `true` when the key was in the JSON with `null`.
35    pub fn is_null(&self) -> bool {
36        matches!(self, Field::Null)
37    }
38
39    /// The value, or `None` when absent or `null`.
40    pub fn value(&self) -> Option<&T> {
41        match self {
42            Field::Value(v) => Some(v),
43            _ => None,
44        }
45    }
46
47    /// Converts into the value, or `None` when absent or `null`.
48    pub fn into_value(self) -> Option<T> {
49        match self {
50            Field::Value(v) => Some(v),
51            _ => None,
52        }
53    }
54
55    /// Borrows the content.
56    pub fn as_ref(&self) -> Field<&T> {
57        match self {
58            Field::Absent => Field::Absent,
59            Field::Null => Field::Null,
60            Field::Value(v) => Field::Value(v),
61        }
62    }
63}
64
65impl<'de, T: Deserialize<'de>> Deserialize<'de> for Field<T> {
66    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
67        // Only called when the key is present; a missing key uses `Default` (Absent).
68        Ok(match Option::<T>::deserialize(deserializer)? {
69            Some(v) => Field::Value(v),
70            None => Field::Null,
71        })
72    }
73}
74
75impl<T: Serialize> Serialize for Field<T> {
76    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
77        match self {
78            // Fields that use Field skip serializing when absent; this arm is a fallback.
79            Field::Absent | Field::Null => serializer.serialize_none(),
80            Field::Value(v) => v.serialize(serializer),
81        }
82    }
83}