Advertisement
Guest User

Untitled

a guest
Aug 21st, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. //! The following code is licensed under `CC0-1.0`.
  2.  
  3. fn main() {
  4. let mut counter = Alphabets::<usize>::new();
  5. counter[b'A'] += 42;
  6. counter[b'Z'] += 100;
  7. dbg!(counter);
  8. }
  9.  
  10. // "Associated constants" was stabilized in Rust 1.20
  11. const A: u8 = b'A';
  12.  
  13. // "impl Trait" was stabilized in Rust 1.26
  14. type Iter<'a, T> =
  15. std::iter::Map<std::iter::Enumerate<std::slice::Iter<'a, T>>, fn((usize, &T)) -> (u8, T)>;
  16.  
  17. #[derive(Default)]
  18. struct Alphabets<T>([T; 26]);
  19.  
  20. impl<T: Default> Alphabets<T> {
  21. fn new() -> Self {
  22. Self::default()
  23. }
  24. }
  25.  
  26. impl<T: Copy> Alphabets<T> {
  27. fn iter(&self) -> Iter<T> {
  28. self.0.iter().enumerate().map(|(i, &v)| (i as u8 + A, v))
  29. }
  30.  
  31. fn values(&self) -> std::iter::Cloned<std::slice::Iter<T>> {
  32. self.0.iter().cloned()
  33. }
  34. }
  35.  
  36. impl<T: Copy + Ord> Alphabets<T> {
  37. fn max(&self) -> T {
  38. self.0.iter().cloned().max().unwrap()
  39. }
  40.  
  41. fn min(&self) -> T {
  42. self.0.iter().cloned().min().unwrap()
  43. }
  44. }
  45.  
  46. impl<T> std::ops::Index<u8> for Alphabets<T> {
  47. type Output = T;
  48.  
  49. fn index(&self, idx: u8) -> &T {
  50. &self.0[usize::from(idx - A)]
  51. }
  52. }
  53.  
  54. impl<T> std::ops::IndexMut<u8> for Alphabets<T> {
  55. fn index_mut(&mut self, idx: u8) -> &mut T {
  56. &mut self.0[usize::from(idx - A)]
  57. }
  58. }
  59.  
  60. impl<T: std::fmt::Debug> std::fmt::Debug for Alphabets<T> {
  61. fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
  62. let mut fmt = fmt.debug_map();
  63. fmt.entries((A..A + 26).map(|c| (char::from(c), &self[c])));
  64. fmt.finish()
  65. }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement