001/*
002 * Copyright (c) 2016-2017 Chris K Wensel <chris@wensel.net>. All Rights Reserved.
003 * Copyright (c) 2007-2017 Xplenty, Inc. All Rights Reserved.
004 *
005 * Project and contact information: http://www.cascading.org/
006 *
007 * This file is part of the Cascading project.
008 *
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 *
013 *     http://www.apache.org/licenses/LICENSE-2.0
014 *
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 */
021
022package cascading.tuple;
023
024import java.util.Iterator;
025
026import cascading.tuple.util.Resettable;
027
028/**
029 * TupleChainIterator chains the given Iterators into a single Iterator.
030 * <p>
031 * As one iterator is completed, it will be closed and a new one will start.
032 */
033public class TupleChainIterable implements Iterable<Tuple>, Resettable<Iterable<Tuple>>
034  {
035  /** Field iterator */
036  Iterable<Tuple>[] iterables;
037
038  public TupleChainIterable( Iterable<Tuple> first, Iterable<Tuple>... iterables )
039    {
040    Iterable<Tuple>[] initial;
041
042    if( first instanceof TupleChainIterable )
043      initial = ( (TupleChainIterable) first ).iterables;
044    else
045      initial = new Iterable[]{first};
046
047    this.iterables = new Iterable[ initial.length + iterables.length ];
048
049    System.arraycopy( initial, 0, this.iterables, 0, initial.length );
050    System.arraycopy( iterables, 0, this.iterables, initial.length, iterables.length );
051    }
052
053  @Override
054  public Iterator<Tuple> iterator()
055    {
056    Iterator<Tuple>[] iterators = new Iterator[ iterables.length ];
057
058    for( int i = 0; i < iterables.length; i++ )
059      iterators[ i ] = iterables[ i ].iterator();
060
061    return new TupleChainIterator( iterators );
062    }
063
064  @Override
065  public void reset( Iterable<Tuple>... iterables )
066    {
067    this.iterables = iterables;
068    }
069  }