diff --git a/doc/tutorial-container.md b/doc/tutorial-container.md index 1f47c3df14f..bd706d41288 100644 --- a/doc/tutorial-container.md +++ b/doc/tutorial-container.md @@ -319,6 +319,16 @@ for x in it.invert() { } ~~~ +The `reverse_` method is also available for any double-ended iterator yielding +mutable references. It can be used to reverse a container in-place. Note that +the trailing underscore is a workaround for issue #5898 and will be removed. + +~~~ +let mut ys = [1, 2, 3, 4, 5]; +ys.mut_iter().reverse_(); +assert_eq!(ys, [5, 4, 3, 2, 1]); +~~~ + ## Random-access iterators The `RandomAccessIterator` trait represents an iterator offering random access diff --git a/src/libstd/iterator.rs b/src/libstd/iterator.rs index 554913ab5ec..36e62856464 100644 --- a/src/libstd/iterator.rs +++ b/src/libstd/iterator.rs @@ -24,6 +24,7 @@ use ops::{Add, Mul, Sub}; use cmp::Ord; use clone::Clone; use uint; +use util; /// Conversion from an `Iterator` pub trait FromIterator<A> { @@ -583,6 +584,26 @@ pub trait DoubleEndedIterator<A>: Iterator<A> { } } +/// A double-ended iterator yielding mutable references +pub trait MutableDoubleEndedIterator { + // FIXME: #5898: should be called `reverse` + /// Use an iterator to reverse a container in-place + fn reverse_(&mut self); +} + +impl<'self, A, T: DoubleEndedIterator<&'self mut A>> MutableDoubleEndedIterator for T { + // FIXME: #5898: should be called `reverse` + /// Use an iterator to reverse a container in-place + fn reverse_(&mut self) { + loop { + match (self.next(), self.next_back()) { + (Some(x), Some(y)) => util::swap(x, y), + _ => break + } + } + } +} + /// An object implementing random access indexing by `uint` /// /// A `RandomAccessIterator` should be either infinite or a `DoubleEndedIterator`. @@ -2338,4 +2359,11 @@ mod tests { assert_eq!(range_inclusive(0i, 5).collect::<~[int]>(), ~[0i, 1, 2, 3, 4, 5]); assert_eq!(range_inclusive(0i, 5).invert().collect::<~[int]>(), ~[5i, 4, 3, 2, 1, 0]); } + + #[test] + fn test_reverse() { + let mut ys = [1, 2, 3, 4, 5]; + ys.mut_iter().reverse_(); + assert_eq!(ys, [5, 4, 3, 2, 1]); + } } diff --git a/src/libstd/prelude.rs b/src/libstd/prelude.rs index 893c32e830a..7a0346c94fc 100644 --- a/src/libstd/prelude.rs +++ b/src/libstd/prelude.rs @@ -51,8 +51,8 @@ pub use container::{Container, Mutable, Map, MutableMap, Set, MutableSet}; pub use hash::Hash; pub use iter::Times; pub use iterator::Extendable; -pub use iterator::{Iterator, DoubleEndedIterator}; -pub use iterator::{ClonableIterator, OrdIterator}; +pub use iterator::{Iterator, DoubleEndedIterator, ClonableIterator, OrdIterator}; +pub use iterator::MutableDoubleEndedIterator; pub use num::{Num, NumCast, CheckedAdd, CheckedSub, CheckedMul}; pub use num::{Orderable, Signed, Unsigned, Round}; pub use num::{Algebraic, Trigonometric, Exponential, Hyperbolic};