dbulfin_lib/
lib.rs

1pub trait ApplyAssign<T> {
2    /// Applies a function to a variable and sets the variable to
3    /// the resulting value
4    ///
5    /// # Examples
6    /// ```
7    /// use crate::dbulfin_lib::ApplyAssign;
8    ///
9    /// let mut x = (1, 2);
10    /// x.app_ass(|(x, y)| (y, x));
11    /// assert_eq!(x, (2, 1))
12    /// ```
13    fn app_ass<F>(&mut self, f: F)
14    where
15        F: FnOnce(T) -> T;
16}
17
18impl<T> ApplyAssign<T> for T
19where
20    T: Clone,
21{
22    fn app_ass<F>(&mut self, f: F)
23    where
24        F: FnOnce(T) -> T,
25    {
26        *self = f(self.clone())
27    }
28}
29
30/// Reverse a String value char-wise
31/// 
32/// # Examples
33/// ```
34/// use crate::dbulfin_lib::rev_string;
35///
36/// let mut s = String::from("ABC");
37/// assert_eq!(rev_string(s), String::from("CBA"))
38/// ```
39pub fn rev_string(s: String) ->String {
40    s.chars().rev().collect()
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46
47    fn tuple_edit(x: (i32, i32)) -> (i32, i32) {
48        (x.1, x.0)
49    }
50
51    fn vec_edit(x: Vec<i32>) -> Vec<i32> {
52        x.into_iter().rev().collect()
53    }
54
55    #[test]
56    fn tuples() {
57        let mut x = (1, 2);
58
59        x.app_ass(tuple_edit);
60
61        assert_eq!(x, (2, 1))
62    }
63
64    #[test]
65    fn vecs() {
66        let mut x = vec![1, 2, 3];
67
68        x.app_ass(vec_edit);
69
70        assert_eq!(x, vec![3, 2, 1])
71    }
72}