001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      https://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.apache.commons.io.function;
019
020import java.io.IOException;
021import java.io.UncheckedIOException;
022import java.util.Objects;
023
024/**
025 * Like {@link Iterable} but throws {@link IOException}.
026 *
027 * @param <T> the type of elements returned by the iterable.
028 * @since 2.19.0
029 */
030public interface IOIterable<T> {
031
032    /**
033     * Creates an {@link Iterable} for this instance that throws {@link UncheckedIOException} instead of
034     * {@link IOException}.
035     *
036     * @return an {@link UncheckedIOException} {@link Iterable}.
037     * @since 2.21.0
038     */
039    default Iterable<T> asIterable() {
040        return new UncheckedIOIterable<>(this);
041    }
042
043    /**
044     * Like {@link Iterable#iterator()}.
045     *
046     * @param action The action to be performed for each element.
047     * @throws NullPointerException if the specified action is null.
048     * @throws IOException thrown by the given action.
049     * @see Iterable#iterator()
050     */
051    default void forEach(final IOConsumer<? super T> action) throws IOException {
052        iterator().forEachRemaining(Objects.requireNonNull(action));
053    }
054
055    /**
056     * Like {@link Iterable#iterator()}.
057     *
058     * @return See {@link Iterable#iterator() delegate}.
059     * @see Iterable#iterator()
060     */
061    IOIterator<T> iterator();
062
063    /**
064     * Like {@link Iterable#spliterator()}.
065     *
066     * @return See {@link Iterable#spliterator() delegate}.
067     * @see Iterable#spliterator()
068     */
069    default IOSpliterator<T> spliterator() {
070        return IOSpliteratorAdapter.adapt(new UncheckedIOIterable<>(this).spliterator());
071    }
072
073    /**
074     * Unwraps this instance and returns the underlying {@link Iterable}.
075     * <p>
076     * Implementations may not have anything to unwrap and that behavior is undefined for now.
077     * </p>
078     * @return the underlying Iterable.
079     */
080    Iterable<T> unwrap();
081
082}