1 //! Helper functions for computing modular index safely.
2
3 /// Computes modular offset safely for indices.
4 #[inline(always)]
offset(n: usize, i: usize, off: isize) -> usize5 pub fn offset(n: usize, i: usize, off: isize) -> usize {
6 (i + (off % n as isize + n as isize) as usize) % n
7 }
8
9 /// Computes previous modular index safely.
10 #[inline(always)]
previous(n: usize, i: usize) -> usize11 pub fn previous(n: usize, i: usize) -> usize {
12 offset(n, i, -1)
13 }
14
15 /// Computes next modular index safely.
16 #[inline(always)]
next(n: usize, i: usize) -> usize17 pub fn next(n: usize, i: usize) -> usize {
18 offset(n, i, 1)
19 }
20
21 #[cfg(test)]
22 mod tests {
23 use super::*;
24
25 #[test]
test_offset()26 fn test_offset() {
27 assert_eq!(offset(3, 0, -1), 2);
28 assert_eq!(offset(3, 1, -1), 0);
29 assert_eq!(offset(3, 2, -1), 1);
30 assert_eq!(offset(3, 3, -1), 2);
31
32 assert_eq!(offset(3, 0, 1), 1);
33 assert_eq!(offset(3, 1, 1), 2);
34 assert_eq!(offset(3, 2, 1), 0);
35 assert_eq!(offset(3, 3, 1), 1);
36 }
37 }
38