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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
use std::fmt::Debug;
use std::ops::AddAssign;
use num_traits::int::PrimInt;
pub trait SpIndex:
Debug + PrimInt + AddAssign<Self> + Default + Send + Sync
{
fn index(self) -> usize;
fn try_index(self) -> Option<usize>;
fn index_unchecked(self) -> usize;
fn from_usize(ind: usize) -> Self;
fn try_from_usize(ind: usize) -> Option<Self>;
fn from_usize_unchecked(ind: usize) -> Self;
}
impl SpIndex for usize {
#[inline(always)]
fn index(self) -> usize {
self
}
#[inline(always)]
fn try_index(self) -> Option<usize> {
Some(self)
}
#[inline(always)]
fn index_unchecked(self) -> usize {
self
}
#[inline(always)]
fn from_usize(ind: usize) -> Self {
ind
}
#[inline(always)]
fn try_from_usize(ind: usize) -> Option<Self> {
Some(ind)
}
#[inline(always)]
fn from_usize_unchecked(ind: usize) -> Self {
ind
}
}
macro_rules! sp_index_impl {
($int: ident) => {
impl SpIndex for $int {
#[inline(always)]
fn index(self) -> usize {
self.try_index().unwrap_or_else(|| {
panic!("Failed to convert {} to usize", self)
})
}
#[inline(always)]
fn try_index(self) -> Option<usize> {
num_traits::cast(self)
}
#[inline(always)]
fn index_unchecked(self) -> usize {
debug_assert!(self.try_index().is_some());
self as usize
}
#[inline(always)]
fn from_usize(ind: usize) -> Self {
Self::try_from_usize(ind).unwrap_or_else(|| {
panic!("Failed to convert {} to index type", ind)
})
}
#[inline(always)]
fn try_from_usize(ind: usize) -> Option<Self> {
num_traits::cast(ind)
}
#[inline(always)]
fn from_usize_unchecked(ind: usize) -> Self {
debug_assert!(Self::try_from_usize(ind).is_some());
ind as $int
}
}
};
}
sp_index_impl!(isize);
sp_index_impl!(i64);
sp_index_impl!(i32);
sp_index_impl!(i16);
sp_index_impl!(u64);
sp_index_impl!(u32);
sp_index_impl!(u16);
#[cfg(test)]
mod test {
use super::SpIndex;
#[test]
#[should_panic]
fn overflow_u16() {
let b: u16 = u16::from_usize(131072);
println!("{}", b);
}
#[test]
#[should_panic]
fn negative_i16() {
let b: i16 = -1;
let a = b.index();
println!("{}", a);
}
}