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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
use std::hash::Hash;

use crate::prelude::*;

/// Only considers the generation number for [Hash] and [PartialEq].
#[derive(Debug, Clone, Copy, Eq, PartialOrd, Ord)]
pub struct NumGeneration {
	num: NonZeroU8,
	short: bool,
}

impl PartialEq for NumGeneration {
	fn eq(&self, other: &Self) -> bool {
		self.num == other.num
	}
}

impl Hash for NumGeneration {
	fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
		self.num.hash(state);
	}
}

impl NumGeneration {
	const fn ordinal(&self) -> &str {
		match self.num.get() {
			1 => "st",
			2 => "nd",
			3 => "rd",
			_ => "th",
		}
	}

	#[cfg_attr(not(test), allow(dead_code))]
	pub(super) fn testing_new(num: NonZeroU8) -> Self {
		Self {
			num,
			short: false,
		}
	}

	fn long(num: NonZeroU8) -> Self {
		Self {
			num,
			short: false,
		}
	}

	fn short(num: NonZeroU8) -> Self {
		Self {
			num,
			short: true,
		}
	}

	pub fn get(&self) -> u8 {
		self.num.get()
	}
}

#[tracing::instrument(level = "trace", skip(input))]
fn ordinal(input: &str) -> IResult<&str, &str> {
	alt((tag("st"), tag("nd"), tag("rd"), tag("th")))(input)
}

fn generation_brackets(input: &str) -> IResult<&str, NumGeneration> {
	delimited(
		ws(tag("(")),
		map(NonZeroU8::nom_from_str, NumGeneration::long),
		preceded(ws(ordinal), tag("generation)")),
	)(input)
}

fn generation_model(input: &str) -> IResult<&str, NumGeneration> {
	terminated(
		map(NonZeroU8::nom_from_str, NumGeneration::short),
		tag("G"),
	)(input)
}

impl NomFromStr for NumGeneration {
	#[tracing::instrument(level = "trace", skip(input))]
	fn nom_from_str(input: &str) -> IResult<&str, Self> {
		alt((generation_brackets, generation_model))(input)
	}
}

impl Display for NumGeneration {
	#[tracing::instrument(level = "trace", skip(self, f))]
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		match self.short {
			false => write!(f, "({}{} generation)", self.get(), self.ordinal()),
			true => write!(f, "{}G", self.get()),
		}
	}
}

#[cfg(test)]
mod tests {
	use tracing::debug;

	use super::*;

	#[test]
	fn generation_ordering() {
		let old = NumGeneration::long(NonZeroU8::new(1).unwrap());
		let newer = NumGeneration::short(NonZeroU8::new(2).unwrap());
		assert!(newer > old);

		let old = NumGeneration::short(NonZeroU8::new(1).unwrap());
		let newer = NumGeneration::long(NonZeroU8::new(2).unwrap());
		assert!(newer > old);
	}

	#[test]
	fn test_parse_ordinal() {
		let examples = ["st", "nd", "th"];
		for example in examples.iter() {
			let output = ordinal(example);
			match output {
				Ok((remaining, _)) => {
					debug!("Parsed ordinal from {}: {:?}", example, remaining)
				}
				Err(e) => panic!("Failed to parse {:?}: {}", example, e),
			}
		}
	}

	#[test]
	fn hardcoded_num_generation() {
		let examples = [
			"(1st generation)",
			"(2nd generation)",
			"(3rd generation)",
			"(4th generation)",
			"3G",
			"69G",
		];
		for example in examples.iter() {
			let output = NumGeneration::nom_from_str(example);
			match output {
				Ok((remaining, generation)) => {
					debug!(
						"Parsed generation: {:?} from {} [remaining: {}]",
						generation, example, remaining
					);
					assert!(
						remaining.is_empty(),
						"Remaining was not empty: {}",
						remaining
					);
					assert_eq!(&format!("{}", generation), example);
				}
				Err(e) => panic!("Failed to parse {:?}: {}", example, e),
			}
		}
	}
}