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
// Copyright (C) 2020 Daniel Mueller <deso@posteo.net>
// SPDX-License-Identifier: GPL-3.0-or-later

use std::ops::Add as _;


/// A trait representing the capability to increment a value.
pub trait Inc {
  /// Increment self and return the new value.
  fn inc(self) -> Self;
}

macro_rules! inc {
  ( $t:ty ) => {
    impl Inc for $t {
      fn inc(self) -> Self {
        self.add(1)
      }
    }
  };
}

inc!(u8);
inc!(i8);
inc!(u16);
inc!(i16);
inc!(u32);
inc!(i32);
inc!(u64);
inc!(i64);
inc!(u128);
inc!(i128);
inc!(usize);
inc!(isize);


#[cfg(test)]
mod tests {
  use super::*;


  #[test]
  fn increment() {
    fn inc<T>(x: T) -> T
    where
      T: Inc,
    {
      x.inc()
    }

    assert_eq!(inc(1u8), 2);
    assert_eq!(inc(-1i16), 0);
    assert_eq!(inc(129_012u32), 129_013);
    assert_eq!(inc(42usize), 43);
  }
}