konst/string/
split_terminator_items.rs

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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
use crate::{
    iter::{IntoIterKind, IsIteratorKind},
    string::{self, str_from, str_up_to},
};

use konst_macro_rules::iterator_shared;

/// Const equivalent of [`str::split_terminator`], which only takes a `&str` delimiter.
///
/// The same as [`split`](crate::string::split),
/// except that, if the string after the last delimiter is empty, it is skipped.
///
/// # Version compatibility
///
/// This requires the `"rust_1_64"` feature.
///
/// # Example
///
/// ```rust
/// use konst::string;
/// use konst::iter::for_each;
///
/// const STRS: &[&str] = &{
///     let mut arr = [""; 3];
///     for_each!{(i, sub) in string::split_terminator("foo,bar,baz,", ","),enumerate() =>
///         arr[i] = sub;
///     }
///     arr
/// };
///
/// assert_eq!(STRS, ["foo", "bar", "baz"]);
/// ```
#[cfg_attr(feature = "docsrs", doc(cfg(feature = "rust_1_64")))]
pub const fn split_terminator<'a, 'b>(this: &'a str, delim: &'b str) -> SplitTerminator<'a, 'b> {
    SplitTerminator {
        this,
        state: if delim.is_empty() {
            State::Empty(EmptyState::Start)
        } else {
            State::Normal { delim }
        },
    }
}

/// Const equivalent of [`str::rsplit_terminator`], which only takes a `&str` delimiter.
///
/// The same as [`rsplit`](crate::string::rsplit),
/// except that, if the string before the first delimiter is empty, it is skipped.
///
/// # Version compatibility
///
/// This requires the `"rust_1_64"` feature.
///
/// # Example
///
/// ```rust
/// use konst::string;
/// use konst::iter::for_each;
///
/// const STRS: &[&str] = &{
///     let mut arr = [""; 3];
///     for_each!{(i, sub) in string::rsplit_terminator(":foo:bar:baz", ":"),enumerate() =>
///         arr[i] = sub;
///     }
///     arr
/// };
///
/// assert_eq!(STRS, ["baz", "bar", "foo"]);
/// ```
#[cfg_attr(feature = "docsrs", doc(cfg(feature = "rust_1_64")))]
pub const fn rsplit_terminator<'a, 'b>(this: &'a str, delim: &'b str) -> RSplitTerminator<'a, 'b> {
    let SplitTerminator { this, state } = split_terminator(this, delim);
    RSplitTerminator { this, state }
}

#[derive(Copy, Clone)]
enum State<'a> {
    Normal { delim: &'a str },
    Empty(EmptyState),
}

#[derive(Copy, Clone)]
enum EmptyState {
    Start,
    Continue,
}

/// Const equivalent of `core::str::SplitTerminator<'a, &'b str>`
///
/// This is constructed with [`split_terminator`] like this:
/// ```rust
/// # let string = "";
/// # let delim = "";
/// # let _: konst::string::SplitTerminator<'_, '_> =
/// konst::string::split_terminator(string, delim)
/// # ;
/// ```
///
/// # Version compatibility
///
/// This requires the `"rust_1_64"` feature.
///
#[cfg_attr(feature = "docsrs", doc(cfg(feature = "rust_1_64")))]
pub struct SplitTerminator<'a, 'b> {
    this: &'a str,
    state: State<'b>,
}
impl IntoIterKind for SplitTerminator<'_, '_> {
    type Kind = IsIteratorKind;
}

impl<'a, 'b> SplitTerminator<'a, 'b> {
    iterator_shared! {
        is_forward = true,
        item = &'a str,
        iter_forward = SplitTerminator<'a, 'b>,
        next(self){
            let Self {
                this,
                state,
            } = self;

            match state {
                State::Empty(EmptyState::Start) => {
                    self.state = State::Empty(EmptyState::Continue);
                    Some(("", self))
                }
                _ if this.is_empty() => {
                    None
                }
                State::Normal{delim} => {
                    let (next, ret) = match string::find(this, delim, 0) {
                        Some(pos) => (pos + delim.len(), pos),
                        None => (this.len(), this.len()),
                    };
                    self.this = str_from(this, next);
                    Some((str_up_to(this, ret), self))
                }
                State::Empty(EmptyState::Continue) => {
                    let next_char = string::find_next_char_boundary(self.this.as_bytes(), 0);
                    let (next_char, rem) = string::split_at(self.this, next_char);
                    self.this = rem;
                    Some((next_char, self))
                }
            }
        },
        fields = {this, state},
    }

    /// Gets the remainder of the string.
    ///
    /// # Example
    ///
    /// ```rust
    /// let iter = konst::string::split_terminator("foo,bar,baz,", ",");
    /// assert_eq!(iter.remainder(), "foo,bar,baz,");
    ///
    /// let (elem, iter) = iter.next().unwrap();
    /// assert_eq!(elem, "foo");
    /// assert_eq!(iter.remainder(), "bar,baz,");
    ///
    /// let (elem, iter) = iter.next().unwrap();
    /// assert_eq!(elem, "bar");
    /// assert_eq!(iter.remainder(), "baz,");
    ///
    /// let (elem, iter) = iter.next().unwrap();
    /// assert_eq!(elem, "baz");
    /// assert_eq!(iter.remainder(), "");
    ///
    /// ```
    pub const fn remainder(&self) -> &'a str {
        self.this
    }
}

/// Const equivalent of `core::str::RSplitTerminator<'a, &'b str>`
///
/// This is constructed with [`rsplit_terminator`] like this:
/// ```rust
/// # let string = "";
/// # let delim = "";
/// # let _: konst::string::RSplitTerminator<'_, '_> =
/// konst::string::rsplit_terminator(string, delim)
/// # ;
/// ```
///
/// # Version compatibility
///
/// This requires the `"rust_1_64"` feature.
///
#[cfg_attr(feature = "docsrs", doc(cfg(feature = "rust_1_64")))]
pub struct RSplitTerminator<'a, 'b> {
    this: &'a str,
    state: State<'b>,
}
impl IntoIterKind for RSplitTerminator<'_, '_> {
    type Kind = IsIteratorKind;
}

impl<'a, 'b> RSplitTerminator<'a, 'b> {
    iterator_shared! {
        is_forward = true,
        item = &'a str,
        iter_forward = RSplitTerminator<'a, 'b>,
        next(self){
            let Self {
                this,
                state,
            } = self;

            match state {
                State::Empty(EmptyState::Start) => {
                    self.state = State::Empty(EmptyState::Continue);
                    Some(("", self))
                }
                _ if this.is_empty() => {
                    None
                }
                State::Normal{delim} => {
                    let (next, ret) = match string::rfind(this, delim, this.len()) {
                        Some(pos) => (pos, pos + delim.len()),
                        None => (0, 0),
                    };
                    self.this = str_up_to(this, next);
                    Some((str_from(this, ret), self))
                }
                State::Empty(EmptyState::Continue) => {
                    let bytes = self.this.as_bytes();
                    let next_char = string::find_prev_char_boundary(bytes, bytes.len());
                    let (rem, next_char) = string::split_at(self.this, next_char);
                    self.this = rem;
                    Some((next_char, self))
                }
            }
        },
        fields = {this, state},
    }

    /// Gets the remainder of the string.
    ///
    /// # Example
    ///
    /// ```rust
    /// let iter = konst::string::rsplit_terminator("=foo=bar=baz", "=");
    /// assert_eq!(iter.remainder(), "=foo=bar=baz");
    ///
    /// let (elem, iter) = iter.next().unwrap();
    /// assert_eq!(elem, "baz");
    /// assert_eq!(iter.remainder(), "=foo=bar");
    ///
    /// let (elem, iter) = iter.next().unwrap();
    /// assert_eq!(elem, "bar");
    /// assert_eq!(iter.remainder(), "=foo");
    ///
    /// let (elem, iter) = iter.next().unwrap();
    /// assert_eq!(elem, "foo");
    /// assert_eq!(iter.remainder(), "");
    ///
    /// ```
    pub const fn remainder(&self) -> &'a str {
        self.this
    }
}