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
// Copyright 2021 Vill. Snow

//! Just add traits for post increment and decrement.
//!
//! ```
//! use post_incr::PostIncr as _;
//! use post_incr::PostDecr as _;
//!
//! let mut x: i32 = 0;
//! assert_eq!(x.post_incr(), 0);
//! assert_eq!(x.post_incr(), 1);
//! assert_eq!(x.post_incr(), 2);
//!
//! assert_eq!(x.post_decr(), 3);
//! assert_eq!(x.post_decr(), 2);
//! assert_eq!(x.post_decr(), 1);
//! ```

use core::ops::AddAssign;
use core::ops::SubAssign;

pub trait PostIncr {
    /// `x++` in other language.
    ///
    /// ```
    /// use post_incr::PostIncr as _;
    ///
    /// let mut x: i32 = 0;
    /// assert_eq!(x.post_incr(), 0);
    /// assert_eq!(x.post_incr(), 1);
    /// assert_eq!(x.post_incr(), 2);
    /// ```
    fn post_incr(&mut self) -> Self;
}

pub trait PostDecr {
    /// `x--` in other language.
    ///
    /// ```
    /// use post_incr::PostDecr as _;
    ///
    /// let mut x: i32 = 0;
    /// assert_eq!(x.post_decr(), 0);
    /// assert_eq!(x.post_decr(), -1);
    /// assert_eq!(x.post_decr(), -2);
    /// ```
    fn post_decr(&mut self) -> Self;
}

impl<T> PostIncr for T
where
    Self: Copy + AddAssign + num_traits::One,
{
    fn post_incr(&mut self) -> Self {
        let bk = *self;
        *self += Self::one();
        bk
    }
}

impl<T> PostDecr for T
where
    Self: Copy + SubAssign + num_traits::One,
{
    fn post_decr(&mut self) -> Self {
        let bk = *self;
        *self -= Self::one();
        bk
    }
}