1/*2 * Licensed to the Apache Software Foundation (ASF) under one3 * or more contributor license agreements. See the NOTICE file4 * distributed with this work for additional information5 * regarding copyright ownership. The ASF licenses this file6 * to you under the Apache License, Version 2.0 (the7 * "License"); you may not use this file except in compliance8 * with the License. You may obtain a copy of the License at9 *10 * http://www.apache.org/licenses/LICENSE-2.011 *12 * Unless required by applicable law or agreed to in writing, software13 * distributed under the License is distributed on an "AS IS" BASIS,14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15 * See the License for the specific language governing permissions and16 * limitations under the License.17 */18package org.apache.giraph.block_app.framework.block;
1920import java.util.Iterator;
2122import org.apache.giraph.block_app.framework.piece.AbstractPiece;
23import org.apache.giraph.function.Consumer;
24import org.apache.giraph.function.Supplier;
2526import com.google.common.collect.AbstractIterator;
27import com.google.common.collect.Iterators;
2829/**30 * Block that repeats another block until toQuit supplier returns true,31 * but at most given number of times.32 *33 * If toQuit returns true on first run, block is not going34 * to be executed at all.35 */36 @SuppressWarnings("rawtypes")
37publicfinalclassRepeatUntilBlockimplementsBlock {
38privatefinalBlock block;
39privatefinalint repeatTimes;
40privatefinal Supplier<Boolean> toQuit;
4142publicRepeatUntilBlock(
43int repeatTimes, Block block, Supplier<Boolean> toQuit) {
44this.block = block;
45this.repeatTimes = repeatTimes;
46this.toQuit = toQuit;
47 }
4849/**50 * Repeat unlimited number of times, until toQuit supplier returns true.51 */52publicstaticBlock unlimited(Block block, Supplier<Boolean> toQuit) {
53returnnewRepeatUntilBlock(Integer.MAX_VALUE, block, toQuit);
54 }
5556 @Override
57public Iterator<AbstractPiece> iterator() {
58return Iterators.concat(new AbstractIterator<Iterator<AbstractPiece>>() {
59privateint index = 0;
6061 @Override
62protected Iterator<AbstractPiece> computeNext() {
63if (index >= repeatTimes || Boolean.TRUE.equals(toQuit.get())) {
64return endOfData();
65 }
66 index++;
67return block.iterator();
68 }
69 });
70 }
7172 @Override
73publicvoid forAllPossiblePieces(Consumer<AbstractPiece> consumer) {
74 block.forAllPossiblePieces(consumer);
75 }
7677 @Override
78publicPieceCount getPieceCount() {
79return PieceCount.createUnknownCount();
80 }
8182 @Override
83public String toString() {
84return"RepeatUntilBlock(" + repeatTimes + " * " + block + ")";
85 }
86 }