rust/vec2d/src/lib.rs
changeset 13911 fa9f93393e9c
child 13915 f64790b2a725
equal deleted inserted replaced
13910:6c8d4e140f27 13911:fa9f93393e9c
       
     1 use std::iter;
       
     2 use std::ops::{Index, IndexMut};
       
     3 
       
     4 struct Vec2D<T> {
       
     5     data: Vec<T>,
       
     6     width: usize,
       
     7     height: usize,
       
     8 }
       
     9 
       
    10 impl<T> Index<usize> for Vec2D<T> {
       
    11     type Output = [T];
       
    12 
       
    13     #[inline]
       
    14     fn index(&self, row: usize) -> &[T] {
       
    15         debug_assert!(row < self.height);
       
    16 
       
    17         let pos = row * self.width;
       
    18 
       
    19         &self.data[pos..pos + self.width]
       
    20     }
       
    21 }
       
    22 
       
    23 impl<T> IndexMut<usize> for Vec2D<T> {
       
    24     #[inline]
       
    25     fn index_mut(&mut self, row: usize) -> &mut [T] {
       
    26         debug_assert!(row < self.height);
       
    27 
       
    28         let pos = row * self.width;
       
    29 
       
    30         &mut self.data[pos..pos + self.width]
       
    31     }
       
    32 }
       
    33 
       
    34 impl<T: Copy> Vec2D<T> {
       
    35     pub fn new(width: usize, height: usize, value: T) -> Self {
       
    36         let mut vec = Self {
       
    37             data: Vec::new(),
       
    38             width,
       
    39             height,
       
    40         };
       
    41 
       
    42         vec.data.extend(iter::repeat(value).take(width * height));
       
    43 
       
    44         vec
       
    45     }
       
    46 
       
    47     #[inline]
       
    48     pub fn width(&self) -> usize {
       
    49         self.width
       
    50     }
       
    51 
       
    52     #[inline]
       
    53     pub fn height(&self) -> usize {
       
    54         self.height
       
    55     }
       
    56 }
       
    57 
       
    58 #[cfg(test)]
       
    59 mod tests {
       
    60     use super::*;
       
    61 
       
    62     #[test]
       
    63     fn basics() {
       
    64         let mut v: Vec2D<u8> = Vec2D::new(2, 3, 0xff);
       
    65 
       
    66         assert_eq!(v.width, 2);
       
    67         assert_eq!(v.height, 3);
       
    68 
       
    69         assert_eq!(v[0][0], 0xff);
       
    70         assert_eq!(v[2][1], 0xff);
       
    71 
       
    72         v[2][1] = 0;
       
    73 
       
    74         assert_eq!(v[2][0], 0xff);
       
    75         assert_eq!(v[2][1], 0);
       
    76     }
       
    77 }