Skip to main content

tuwunel_core/utils/string/
between.rs

1type Delim<'a> = (&'a str, &'a str);
2
3/// Slice a string between a pair of delimiters.
4pub trait Between<'a> {
5	/// Extract a string between the delimiters. If the delimiters were not
6	/// found None is returned, otherwise the first extraction is returned.
7	fn between(&self, delim: Delim<'_>) -> Option<&'a str>;
8
9	/// Extract a string between the delimiters. If the delimiters were not
10	/// found the original string is returned; take note of this behavior,
11	/// if an empty slice is desired for this case use the fallible version and
12	/// unwrap to EMPTY.
13	fn between_infallible(&self, delim: Delim<'_>) -> &'a str;
14}
15
16impl<'a> Between<'a> for &'a str {
17	#[inline]
18	fn between_infallible(&self, delim: Delim<'_>) -> &'a str {
19		self.between(delim).unwrap_or(self)
20	}
21
22	#[inline]
23	fn between(&self, delim: Delim<'_>) -> Option<&'a str> {
24		self.split_once(delim.0)
25			.and_then(|(_, b)| b.rsplit_once(delim.1))
26			.map(|(a, _)| a)
27	}
28}