/*
 * cc.redberry.pipe: java library for implementation of concurrent pipelines
 * Copyright (c) 2010-2012
 * Bolotin Dmitriy <bolotin.dmitriy@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package cc.redberry.pipe.util;

import cc.redberry.pipe.InputPort;
import cc.redberry.pipe.OutputPort;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Concurrent unlimited objects buffer based on ConcurrentLinkedQueue.<br/> It is a simple wrapper for
 * ConcurrentLinkedQueue.<br/> For normal functioning all objects must be putted before first object can be taken.
 *
 * @param <T>
 * @author Bolotin Dmitriy (bolotin.dmitriy@gmail.com)
 */
public final class InputPortBuffer<T> implements InputPort<T>, OutputPort<T> {
    private final AtomicInteger elements = new AtomicInteger();
    private final Queue<T> queue;

    public InputPortBuffer() {
        queue = new ConcurrentLinkedQueue<>();
    }

    @Override
    public void put(T object) {
        if (object == null) //Do nothing on close
            return;
        elements.incrementAndGet();
        queue.add(object);
    }

    @Override
    public T take() {
        T element;
        if ((element = queue.poll()) != null)
            elements.decrementAndGet();
        return element;
    }

    public int size() {
        return elements.get();
    }
}
