Skip to main content

iota_config/
setting.rs

1// Copyright (c) 2026 IOTA Stiftung
2// SPDX-License-Identifier: Apache-2.0
3
4use serde::{Deserialize, Deserializer, Serialize, Serializer, ser::Error as _};
5
6/// A config field that is either set to a value, absent, or explicitly `null`.
7///
8/// `None` value of a config field of type `Option<T>` is ambiguous, it can mean
9/// either "setting is disabled" or "setting is unset, use default". `Setting<T>`
10/// type solves this problem: disabled config values (encoded in YAML as `null`)
11/// deserialize to `Setting::Disabled` and correspond to `Option::None`, while
12/// absent values deserialize to `Setting::Unset` and correspond to a default
13/// setting value that is resolved to `default` argument of [`Setting::resolve`].
14///
15/// Declare a field of this type as:
16///
17/// ```ignore
18/// #[serde(default, skip_serializing_if = "Setting::is_unset")]
19/// pub value: Setting<usize>,
20/// ```
21///
22/// Both attributes are required. `default` is the only way serde reports an
23/// absent field, and it yields [`Setting::Unset`]. `skip_serializing_if`
24/// prevents serialising `Unset`, which is an error: it would have to be written
25/// as nothing, which serde serializer does not implement.
26///
27/// A field written with an empty value — `max-connections:` — is YAML `null`,
28/// so it turns the setting off rather than leaving the default.
29#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
30pub enum Setting<T> {
31    /// The field was set to this value.
32    Value(T),
33    /// The field was absent, so the default applies.
34    #[default]
35    Unset,
36    /// The field was `null`, so whatever it configures is off.
37    Disabled,
38}
39
40impl<T> Setting<T> {
41    /// The configured value, falling back to `default` where the field was
42    /// absent. `None` means off.
43    pub fn resolve(self, default: impl Into<Option<T>>) -> Option<T> {
44        match self {
45            Self::Value(value) => Some(value),
46            Self::Unset => default.into(),
47            Self::Disabled => None,
48        }
49    }
50
51    /// Whether the field was absent. Meant for `skip_serializing_if`.
52    pub fn is_unset(&self) -> bool {
53        matches!(self, Self::Unset)
54    }
55}
56
57impl<T: Serialize> Serialize for Setting<T> {
58    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
59        match self {
60            Self::Value(value) => serializer.serialize_some(value),
61            Self::Disabled => serializer.serialize_none(),
62            // Unreachable through a field that carries
63            // `skip_serializing_if = "Setting::is_unset"`, and an error rather
64            // than a guess because `null` is how "off" is spelled: writing one
65            // for the other would change what the file means.
66            Self::Unset => Err(S::Error::custom(
67                "an unset field must carry `skip_serializing_if = \"Setting::is_unset\"`",
68            )),
69        }
70    }
71}
72
73impl<'de, T: Deserialize<'de>> Deserialize<'de> for Setting<T> {
74    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
75        // An absent field never reaches here: `#[serde(default)]` answers that
76        // case with `Unset`. What arrives is either a value or `null`.
77        match Option::<T>::deserialize(deserializer) {
78            Ok(Some(value)) => Ok(Self::Value(value)),
79            Ok(None) => Ok(Self::Disabled),
80            Err(err) => Err(err),
81        }
82    }
83}
84
85#[cfg(test)]
86mod tests {
87    use std::{num::NonZeroUsize, time::Duration};
88
89    use super::*;
90
91    #[derive(Debug, PartialEq, Deserialize, Serialize)]
92    #[serde(rename_all = "kebab-case")]
93    struct Config {
94        #[serde(default, skip_serializing_if = "Setting::is_unset")]
95        non_zero: Setting<NonZeroUsize>,
96        #[serde(default, skip_serializing_if = "Setting::is_unset")]
97        duration: Setting<Duration>,
98    }
99
100    fn parse(yaml: &str) -> Result<Config, serde_yaml::Error> {
101        serde_yaml::from_str(yaml)
102    }
103
104    #[test]
105    fn an_absent_field_is_unset() {
106        let limits = parse("{}").unwrap();
107        assert_eq!(limits.non_zero, Setting::Unset);
108        assert_eq!(limits.duration, Setting::Unset);
109    }
110
111    #[test]
112    fn a_value_is_the_value() {
113        let limits = parse("non-zero: 8192").unwrap();
114        assert_eq!(
115            limits.non_zero,
116            Setting::Value(NonZeroUsize::new(8192).unwrap())
117        );
118    }
119
120    #[test]
121    fn an_explicit_null_is_disabled() {
122        let limits = parse("non-zero: null").unwrap();
123        assert_eq!(limits.non_zero, Setting::Disabled);
124    }
125
126    /// A field written with no value is YAML `null`, so it reads as off rather
127    /// than as the default. Pinned because it is the one state an operator may
128    /// not expect.
129    #[test]
130    fn a_field_with_no_value_is_disabled() {
131        let limits = parse("non-zero:").unwrap();
132        assert_eq!(limits.non_zero, Setting::Disabled);
133    }
134
135    /// Zero is not a way to turn a count off; `null` is. `NonZeroUsize` is what
136    /// rejects it, and it is rejected where it is written rather than later.
137    #[test]
138    fn a_zero_count_is_refused() {
139        let error = parse("non-zero: 0").unwrap_err().to_string();
140        assert!(
141            error.contains("non-zero"),
142            "the error should name the field, got: {error}"
143        );
144    }
145
146    #[test]
147    fn resolve_applies_the_default_only_when_unset() {
148        let default = NonZeroUsize::new(64);
149        assert_eq!(
150            Setting::Value(NonZeroUsize::new(8).unwrap()).resolve(default),
151            NonZeroUsize::new(8)
152        );
153        assert_eq!(Setting::Unset.resolve(default), default);
154        assert_eq!(Setting::<NonZeroUsize>::Disabled.resolve(default), None);
155    }
156
157    #[test]
158    fn every_state_survives_a_round_trip() {
159        for limits in [
160            Config {
161                non_zero: Setting::Unset,
162                duration: Setting::Unset,
163            },
164            Config {
165                non_zero: Setting::Value(NonZeroUsize::new(8192).unwrap()),
166                duration: Setting::Value(Duration::from_secs(300)),
167            },
168            Config {
169                non_zero: Setting::Disabled,
170                duration: Setting::Disabled,
171            },
172            Config {
173                non_zero: Setting::Value(NonZeroUsize::new(1).unwrap()),
174                duration: Setting::Disabled,
175            },
176        ] {
177            let yaml = serde_yaml::to_string(&limits).unwrap();
178            assert_eq!(parse(&yaml).unwrap(), limits, "round trip of {yaml}");
179        }
180    }
181
182    /// A fully defaulted struct writes nothing, which is what keeps a config
183    /// file free of settings nobody chose.
184    #[test]
185    fn an_unset_field_is_not_written() {
186        let yaml = serde_yaml::to_string(&Config {
187            non_zero: Setting::Unset,
188            duration: Setting::Value(Duration::from_secs(1)),
189        })
190        .unwrap();
191        assert!(
192            !yaml.contains("non-zero"),
193            "an unset field should be skipped, got: {yaml}"
194        );
195    }
196
197    /// The guard above is a real requirement, not a style note.
198    #[test]
199    fn serialising_an_unset_field_without_the_guard_is_an_error() {
200        #[derive(Serialize)]
201        struct Unguarded {
202            non_zero: Setting<NonZeroUsize>,
203        }
204
205        let error = serde_yaml::to_string(&Unguarded {
206            non_zero: Setting::Unset,
207        })
208        .unwrap_err()
209        .to_string();
210        assert!(
211            error.contains("skip_serializing_if"),
212            "the error should say what is missing, got: {error}"
213        );
214    }
215}