1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
use serde::{ser::Error, Deserialize, Deserializer, Serialize, Serializer};

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum OptionSerializer<T> {
    Some(T),
    None,
    Skip,
}

impl<T> OptionSerializer<T> {
    pub fn none() -> Self {
        Self::None
    }

    pub fn skip() -> Self {
        Self::Skip
    }

    pub fn should_skip(&self) -> bool {
        matches!(self, Self::Skip)
    }

    pub fn or_skip(option: Option<T>) -> Self {
        match option {
            Option::Some(item) => Self::Some(item),
            Option::None => Self::Skip,
        }
    }

    pub fn as_ref(&self) -> OptionSerializer<&T> {
        #[allow(clippy::needless_match)] // The nightly clippy used by CI is incorrect here
        match self {
            OptionSerializer::Some(item) => OptionSerializer::Some(item),
            OptionSerializer::None => OptionSerializer::None,
            OptionSerializer::Skip => OptionSerializer::Skip,
        }
    }
}

impl<T> From<Option<T>> for OptionSerializer<T> {
    fn from(option: Option<T>) -> Self {
        match option {
            Option::Some(item) => Self::Some(item),
            Option::None => Self::None,
        }
    }
}

impl<T> From<OptionSerializer<T>> for Option<T> {
    fn from(option: OptionSerializer<T>) -> Self {
        match option {
            OptionSerializer::Some(item) => Self::Some(item),
            _ => Self::None,
        }
    }
}

impl<T: Serialize> Serialize for OptionSerializer<T> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::Some(item) => item.serialize(serializer),
            Self::None => serializer.serialize_none(),
            Self::Skip => Err(Error::custom("Skip variants should not be serialized")),
        }
    }
}

impl<'de, T: Deserialize<'de>> Deserialize<'de> for OptionSerializer<T> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Option::deserialize(deserializer).map(Into::into)
    }
}