Add get_mut() to Vec2D
authorunc0rr
Sun, 14 Oct 2018 23:16:11 +0200
changeset 13937 cd437d76978a
parent 13936 f64790b2a725
child 13938 a83ba9ba1566
Add get_mut() to Vec2D
rust/vec2d/src/lib.rs
--- a/rust/vec2d/src/lib.rs	Sun Oct 14 21:26:15 2018 +0200
+++ b/rust/vec2d/src/lib.rs	Sun Oct 14 23:16:11 2018 +0200
@@ -1,7 +1,7 @@
-use std::iter;
 use std::ops::{Index, IndexMut};
+use std::slice::SliceIndex;
 
-struct Vec2D<T> {
+pub struct Vec2D<T> {
     data: Vec<T>,
     width: usize,
     height: usize,
@@ -49,6 +49,11 @@
     pub fn height(&self) -> usize {
         self.height
     }
+
+    #[inline]
+    pub fn get_mut(&mut self, row: usize, column: usize) -> Option<&mut <usize as SliceIndex<[T]>>::Output> {
+        self.data.get_mut(row * self.width + column)
+    }
 }
 
 #[cfg(test)]
@@ -69,5 +74,10 @@
 
         assert_eq!(v[2][0], 0xff);
         assert_eq!(v[2][1], 0);
+
+        v.get_mut(2, 1).map(|v| *v = 1);
+        assert_eq!(v[2][1], 1);
+
+        assert_eq!(v.get_mut(2, 2), None);
     }
 }