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
79
use std::{
convert::TryFrom,
fmt::{Display, Formatter, Result as FmtResult},
};
use serde::{
de::{self, Unexpected},
Deserialize, Deserializer, Serialize, Serializer,
};
use crate::OwnedDeviceId;
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[allow(clippy::exhaustive_enums)]
pub enum DeviceIdOrAllDevices {
DeviceId(OwnedDeviceId),
AllDevices,
}
impl Display for DeviceIdOrAllDevices {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
match self {
DeviceIdOrAllDevices::DeviceId(device_id) => write!(f, "{}", device_id),
DeviceIdOrAllDevices::AllDevices => write!(f, "*"),
}
}
}
impl From<OwnedDeviceId> for DeviceIdOrAllDevices {
fn from(d: OwnedDeviceId) -> Self {
DeviceIdOrAllDevices::DeviceId(d)
}
}
impl TryFrom<&str> for DeviceIdOrAllDevices {
type Error = &'static str;
fn try_from(device_id_or_all_devices: &str) -> Result<Self, Self::Error> {
if device_id_or_all_devices.is_empty() {
Err("Device identifier cannot be empty")
} else if "*" == device_id_or_all_devices {
Ok(DeviceIdOrAllDevices::AllDevices)
} else {
Ok(DeviceIdOrAllDevices::DeviceId(device_id_or_all_devices.into()))
}
}
}
impl Serialize for DeviceIdOrAllDevices {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::DeviceId(device_id) => device_id.serialize(serializer),
Self::AllDevices => serializer.serialize_str("*"),
}
}
}
impl<'de> Deserialize<'de> for DeviceIdOrAllDevices {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = crate::serde::deserialize_cow_str(deserializer)?;
DeviceIdOrAllDevices::try_from(s.as_ref()).map_err(|_| {
de::Error::invalid_value(Unexpected::Str(&s), &"a valid device identifier or '*'")
})
}
}