// 
// Decompiled by Procyon v0.6.0
// 

package io.netty.util.internal;

import java.io.IOException;
import org.jetbrains.annotations.NotNull;
import java.io.InputStream;
import java.io.FilterInputStream;

public final class BoundedInputStream extends FilterInputStream
{
    private final int maxBytesRead;
    private int numRead;
    
    public BoundedInputStream(@NotNull final InputStream in, final int maxBytesRead) {
        super(in);
        this.maxBytesRead = ObjectUtil.checkPositive(maxBytesRead, "maxRead");
    }
    
    public BoundedInputStream(@NotNull final InputStream in) {
        this(in, 8192);
    }
    
    @Override
    public int read() throws IOException {
        this.checkMaxBytesRead();
        final int b = super.read();
        if (b != -1) {
            ++this.numRead;
        }
        return b;
    }
    
    @Override
    public int read(final byte[] buf, final int off, final int len) throws IOException {
        this.checkMaxBytesRead();
        final int num = Math.min(len, this.maxBytesRead - this.numRead + 1);
        final int b = super.read(buf, off, num);
        if (b != -1) {
            this.numRead += b;
        }
        return b;
    }
    
    private void checkMaxBytesRead() throws IOException {
        if (this.numRead > this.maxBytesRead) {
            throw new IOException("Maximum number of bytes read: " + this.numRead);
        }
    }
}
