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
use serde::Deserialize;
#[derive(Debug, PartialEq, Deserialize)]
pub struct UpdatePackage {
#[serde(rename = "product")]
pub product_uid: String,
pub version: String,
#[serde(default, rename = "supported-hardware")]
pub supported_hardware: SupportedHardware,
pub objects: (Vec<crate::Object>, Vec<crate::Object>),
}
#[derive(Debug, PartialEq, Deserialize)]
#[serde(untagged)]
pub enum SupportedHardware {
#[serde(deserialize_with = "any")]
Any,
HardwareList(Vec<String>),
}
impl Default for SupportedHardware {
fn default() -> Self {
SupportedHardware::Any
}
}
fn any<'de, D: serde::de::Deserializer<'de>>(deserializer: D) -> Result<(), D::Error> {
if String::deserialize(deserializer)? == "any" {
Ok(())
} else {
Err(serde::de::Error::custom("expected \"any\""))
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn no_hardware() {
assert!(serde_json::from_str::<SupportedHardware>("").is_err());
}
#[test]
fn any_hardware() {
assert_eq!(
SupportedHardware::Any,
serde_json::from_str::<SupportedHardware>(&json!("any").to_string()).unwrap()
);
}
#[test]
fn one_hardware() {
assert_eq!(
SupportedHardware::HardwareList(vec!["hw".to_string()]),
serde_json::from_str::<SupportedHardware>(&json!(["hw"]).to_string()).unwrap()
);
}
#[test]
fn many_hardware() {
assert_eq!(
SupportedHardware::HardwareList(vec!["hw-1".into(), "hw-2".into()]),
serde_json::from_str::<SupportedHardware>(&json!(["hw-1", "hw-2"]).to_string())
.unwrap()
);
}
}