bump_scope/owned_str/
drain.rs

1use core::{fmt, iter::FusedIterator, ptr::NonNull, str::Chars};
2
3use crate::BumpBox;
4
5/// A draining iterator for an owned string.
6///
7/// This struct is created by the `drain` method on
8/// [`BumpBox<str>`](BumpBox<str>::drain),
9/// [`FixedBumpString`](crate::FixedBumpString::drain),
10/// [`BumpString`](crate::BumpString::drain) and
11/// [`MutBumpString`](crate::MutBumpString::drain).
12///
13/// See their documentation for more.
14pub struct Drain<'a> {
15    /// Will be used as `&'a mut BumpBox<str>` in the destructor
16    pub(crate) string: NonNull<BumpBox<'a, str>>,
17    /// Start of part to remove
18    pub(crate) start: usize,
19    /// End of part to remove
20    pub(crate) end: usize,
21    /// Current remaining range to remove
22    pub(crate) iter: Chars<'a>,
23}
24
25impl fmt::Debug for Drain<'_> {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        f.debug_tuple("Drain").field(&self.as_str()).finish()
28    }
29}
30
31unsafe impl Sync for Drain<'_> {}
32unsafe impl Send for Drain<'_> {}
33
34impl Drop for Drain<'_> {
35    fn drop(&mut self) {
36        unsafe {
37            // Use `BumpBox::<[u8]>::drain`. "Reaffirm" the bounds checks to avoid
38            // panic code being inserted again.
39            let self_vec = self.string.as_mut().as_mut_bytes();
40
41            if self.start <= self.end && self.end <= self_vec.len() {
42                self_vec.drain(self.start..self.end);
43            }
44        }
45    }
46}
47
48impl Drain<'_> {
49    /// Returns the remaining (sub)string of this iterator as a slice.
50    ///
51    /// # Examples
52    ///
53    /// ```
54    /// # use bump_scope::Bump;
55    /// # let bump: Bump = Bump::new();
56    /// let mut s = bump.alloc_str("abc");
57    /// let mut drain = s.drain(..);
58    /// assert_eq!(drain.as_str(), "abc");
59    /// let _ = drain.next().unwrap();
60    /// assert_eq!(drain.as_str(), "bc");
61    /// ```
62    #[must_use]
63    pub fn as_str(&self) -> &str {
64        self.iter.as_str()
65    }
66}
67
68impl AsRef<str> for Drain<'_> {
69    fn as_ref(&self) -> &str {
70        self.as_str()
71    }
72}
73
74impl AsRef<[u8]> for Drain<'_> {
75    fn as_ref(&self) -> &[u8] {
76        self.as_str().as_bytes()
77    }
78}
79
80impl Iterator for Drain<'_> {
81    type Item = char;
82
83    #[inline]
84    fn next(&mut self) -> Option<char> {
85        self.iter.next()
86    }
87
88    #[inline]
89    fn size_hint(&self) -> (usize, Option<usize>) {
90        self.iter.size_hint()
91    }
92
93    #[inline]
94    fn last(mut self) -> Option<char> {
95        self.next_back()
96    }
97}
98
99impl DoubleEndedIterator for Drain<'_> {
100    #[inline]
101    fn next_back(&mut self) -> Option<char> {
102        self.iter.next_back()
103    }
104}
105
106impl FusedIterator for Drain<'_> {}