-
Notifications
You must be signed in to change notification settings - Fork 332
/
Copy patharray_index.rs
44 lines (40 loc) · 1.08 KB
/
array_index.rs
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
/*
* Copyright Redis Ltd. 2016 - present
* Licensed under your choice of the Redis Source Available License 2.0 (RSALv2) or
* the Server Side Public License v1 (SSPLv1).
*/
pub trait ArrayIndex {
fn normalize(self, len: i64) -> usize;
}
impl ArrayIndex for i64 {
fn normalize(self, len: i64) -> usize {
let index = if self < 0 {
len - len.min(-self)
} else if len > 0 {
(len - 1).min(self)
} else {
0
};
index as usize
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_index() {
// [0,1,2,3,4]
assert_eq!((-6).normalize(5), 0);
assert_eq!((-5).normalize(5), 0);
assert_eq!((-2).normalize(5), 3);
assert_eq!((-1).normalize(5), 4);
assert_eq!(0.normalize(5), 0);
assert_eq!(1.normalize(5), 1);
assert_eq!(4.normalize(5), 4);
assert_eq!(5.normalize(5), 4);
assert_eq!(6.normalize(5), 4);
assert_eq!(0.normalize(0), 0);
assert_eq!((-1).normalize(0), 0);
assert_eq!(1.normalize(0), 0);
}
}