package com.apobates.forum.utils.lang.stream;

import java.util.Spliterator;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.function.Consumer;

/**
 *
 * @author xiaofanku
 */
public class LinkedBlockingQueueSpliterator<T> implements Spliterator<T> {
    private final LinkedBlockingQueue<T> q;
    private boolean finished;
    
    LinkedBlockingQueueSpliterator(LinkedBlockingQueue<T> q) {
        this.q = q;
    }
    
    @Override
    public boolean tryAdvance(Consumer<? super T> action) {
        if (!finished) {
            T t;
            while (true) {
                try {
                    t = q.take();
                    break;
                } catch (InterruptedException e) {
                }
            }
            
            if (t != ForkingStreamConsumer.SENTINAL) {
                action.accept(t);
                return true;
            }
            
            finished = true;
        }
        return false;
    }
    
    @Override
    public Spliterator<T> trySplit() {
        // @@@ Support limited splitting, using buffering with say
        // q.drainTo
        return null;
    }
    
    @Override
    public long estimateSize() {
        // @@@ Support size if known by forking stream
        return 0;
    }
    
    @Override
    public int characteristics() {
        // @@@ Inherit characters from forking stream
        return 0;
    }
}