/*
 * Copyright (c) 2004-2017, by Alex Leigh.
 * All rights reserved.
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE
 * The copyright notice above does not evidence any
 * actual or intended publication of such source code.
 */

package lc.mecha.nio;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

public class ByteBufferInputStream extends InputStream {
    protected final ByteBuffer _b;

    public ByteBufferInputStream(final ByteBuffer buf) {
        _b = buf;
    }

    @Override
    public int available() {
        return _b.remaining();
    }

    @Override
    public int read() throws IOException {
        return _b.hasRemaining() ? (_b.get() & 0xFF) : -1;
    }

    @Override
    public int read(final byte[] bytes, final int off, int len) throws IOException {
        if (!_b.hasRemaining()) return -1;
        len = Math.min(len, _b.remaining());
        _b.get(bytes, off, len);
        return len;
    }
}