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 crate::prelude::*;

/// Isomorphic to [DeviceName].
/// [Deserialize]s and [Serialize]s from a [String] representation.
#[derive(
	Debug, Clone, PartialEq, derive_more::Display, derive_more::From, Serialize, Deserialize,
)]
#[serde(try_from = "&str")]
#[serde(into = "String")]
pub enum ModelName {
	IPhone(IPhoneVariant),

	IPad(IPadVariant),

	#[from(ignore)]
	#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/docs/inline/TODO.md"))]
	UnImplemented(String),
}

impl From<ModelName> for String {
	#[tracing::instrument(level = "trace", skip(variant))]
	fn from(variant: ModelName) -> Self {
		variant.to_string()
	}
}

impl TryFrom<&str> for ModelName {
	type Error = <Self as FromStr>::Err;

	fn try_from(value: &str) -> std::prelude::v1::Result<Self, Self::Error> {
		value.parse()
	}
}

impl_from_str_nom!(ModelName);

impl ModelName {
	pub fn is_iphone(&self) -> bool {
		matches!(self, ModelName::IPhone(_))
	}
	pub fn is_ipad(&self) -> bool {
		matches!(self, ModelName::IPad(_))
	}

	pub fn parsed_successfully(&self) -> bool {
		!matches!(self, ModelName::UnImplemented(_))
	}
}

impl NomFromStr for ModelName {
	fn nom_from_str(input: &str) -> IResult<&str, Self> {
		alt((
			map(IPadVariant::nom_from_str, ModelName::from),
			map(IPhoneVariant::nom_from_str, ModelName::from),
			map(rest, |s: &str| ModelName::UnImplemented(s.to_owned())),
		))(input)
	}
}

#[cfg(test)]
mod tests {
	use crate::shared::assert_nom_parses;

	use super::ModelName;

	#[test]
	fn model_names_parse() {
		let examples = include!(concat!(
			env!("CARGO_MANIFEST_DIR"),
			"/tests/model-names.json"
		));
		assert_nom_parses::<ModelName>(examples, |input| input.parsed_successfully());
	}
}