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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
#![feature(pattern)]
#![no_std]

//! Little crate implementing some split-like methods on mutable string slices,concretely
//! [`slice::split_mut`] and [`slice::splitn_mut`].
//! 
//! [`slice::split_mut`]: https://doc.rust-lang.org/std/primitive.slice.html#method.split_mut
//! [`slice::splitn_mut`]: https://doc.rust-lang.org/std/primitive.slice.html#method.splitn_mut


extern crate alloc;

use alloc::string::String;

use core::str::pattern::{Pattern, Searcher, ReverseSearcher};
use core::mem;
use core::str::from_utf8_unchecked_mut;
use core::iter::FusedIterator;
use core::ptr;

/// Trait implementing [`slice::split_mut`] and [`slice::splitn_mut`] on [`str`].
/// 
/// [`slice::split_mut`]: https://doc.rust-lang.org/std/primitive.slice.html#method.split_mut
/// [`slice::splitn_mut`]: https://doc.rust-lang.org/std/primitive.slice.html#method.splitn_mut
pub trait SplitMutStr<'a, T: Pattern<'a>> {
    /// Returns an iterator that yields mutable string slices of `self` separated by `pattern`.  
    fn split_mut(&'a mut self, pattern: T) -> SplitMut<'a, T>;

    /// Returns an iterator that yields mutable string slices of `self` separated by `pattern` at
    /// most `n` times.  
    fn splitn_mut(&'a mut self, n: usize, pattern: T) -> SplitNMut<'a, T>;
}

impl<'a, T: Pattern<'a>> SplitMutStr<'a, T> for str {
    fn split_mut(&'a mut self, pattern: T) -> SplitMut<'a, T> {
        SplitMut { v: self, pattern, finished: false }
    }

    fn splitn_mut(&'a mut self, n: usize, pattern: T) -> SplitNMut<'a, T> {
        SplitNMut { v: self, pattern, count: n }
    }
}

impl<'a, T: Pattern<'a>> SplitMutStr<'a, T> for String {
    fn split_mut(&'a mut self, pattern: T) -> SplitMut<'a, T> {
        SplitMutStr::split_mut(&mut **self, pattern)
    }

    fn splitn_mut(&'a mut self, n: usize, pattern: T) -> SplitNMut<'a, T> {
        SplitMutStr::splitn_mut(&mut **self, n, pattern)
    }
}

/// Struct created with the [`SplitMutStr::split_mut`] method.
pub struct SplitMut<'a, T: Pattern<'a>> {
    v: &'a mut str,
    pattern: T,
    finished: bool
}

impl<'a, T: Pattern<'a>> SplitMut<'a, T> {
    fn v(&mut self) -> &'a mut str {
        mem::replace(&mut self.v, unsafe { from_utf8_unchecked_mut(&mut [][..]) })
    }

    /// Returns `true` if the iterator can't return more substrings.
    #[inline]
    pub fn finished(&self) -> bool {
        self.finished
    }
}

impl<'a, T: Pattern<'a>> AsRef<str> for SplitMut<'a, T> {
    /// Returns a shared reference to the rest of the string.
    fn as_ref(&self) -> &str {
        &*self.v
    }
}

impl<'a, T: Pattern<'a>> AsMut<str> for SplitMut<'a, T> {
    /// Returns a mutable reference to the rest of the string.
    fn as_mut(&mut self) -> &mut str {
        // SAFETY: as they have the same inferred lifetime,this reference must dead to use the one
        // in `self` so the copy it's safe.
        unsafe { ptr::read(&self.v) }
    }
}

impl<'a, T: Pattern<'a>> Iterator for SplitMut<'a, T> {
    type Item = &'a mut str;

    #[inline]
    fn next(&mut self) -> Option<&'a mut str> {
        if self.finished {
            return None;
        }

        let tmp1 = self.v();

        // SAFETY: after tmp1 it's used as inmmutable in `into_searcher` and the searcher it's dropped
        // the reference must count as "dead" and then available to use it again as mutable but instead
        // fails to compile and forces me to reborrow it
        let tmp = unsafe { &*(tmp1 as *mut str) };

        // SAFETY: all elements that implement Pattern are Copy except for `FnMut` this type
        // contains mutable references but as we're copying and rapidly discarding the result this
        // is safe.
        match unsafe { ptr::read(&self.pattern) }.into_searcher(tmp).next_match() {
            None => {
               self.finished = true;
               Some(tmp1) 
            },
            Some((idx1, idx2)) => {
                let len = idx2 - idx1;
                let (head, tail) = tmp1.split_at_mut(idx1);
                self.v = &mut tail[len..];
                Some(head)  
            }
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        if self.finished {
            (0, Some(0))
        } else {
            (1, Some(self.v.len() + 1))
        }
    }
}

impl<'a, U: ReverseSearcher<'a>, T: Pattern<'a, Searcher = U>> DoubleEndedIterator for SplitMut<'a, T>
{
    #[inline]
    fn next_back(&mut self) -> Option<&'a mut str> {
        if self.finished {
            return None;
        }

        let tmp1 = self.v();

        let tmp = unsafe { &*(tmp1 as *mut str) };

        match unsafe { ptr::read(&self.pattern) }.into_searcher(tmp).next_match_back() {
            None => {
               self.finished = true;
               Some(tmp1) 
            },
            Some((idx1, idx2)) => {
                let len = idx2 - idx1;
                let (head, tail) = tmp1.split_at_mut(idx1);
                self.v = head;
                Some(&mut tail[len..])
            }
        }
    }
}

impl<'a, T: Pattern<'a> + Copy> FusedIterator for SplitMut<'a, T> {}

/// Struct created with the [`SplitMutStr::splitn_mut`] method.
pub struct SplitNMut<'a, T: Pattern<'a>> {
    v: &'a mut str,
    pattern: T,
    count: usize
}

impl<'a, T: Pattern<'a>> AsRef<str> for SplitNMut<'a, T> {
    /// Returns a shared reference to the rest of the string.
    fn as_ref(&self) -> &str {
        &*self.v
    }
}

impl<'a, T: Pattern<'a>> AsMut<str> for SplitNMut<'a, T> {
    /// Returns a mutable reference to the rest of the string.
    fn as_mut(&mut self) -> &mut str {
        // SAFETY: see the `AsMut` implementation in `SplitMut`.
        unsafe { ptr::read(&self.v) }
    }
}

impl<'a, T: Pattern<'a>> SplitNMut<'a, T> {
    fn v(&mut self) -> &'a mut str {
        mem::replace(&mut self.v, unsafe { from_utf8_unchecked_mut(&mut [][..]) })
    }

    /// Returns `true` if the iterator can't return more substrings.
    #[inline]
    pub fn finished(&self) -> bool {
        self.count == 0
    }
}

impl<'a, T: Pattern<'a>> Iterator for SplitNMut<'a, T> {
    type Item = &'a mut str;

    #[inline]
    fn next(&mut self) -> Option<&'a mut str> {
        if self.finished() {
            return None;
        }

        let tmp1 = self.v();

        // SAFETY: after tmp1 it's used as inmmutable in `into_searcher` and the searcher it's dropped
        // the reference must count as "dead" and then available to use it again as mutable but instead
        // fails to compile and forces me to reborrow it
        let tmp = unsafe { &*(tmp1 as *mut str) };

        if self.count == 1 {
            self.count = 0;
            return Some(tmp1);
        }

        match unsafe { ptr::read(&self.pattern) }.into_searcher(tmp).next_match() {
            None => {
               self.count = 0;
               Some(tmp1) 
            },
            Some((idx1, idx2)) => {
                let len = idx2 - idx1;
                let (head, tail) = tmp1.split_at_mut(idx1);
                self.v = &mut tail[len..];
                self.count = self.count.wrapping_sub(1);
                Some(head)  
            }
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        if self.finished() {
            (0, Some(0))
        } else {
            (1, Some(self.count))
        }
    }
}

impl<'a, U: ReverseSearcher<'a>, T: Pattern<'a, Searcher = U>> DoubleEndedIterator for SplitNMut<'a, T>
{
    #[inline]
    fn next_back(&mut self) -> Option<&'a mut str> {
        if self.finished() {
            return None;
        }

        let tmp1 = self.v();

        let tmp = unsafe { &*(tmp1 as *mut str) };

        if self.count == 1 {
            self.count = 0;
            return Some(tmp1);
        }

        match unsafe { ptr::read(&self.pattern) }.into_searcher(tmp).next_match_back() {
            None => {
               self.count = 0;
               Some(tmp1) 
            },
            Some((idx1, idx2)) => {
                let len = idx2 - idx1;
                let (head, tail) = tmp1.split_at_mut(idx1);
                self.v = head;
                self.count = self.count.wrapping_sub(1);
                Some(&mut tail[len..])
            }
        }
    }
}

impl<'a, T: Pattern<'a>> FusedIterator for SplitNMut<'a, T> {}

#[cfg(test)]
mod test {
    use super::*;

    use alloc::{
        format,
        vec::Vec,
    };

    #[test]
    fn a() {
        let mut b = format!("sdasdasd");

        assert_eq!(b.as_mut().split_mut("a").collect::<Vec<&mut str>>(), ["sd", "sd", "sd"]);
        assert_eq!(format!("sdasdasd").split_mut(&format!("a")).collect::<Vec<&mut str>>(), ["sd", "sd", "sd"]);
        assert_eq!(format!("sdasdasd").split_mut(|c: char| c == 'a').collect::<Vec<&mut str>>(), ["sd", "sd", "sd"]);
        assert_eq!(format!("sdasdasd").split_mut('a').collect::<Vec<&mut str>>(), ["sd", "sd", "sd"]);
        assert_eq!(format!("sdasdasd").split_mut(&['a', 'b'][..]).collect::<Vec<&mut str>>(), ["sd", "sd", "sd"]);
        assert_eq!(format!("sdasdasdads").split_mut("a").rev().collect::<Vec<&mut str>>(), ["ds", "sd", "sd", "sd"]);

        
        assert_eq!(format!("sdasdasd").splitn_mut(2, "a").collect::<Vec<&mut str>>(), ["sd", "sdasd"]);
        assert_eq!(format!("sdasdasd").splitn_mut(2, |c: char| c == 'a').collect::<Vec<&mut str>>(), ["sd", "sdasd"]);
        assert_eq!(format!("sdasdasd").splitn_mut(2, 'a').collect::<Vec<&mut str>>(), ["sd", "sdasd"]);
        assert_eq!(format!("sdasdasd").splitn_mut(2, &['a', 'b'][..]).collect::<Vec<&mut str>>(), ["sd", "sdasd"]);
        assert_eq!(format!("sdasdasdads").splitn_mut(2, "a").rev().collect::<Vec<&mut str>>(), ["ds", "sdasdasd"]);
    }
}