Skip to main content

lux_lib/lockfile/
opt_state.rs

1use std::fmt::Display;
2
3use serde::{Deserialize, Serialize};
4
5#[derive(Copy, Debug, PartialEq, Eq, Hash, Clone, PartialOrd, Ord, Default)]
6pub enum OptState {
7    /// A required package
8    #[default]
9    Required,
10    /// An optional package
11    Optional,
12}
13
14impl OptState {
15    pub(crate) fn as_bool(&self) -> bool {
16        match self {
17            Self::Required => false,
18            Self::Optional => true,
19        }
20    }
21
22    pub(super) fn is_default(&self) -> bool {
23        &Self::default() == self
24    }
25}
26
27impl From<bool> for OptState {
28    fn from(value: bool) -> Self {
29        if value {
30            Self::Optional
31        } else {
32            Self::Required
33        }
34    }
35}
36
37impl Display for OptState {
38    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39        match &self {
40            OptState::Required => "required".fmt(f),
41            OptState::Optional => "optional".fmt(f),
42        }
43    }
44}
45
46impl Serialize for OptState {
47    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
48    where
49        S: serde::Serializer,
50    {
51        serializer.serialize_bool(self.as_bool())
52    }
53}
54
55impl<'de> Deserialize<'de> for OptState {
56    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
57    where
58        D: serde::Deserializer<'de>,
59    {
60        Ok(match bool::deserialize(deserializer)? {
61            false => Self::Required,
62            true => Self::Optional,
63        })
64    }
65}