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
use crate::{
    iter_raw::{iter_with_raw, IterRaw, IterRawAdapter},
    Slice, SliceMut, SoaRaw, Soars,
};
use std::{
    fmt::{self, Debug, Formatter},
    iter::FusedIterator,
    marker::PhantomData,
};

/// Mutable [`Slice`] iterator.
///
/// This struct is created by the [`iter_mut`] method.
///
/// [`Slice`]: crate::Slice
/// [`iter_mut`]: crate::Slice::iter_mut
pub struct IterMut<'a, T>
where
    T: 'a + Soars,
{
    pub(crate) iter_raw: IterRaw<T, Self>,
    pub(crate) _marker: PhantomData<&'a mut T>,
}

impl<'a, T> Debug for IterMut<'a, T>
where
    T: Soars,
    for<'b> T::Ref<'b>: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self.as_slice())
    }
}

impl<'a, T> Default for IterMut<'a, T>
where
    T: Soars,
{
    fn default() -> Self {
        Self {
            iter_raw: IterRaw {
                slice: Slice::empty(),
                len: 0,
                adapter: PhantomData,
            },
            _marker: PhantomData,
        }
    }
}

impl<'a, T> IterRawAdapter<T> for IterMut<'a, T>
where
    T: Soars,
{
    type Item = T::RefMut<'a>;

    fn item_from_raw(raw: <T as Soars>::Raw) -> Self::Item {
        unsafe { raw.get_mut() }
    }
}

impl<'a, T> IterMut<'a, T>
where
    T: Soars,
{
    /// Returns an immutable slice of all elements that have not been yielded
    /// yet.
    pub fn as_slice(&self) -> &Slice<T> {
        unsafe { self.iter_raw.slice.as_unsized(self.iter_raw.len) }
    }

    /// Returns a mutable slice of all elements that have not been yielded yet.
    pub fn as_mut_slice(&mut self) -> &mut Slice<T> {
        unsafe { self.iter_raw.slice.as_unsized_mut(self.iter_raw.len) }
    }

    /// Returns a mutable slice of all elements that have not been yielded yet.
    ///
    /// To avoid creating `&mut` references that alias, this is forced to
    /// consume the iterator.
    pub fn into_slice(self) -> SliceMut<'a, T> {
        SliceMut {
            slice: self.iter_raw.slice,
            len: self.iter_raw.len,
            marker: PhantomData,
        }
    }
}

iter_with_raw!(IterMut<'a, T>, 'a);