From bc06840e00425db342bc5a021c0900d9e63b71f0 Mon Sep 17 00:00:00 2001 From: Michael Williamson Date: Fri, 15 Jul 2016 14:23:47 +0100 Subject: Split switch handling off to desugar step --- .../org/zwobble/couscous/util/ExtraIterables.java | 39 ++++++++++++++++++++++ 1 file changed, 39 insertions(+) (limited to 'src/main/java/org/zwobble/couscous/util/ExtraIterables.java') diff --git a/src/main/java/org/zwobble/couscous/util/ExtraIterables.java b/src/main/java/org/zwobble/couscous/util/ExtraIterables.java index 1140462..3881d29 100644 --- a/src/main/java/org/zwobble/couscous/util/ExtraIterables.java +++ b/src/main/java/org/zwobble/couscous/util/ExtraIterables.java @@ -2,8 +2,11 @@ package org.zwobble.couscous.util; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; +import com.google.common.collect.Iterators; +import com.google.common.collect.PeekingIterator; import java.util.Iterator; +import java.util.NoSuchElementException; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.Function; @@ -162,4 +165,40 @@ public class ExtraIterables { public static Iterable of(T e1, T e2, T e3) { return ImmutableList.of(e1, e2, e3); } + + public static Iterable iterable(Optional optional) { + if (optional.isPresent()) { + return of(optional.get()); + } else { + return empty(); + } + } + + public static Iterable takeUntil(Iterable iterable, Predicate predicate) { + return new Iterable() { + @Override + public Iterator iterator() { + return takeUntil(iterable.iterator(), predicate); + } + }; + } + + public static Iterator takeUntil(Iterator iterator, Predicate predicate) { + PeekingIterator peekingIterator = Iterators.peekingIterator(iterator); + return new Iterator() { + @Override + public boolean hasNext() { + return peekingIterator.hasNext() && !predicate.test(peekingIterator.peek()); + } + + @Override + public T next() { + if (hasNext()) { + return peekingIterator.next(); + } else { + throw new NoSuchElementException(); + } + } + }; + } } -- cgit v1.2.3