slice_mip/
lib.rs

1//! Mutate a slice in place with a map function.
2//!
3//! Note that the map result type must be the same as the input type.
4//!
5//! ## Example
6//!
7//! ```rust
8//! use slice_mip::MapInPlace;
9//!
10//! let mut buf = [1, 2, 3, 4];
11//! buf.map_in_place(|x| x * 2);
12//!
13//! assert_eq!(buf, [2, 4, 6, 8]);
14//! ```
15
16/// A sequence that can be mutated in place.
17pub trait MapInPlace<T> {
18    /// Apply the given map function to each item in the current sequence and replace each
19    /// item with its associated map result.
20    fn map_in_place<F>(&mut self, f: F) where F: FnMut(&T) -> T;
21}
22
23impl<T> MapInPlace<T> for [T] {
24    fn map_in_place<F>(&mut self, mut f: F) where F: FnMut(&T) -> T {
25        for item in self.iter_mut() {
26            *item = f(item);
27        }
28    }
29}
30
31#[cfg(test)]
32mod test {
33    use super::*;
34
35    #[test]
36    fn test_map_in_place() {
37        let mut buf = [0, 1, 2, 3];
38        buf.map_in_place(|x| x + 1);
39
40        assert_eq!(buf, [1, 2, 3, 4]);
41    }
42}