CharSpliterator.java

/*
 * Copyright (c) 2020, Stein Eldar Johnsen
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package net.morimekta.strings.chr;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.UncheckedIOException;
import java.util.Spliterator;
import java.util.function.Consumer;

class CharSpliterator implements Spliterator<Char> {
    private final Reader     in;
    private final CharReader reader;
    private final boolean    lenient;

    CharSpliterator(CharSequence string, boolean lenient) {
        this.in = new StringReader(string.toString());
        this.reader = new CharReader(in);
        this.lenient = lenient;
    }

    @Override
    public boolean tryAdvance(Consumer<? super Char> consumer) {
        try {
            if (lenient) {
                in.mark(10);
            }
            Char c = reader.read();
            if (c != null) {
                consumer.accept(c);
                return true;
            }
            return false;
        } catch (IOException e) {
            if (lenient) {
                try {
                    in.reset();
                    if (in.skip(1) > 0) {
                        consumer.accept(new Unicode(Char.ESC));
                        return true;
                    }
                } catch (IOException e2) {
                    e.addSuppressed(e2);
                }
            }
            throw new UncheckedIOException(e);
        }
    }

    @Override
    public Spliterator<Char> trySplit() {
        return null;
    }

    @Override
    public long estimateSize() {
        return 0;
    }

    @Override
    public int characteristics() {
        return Spliterator.ORDERED | Spliterator.NONNULL | Spliterator.IMMUTABLE;
    }
}