From f6f593195e332fccbd278a1d8fb13da513df510f Mon Sep 17 00:00:00 2001 From: GCastilho Date: Sat, 9 May 2026 12:17:45 -0300 Subject: [PATCH] feat: Impl Clone for all T: Clone - Add Clone impl for all T that also implement Clone --- src/lib.rs | 46 ++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 1880b60..51dd328 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -30,7 +30,7 @@ impl DoubleBuffer { } /// Get an immutable reference to the current-state buffer. - pub fn current(&self) -> Ref { + pub fn current(&self) -> Ref<'_, T> { match self.switched { false => self.first.borrow(), true => self.second.borrow(), @@ -38,7 +38,7 @@ impl DoubleBuffer { } /// Get a mutable reference to the next-state buffer. - pub fn next(&self) -> RefMut { + pub fn next(&self) -> RefMut<'_, T> { match self.switched { false => self.second.borrow_mut(), true => self.first.borrow_mut(), @@ -46,7 +46,7 @@ impl DoubleBuffer { } /// Get an immutable reference to the next-state buffer. - pub fn next_immut(&self) -> Ref { + pub fn next_immut(&self) -> Ref<'_, T> { match self.switched { false => self.second.borrow(), true => self.first.borrow(), @@ -57,9 +57,17 @@ impl DoubleBuffer { pub fn switch(&mut self) { self.switched = !self.switched; } - } +impl Clone for DoubleBuffer { + fn clone(&self) -> Self { + Self { + first: self.first.clone(), + second: self.second.clone(), + switched: self.switched, + } + } +} #[cfg(test)] mod tests { @@ -96,4 +104,34 @@ mod tests { } + #[test] + fn cloning_instance() { + let my_double_buf: DoubleBuffer> = DoubleBuffer::new(vec![2, 4, 6], Vec::new()); + for number in my_double_buf.current().iter() { + my_double_buf.next().push(*number + 1); + } + + let mut my_clone_buf = my_double_buf.clone(); + my_clone_buf.switch(); + assert_eq!(*my_clone_buf.current(), vec!(3, 5, 7)); + *my_clone_buf.next() = Vec::new(); + for number in my_clone_buf.current().iter() { + my_clone_buf.next().push(*number + 1); + } + + assert_eq!(*my_double_buf.current(), vec!(2, 4, 6)); + } + + + #[test] + fn clone_from_elem() { + let my_many_double_buf = vec![DoubleBuffer::new(vec![2, 4, 6], Vec::new()); 2]; + for mut my_double_buf in my_many_double_buf { + for number in my_double_buf.current().iter() { + my_double_buf.next().push(*number + 1); + } + my_double_buf.switch(); + assert_eq!(*my_double_buf.current(), vec!(3, 5, 7)); + } + } }