big_int/
get_back.rs

1//! Safely retrieve items from a collection with negative indexing.
2 
3/// Safely retrieve items from a collection with negative indexing.
4pub trait GetBack {
5  type Item;
6
7  /// Safely retrieve items from a collection with negative indexing.
8  /// Returns `None` if the index is larger than the length of the collection.
9  fn get_back(&self, index: usize) -> Option<Self::Item>;
10}
11
12impl<T: Copy> GetBack for Vec<T> {
13  type Item = T;
14  fn get_back(&self, index: usize) -> Option<Self::Item> {
15      self.len()
16          .checked_sub(index)
17          .and_then(|index| self.get(index)).copied()
18  }
19}
20
21/// Safely retrieve a mutable reference from a collection with negative indexing.
22pub trait GetBackMut {
23  type Item;
24
25  /// Safely retrieve a mutable reference from a collection with negative indexing.
26  /// Returns `None` if the index is larger than the length of the collection.
27  fn get_back_mut(&mut self, index: usize) -> Option<&mut Self::Item>;
28}
29
30impl<T> GetBackMut for Vec<T> {
31  type Item = T;
32  fn get_back_mut(&mut self, index: usize) -> Option<&mut Self::Item> {
33      self.len()
34          .checked_sub(index)
35          .and_then(|index| self.get_mut(index))
36  }
37}