konst/string/split_once.rs
1use crate::string::{self, str_from, str_up_to, Pattern, PatternNorm};
2
3/// A const-equivalent of the [`str::split_once`] method.
4///
5/// This takes [`Pattern`] implementors as the delimiter.
6///
7/// # Example
8///
9/// ```rust
10/// use konst::string;
11///
12/// assert_eq!(string::split_once("", "-"), None);
13/// assert_eq!(string::split_once("foo", "-"), None);
14/// assert_eq!(string::split_once("foo-", "-"), Some(("foo", "")));
15/// assert_eq!(string::split_once("foo-bar", "-"), Some(("foo", "bar")));
16/// assert_eq!(string::split_once("foo-bar-baz", "-"), Some(("foo", "bar-baz")));
17///
18/// assert_eq!(string::split_once("foo,bar", ","), Some(("foo", "bar")));
19/// assert_eq!(string::split_once("foo,bar,baz", ","), Some(("foo", "bar,baz")));
20///
21/// ```
22#[cfg_attr(feature = "docsrs", doc(cfg(feature = "iter")))]
23pub const fn split_once<'a, 'p, P>(this: &'a str, delim: P) -> Option<(&'a str, &'a str)>
24where
25 P: Pattern<'p>,
26{
27 let delim = PatternNorm::new(delim);
28 let delim = delim.as_str();
29
30 if delim.is_empty() {
31 // using split_at so that the pointer points within the string
32 Some(string::split_at(this, 0))
33 } else {
34 crate::option::map! {
35 string::find(this, delim),
36 |pos| (str_up_to(this, pos), str_from(this, pos + delim.len()))
37 }
38 }
39}
40
41/// A const-equivalent of the [`str::rsplit_once`] method.
42///
43/// This takes [`Pattern`] implementors as the delimiter.
44///
45/// # Example
46///
47/// ```rust
48/// use konst::string;
49///
50/// assert_eq!(string::rsplit_once("", "-"), None);
51/// assert_eq!(string::rsplit_once("foo", "-"), None);
52/// assert_eq!(string::rsplit_once("foo-", "-"), Some(("foo", "")));
53/// assert_eq!(string::rsplit_once("-foo", "-"), Some(("","foo")));
54/// assert_eq!(string::rsplit_once("foo-bar", "-"), Some(("foo", "bar")));
55/// assert_eq!(string::rsplit_once("foo-bar-baz", "-"), Some(("foo-bar", "baz")));
56///
57/// assert_eq!(string::rsplit_once("foo,bar", ','), Some(("foo", "bar")));
58/// assert_eq!(string::rsplit_once("foo,bar,baz", ','), Some(("foo,bar", "baz")));
59///
60/// ```
61#[cfg_attr(feature = "docsrs", doc(cfg(feature = "iter")))]
62pub const fn rsplit_once<'a, 'p, P>(this: &'a str, delim: P) -> Option<(&'a str, &'a str)>
63where
64 P: Pattern<'p>,
65{
66 let delim = PatternNorm::new(delim);
67 let delim = delim.as_str();
68
69 if delim.is_empty() {
70 // using split_at so that the pointer points within the string
71 Some(string::split_at(this, this.len()))
72 } else {
73 crate::option::map! {
74 string::rfind(this, delim),
75 |pos| (str_up_to(this, pos), str_from(this, pos + delim.len()))
76 }
77 }
78}