From 0259c7ed7f1e4c237a745f98080d064a3a41aed1 Mon Sep 17 00:00:00 2001 From: Robert Knight Date: Fri, 11 Oct 2024 17:44:58 +0100 Subject: [PATCH] Eliminate unnecessary `T: Clone` bounds on tensor iterators Replace derived `Clone` impls for tensor iterators with manual implementations to remove the unnecessary `T: Clone` bound that the derived impl adds. See also https://github.com/rust-lang/rust/issues/26925. --- rten-tensor/src/iterators.rs | 41 ++++++++++++++++++++++++++++-------- 1 file changed, 32 insertions(+), 9 deletions(-) diff --git a/rten-tensor/src/iterators.rs b/rten-tensor/src/iterators.rs index cb31aedc..b61de792 100644 --- a/rten-tensor/src/iterators.rs +++ b/rten-tensor/src/iterators.rs @@ -184,22 +184,29 @@ impl IndexingIterBase { } } -/// Iterator over elements of a tensor, in their logical order. -#[derive(Clone)] -pub struct Iter<'a, T> { - iter: IterKind<'a, T>, -} - -/// Alternate implementations of `Elements`. +/// Alternate implementations of [`Iter`]. /// /// When the tensor has a contiguous layout, this iterator is just a thin /// wrapper around a slice iterator. -#[derive(Clone)] enum IterKind<'a, T> { Direct(slice::Iter<'a, T>), Indexing(IndexingIter<'a, T>), } +impl<'a, T> Clone for IterKind<'a, T> { + fn clone(&self) -> Self { + match self { + IterKind::Direct(slice_iter) => IterKind::Direct(slice_iter.clone()), + IterKind::Indexing(iter) => IterKind::Indexing((*iter).clone()), + } + } +} + +/// Iterator over elements of a tensor, in their logical order. +pub struct Iter<'a, T> { + iter: IterKind<'a, T>, +} + impl<'a, T> Iter<'a, T> { pub(super) fn new(view: ViewRef<'a, '_, T, L>) -> Iter<'a, T> { if let Some(data) = view.contiguous_data() { @@ -214,6 +221,14 @@ impl<'a, T> Iter<'a, T> { } } +impl<'a, T> Clone for Iter<'a, T> { + fn clone(&self) -> Self { + Iter { + iter: self.iter.clone(), + } + } +} + impl<'a, T> Iterator for Iter<'a, T> { type Item = &'a T; @@ -247,7 +262,6 @@ impl<'a, T> ExactSizeIterator for Iter<'a, T> {} impl<'a, T> FusedIterator for Iter<'a, T> {} -#[derive(Clone)] struct IndexingIter<'a, T> { base: IndexingIterBase, @@ -264,6 +278,15 @@ impl<'a, T> IndexingIter<'a, T> { } } +impl<'a, T> Clone for IndexingIter<'a, T> { + fn clone(&self) -> Self { + IndexingIter { + base: self.base.clone(), + data: self.data, + } + } +} + impl<'a, T> Iterator for IndexingIter<'a, T> { type Item = &'a T;