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
use std::ops::Range;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Emotes {
pub id: usize,
pub ranges: Vec<Range<u16>>,
}
impl Emotes {
pub fn parse(input: &str) -> impl Iterator<Item = Self> + '_ {
input.split_terminator('/').filter_map(|s| {
get_parts(s, ':').and_then(|(head, tail)| {
let emotes = Self {
id: head.parse().ok()?,
ranges: get_ranges(tail).collect(),
};
emotes.into()
})
})
}
}
#[inline]
fn get_parts(input: &str, sep: char) -> Option<(&str, &str)> {
let mut split = input.split_terminator(sep);
(split.next()?, split.next()?).into()
}
#[inline]
fn get_ranges(tail: &str) -> impl Iterator<Item = Range<u16>> + '_ {
tail.split_terminator(',')
.filter_map(|s| get_parts(s, '-'))
.filter_map(move |(start, end)| {
let (start, end) = (start.parse().ok()?, end.parse().ok()?);
Range { start, end }.into()
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse() {
macro_rules! emote {
($id:expr, $($r:expr),* $(,)?) => {
Emotes {
id: $id,
ranges: vec![$($r),*]
}
};
}
let inputs = &[
(
"25:0-4,6-10,12-16",
vec![emote!(25, (0..4), (6..10), (12..16))],
),
("25:0-4", vec![emote!(25, (0..4))]),
(
"1077966:0-6/25:8-12",
vec![emote!(1_077_966, (0..6)), emote!(25, (8..12))],
),
(
"25:0-4,6-10/33:12-19",
vec![emote!(25, (0..4), (6..10)), emote!(33, (12..19))],
),
(
"25:0-4,15-19/33:6-13",
vec![emote!(25, (0..4), (15..19)), emote!(33, (6..13))],
),
(
"33:0-7/25:9-13,15-19",
vec![emote!(33, (0..7)), emote!(25, (9..13), (15..19))],
),
];
for (input, expect) in inputs {
let emotes = Emotes::parse(&input).collect::<Vec<_>>();
assert_eq!(emotes.len(), expect.len());
assert_eq!(emotes, *expect);
}
}
}