SHARE
TWEET

Untitled

a guest Aug 19th, 2019 63 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const SIZE: usize = 3;
  2.  
  3. fn letter(n: u8) -> char {
  4.     assert!(n < 26);
  5.     (n + b'A') as char
  6. }
  7.  
  8. fn main() {
  9.     use rand::Rng;
  10.     let mut rng = rand::thread_rng();
  11.  
  12.     let vec: Vec<char> = (0..SIZE * SIZE)
  13.         .map(|_| letter(rng.gen_range(0, 26)))
  14.         .collect();
  15.     let vec = dbg!(trivial::Trivial2dArr::new(vec));
  16.     dbg!(vec[2][1]);
  17. }
  18.  
  19. mod trivial {
  20.     use super::SIZE;
  21.  
  22.     #[derive(Debug, Clone)]
  23.     pub(crate) struct Trivial2dArr<T>(Box<[T]>); // even better would be Box<[T; SIZE*SIZE]> but we'd need unsafe for the array cast, still, in 2019 :(
  24.  
  25.     impl<T> Trivial2dArr<T> {
  26.         pub(crate) fn new(vec: Vec<T>) -> Self {
  27.             assert_eq!(vec.len(), SIZE * SIZE);
  28.             Self(vec.into())
  29.         }
  30.     }
  31.  
  32.     impl<T> std::ops::Index<usize> for Trivial2dArr<T> {
  33.         type Output = [T];
  34.         fn index(&self, x: usize) -> &[T] {
  35.             let base = x * SIZE;
  36.             &self.0[base..base + SIZE]
  37.         }
  38.     }
  39.     impl<T> std::ops::IndexMut<usize> for Trivial2dArr<T> {
  40.         fn index_mut(&mut self, x: usize) -> &mut [T] {
  41.             let base = x * SIZE;
  42.             &mut self.0[base..base + SIZE]
  43.         }
  44.     }
  45. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top