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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
//! This module defines an index type that can be invalid, although it has the same size as
//! usize. This allows collections of `usize` integers to be reinterpreted as collections of
//! `Index` types.
//! For indexing into mesh topologies use types defined in the `mesh::topology` module.
use std::fmt;
use std::ops::{Add, AddAssign, Div, Mul, Rem, Sub};

mod checked;

pub use self::checked::*;

/// A possibly invalid unsigned index.
/// The maximum `usize` integer represents an invalid index.
/// This index type is ideal for storage.
/// Overflow is not handled by this type. Instead we rely on Rust's internal overflow panics during
/// debug builds.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Index(usize);

impl Index {
    /// Invalid index instance.
    pub const INVALID: Index = Index(std::usize::MAX);

    /// Create a valid index from a usize type. This constructor does the necessary check
    /// for debug builds only.
    #[inline]
    pub fn new(i: usize) -> Index {
        debug_assert!(Index::fits(i));
        Index(i)
    }

    /// Convert this `Index` into `Option<usize>`, which is a larger struct.
    #[inline]
    pub fn into_option(self) -> Option<usize> {
        self.into()
    }

    /// Manipulate the inner representation of the index. This method avoids the additional check
    /// used in `map`. Use this to opt out of automatic index checking.
    #[inline]
    pub fn map_inner<F: FnOnce(usize) -> usize>(self, f: F) -> Index {
        Index(f(self.0))
    }

    /// Checked `and_then` over inner index. This allows operations on valid indices only.
    #[inline]
    pub fn and_then<F: FnOnce(usize) -> Index>(self, f: F) -> Index {
        if self.is_valid() {
            f(self.0 as usize)
        } else {
            self
        }
    }

    /// Apply a function to the inner `usize` index. The index remains unchanged if invalid.
    #[inline]
    pub fn apply<F: FnOnce(&mut usize)>(&mut self, f: F) {
        if self.is_valid() {
            f(&mut self.0);
        }
    }

    /// Apply a function to the inner `usize` index.
    #[inline]
    pub fn if_valid<F: FnOnce(usize)>(self, f: F) {
        if self.is_valid() {
            f(self.0);
        }
    }

    /// Get the raw `usize` representation of this Index. This may be useful for performance
    /// critical code or debugging.
    #[inline]
    pub fn into_inner(self) -> usize {
        self.0
    }

    /// Check that the given index fits inside the internal Index representation. This is used
    /// internally to check various conversions and arithmetics for debug builds.
    #[inline]
    fn fits(i: usize) -> bool {
        i != std::usize::MAX
    }
}

macro_rules! impl_from_unsigned {
    ($u:ty) => {
        /// Create a valid index from a `usize` type. This converter does the necessary bounds
        /// check for debug builds only.
        impl From<$u> for Index {
            #[inline]
            fn from(i: $u) -> Self {
                Index::new(i as usize)
            }
        }
    };
}

impl_from_unsigned!(usize);
impl_from_unsigned!(u64);
impl_from_unsigned!(u32);
impl_from_unsigned!(u16);
impl_from_unsigned!(u8);

macro_rules! impl_from_signed {
    ($i:ty) => {
        /// Create an index from a signed integer type. If the given argument is negative, the
        /// created index will be invalid.
        impl From<$i> for Index {
            #[inline]
            fn from(i: $i) -> Self {
                if i < 0 {
                    Index::invalid()
                } else {
                    Index(i as usize)
                }
            }
        }
    };
}

impl_from_signed!(isize);
impl_from_signed!(i64);
impl_from_signed!(i32);
impl_from_signed!(i16);
impl_from_signed!(i8);

impl Into<Option<usize>> for Index {
    #[inline]
    fn into(self) -> Option<usize> {
        if self.is_valid() {
            Some(self.0 as usize)
        } else {
            None
        }
    }
}

impl From<Option<usize>> for Index {
    #[inline]
    fn from(i: Option<usize>) -> Index {
        match i {
            Some(i) => Index::new(i),
            None => Index::INVALID,
        }
    }
}

impl Add<usize> for Index {
    type Output = Index;

    #[inline]
    fn add(self, rhs: usize) -> Index {
        self.map(|x| x + rhs)
    }
}

impl AddAssign<usize> for Index {
    #[inline]
    fn add_assign(&mut self, rhs: usize) {
        self.apply(|x| *x += rhs)
    }
}

impl Add<Index> for usize {
    type Output = Index;

    #[inline]
    fn add(self, rhs: Index) -> Index {
        rhs + self
    }
}

impl Add for Index {
    type Output = Index;

    #[inline]
    fn add(self, rhs: Index) -> Index {
        // Note: add with overflow is checked by Rust for debug builds.
        self.and_then(|x| rhs.map(|y| x + y))
    }
}

impl Sub<usize> for Index {
    type Output = Index;

    #[inline]
    fn sub(self, rhs: usize) -> Index {
        self.map(|x| x - rhs)
    }
}

impl Sub<Index> for usize {
    type Output = Index;

    #[inline]
    fn sub(self, rhs: Index) -> Index {
        rhs.map(|x| self - x)
    }
}

impl Sub for Index {
    type Output = Index;

    #[inline]
    fn sub(self, rhs: Index) -> Index {
        // Note: subtract with overflow is checked by Rust for debug builds.
        self.and_then(|x| rhs.map(|y| x - y))
    }
}

impl Mul<usize> for Index {
    type Output = Index;

    #[inline]
    fn mul(self, rhs: usize) -> Index {
        self.map(|x| x * rhs)
    }
}

impl Mul<Index> for usize {
    type Output = Index;

    #[inline]
    fn mul(self, rhs: Index) -> Index {
        rhs * self
    }
}

// It often makes sense to divide an index by a non-zero integer
impl Div<usize> for Index {
    type Output = Index;

    #[inline]
    fn div(self, rhs: usize) -> Index {
        if rhs != 0 {
            self.map(|x| x / rhs)
        } else {
            Index::invalid()
        }
    }
}

impl Rem<usize> for Index {
    type Output = Index;

    #[inline]
    fn rem(self, rhs: usize) -> Index {
        if rhs != 0 {
            self.map(|x| x % rhs)
        } else {
            Index::invalid()
        }
    }
}

impl PartialEq<usize> for Index {
    #[inline]
    fn eq(&self, other: &usize) -> bool {
        self.map_or(false, |x| x == *other)
    }
}

impl PartialOrd<usize> for Index {
    #[inline]
    fn partial_cmp(&self, other: &usize) -> Option<std::cmp::Ordering> {
        self.map_or(None, |x| x.partial_cmp(other))
    }
}

impl Default for Index {
    fn default() -> Self {
        Self::invalid()
    }
}

impl fmt::Display for Index {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

// Since we can't use a generic parameter when implementing traits for structs from
// other packages, we have to use a macro here and anticipate the types of things
// would need to index.
macro_rules! impl_index_for {
    (__impl, $value_type:ty, $idx_type:ty) => {
        impl ::std::ops::Index<$idx_type> for Vec<$value_type> {
            type Output = $value_type;
            fn index(&self, index: $idx_type) -> &$value_type {
                &self[usize::from(index)]
            }
        }
        impl ::std::ops::IndexMut<$idx_type> for Vec<$value_type> {
            fn index_mut(&mut self, index: $idx_type) -> &mut $value_type {
                &mut self[usize::from(index)]
            }
        }
    };
    (Vec<$value_type:ty> by $($idx_type:ty),+) => {
        $(impl_index_for!(__impl, $value_type, $idx_type);)*
    };
    // If the collection contains a generic type. We have to wrap the Vec into a custom collection
    // type. The following rules will do this for us automatically
    (__impl_newtype, $collection_type:ident (Vec<$value_type:ty>) by $idx_type:ty) => {
        impl ::std::ops::Index<$idx_type> for $collection_type {
            type Output = $value_type;
            fn index(&self, index: $idx_type) -> &$value_type {
                &self.0[usize::from(index)]
            }
        }
        impl ::std::ops::IndexMut<$idx_type> for $collection_type {
            fn index_mut(&mut self, index: $idx_type) -> &mut $value_type {
                &mut self.0[usize::from(index)]
            }
        }
    };
    (__impl_newtype, $collection_type:ident (Vec<$value_type:ty>) by $idx_type:ty
     where $t:ident: $($traits:tt)*) => {
        impl<$t: $($traits)*> ::std::ops::Index<$idx_type> for $collection_type<$t> {
            type Output = $value_type;
            fn index(&self, index: $idx_type) -> &$value_type {
                &self.0[usize::from(index)]
            }
        }
        impl<$t: $($traits)*> ::std::ops::IndexMut<$idx_type> for $collection_type<$t> {
            fn index_mut(&mut self, index: $idx_type) -> &mut $value_type {
                &mut self.0[usize::from(index)]
            }
        }
    };
    // Custom dynamically sized collection with a generic parameter.
    ($collection_type:ident (Vec<$value_type:ty>) by $($idx_type:ty),+
     where $t:ident: $($traits:tt)*) => {
        #[derive(Clone, Debug, PartialEq, NewCollectionType)]
        #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
        pub struct $collection_type<$t: $($traits)*>(Vec<$value_type>);

        $(impl_index_for!(__impl_newtype, $collection_type(Vec<$value_type>) by $idx_type
                          where $t: $traits);)*
    };
    // Custom dynamically sized collection, no generics
    ($collection_type:ident (Vec<$value_type:ty>) by $($idx_type:ty),+) => {
        #[derive(Clone, Debug, PartialEq, NewCollectionType)]
        #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
        pub struct $collection_type(Vec<$value_type>);

        $(impl_index_for!(__impl_newtype, $collection_type(Vec<$value_type>) by $idx_type);)*
    };
    // Custom statically sized collection, no generics
    ($collection_type:ident ([$value_type:ty; $n:expr]) by $($idx_type:ty),+) => {
        #[derive(Clone, Debug, PartialEq, NewCollectionType)]
        #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
        pub struct $collection_type([$value_type;$n]);

        $(impl_index_for!(__impl_newtype, $collection_type(Vec<$value_type>) by $idx_type);)*
    };
}

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

    #[test]
    fn index_test() {
        let i = Index::new(2);
        let j = Index::new(4);
        let k = Index::invalid();
        assert_eq!(i + j, Index::new(6));
        assert_eq!(j - i, Index::new(2));
        assert_eq!(j * 3, Index::new(12));
        assert_eq!(j % 3, Index::new(1));
        assert_eq!(j / 3, Index::new(1));
        assert_eq!(i - k, Index::invalid());
        assert_eq!(i + k, Index::invalid());
        assert_eq!(k * 2, Index::invalid());
        assert_eq!(k / 2, Index::invalid());
        assert_eq!(k % 2, Index::invalid());
    }
}