From c80ee319e21eefc816d34b956cc26ec86bec9f62 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sun, 30 Jan 2022 12:13:50 -0700 Subject: [PATCH] bidi: add helper for using Direction with Iterator --- bidi/src/direction.rs | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/bidi/src/direction.rs b/bidi/src/direction.rs index 1c8bdb05a..1379c4589 100644 --- a/bidi/src/direction.rs +++ b/bidi/src/direction.rs @@ -29,4 +29,36 @@ impl Direction { Self::LeftToRight => BidiClass::LeftToRight, } } + + /// Given a DoubleEndedIterator, returns an iterator that will + /// either walk it in its natural order if Direction==LeftToRight, + /// or in reverse order if Direction==RightToLeft + pub fn iter, T>(self, iter: I) -> DirectionIter { + DirectionIter::wrap(iter, self) + } +} + +pub enum DirectionIter, T> { + LTR(I), + RTL(std::iter::Rev), +} + +impl, T> DirectionIter { + pub fn wrap(iter: I, direction: Direction) -> Self { + match direction { + Direction::LeftToRight => Self::LTR(iter), + Direction::RightToLeft => Self::RTL(iter.rev()), + } + } +} + +impl, T> Iterator for DirectionIter { + type Item = I::Item; + + fn next(&mut self) -> Option { + match self { + Self::LTR(i) => i.next(), + Self::RTL(i) => i.next(), + } + } }