package io.netty.handler.stream;

import g.a.a.a.a;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.util.Objects;

/* JADX INFO: loaded from: classes.dex */
public class ChunkedStream implements ChunkedInput<ByteBuf> {
    public static final int DEFAULT_CHUNK_SIZE = 8192;
    private final int chunkSize;
    private boolean closed;
    private final PushbackInputStream in;
    private long offset;

    public ChunkedStream(InputStream inputStream) {
        this(inputStream, 8192);
    }

    public ChunkedStream(InputStream inputStream, int i2) {
        Objects.requireNonNull(inputStream, "in");
        if (i2 <= 0) {
            throw new IllegalArgumentException(a.n("chunkSize: ", i2, " (expected: a positive integer)"));
        }
        if (inputStream instanceof PushbackInputStream) {
            this.in = (PushbackInputStream) inputStream;
        } else {
            this.in = new PushbackInputStream(inputStream);
        }
        this.chunkSize = i2;
    }

    @Override // io.netty.handler.stream.ChunkedInput
    public void close() throws IOException {
        this.closed = true;
        this.in.close();
    }

    @Override // io.netty.handler.stream.ChunkedInput
    public boolean isEndOfInput() throws IOException {
        int i2;
        if (this.closed || (i2 = this.in.read()) < 0) {
            return true;
        }
        this.in.unread(i2);
        return false;
    }

    @Override // io.netty.handler.stream.ChunkedInput
    public long length() {
        return -1L;
    }

    @Override // io.netty.handler.stream.ChunkedInput
    public long progress() {
        return this.offset;
    }

    /* JADX WARN: Can't rename method to resolve collision */
    @Override // io.netty.handler.stream.ChunkedInput
    public ByteBuf readChunk(ByteBufAllocator byteBufAllocator) {
        if (isEndOfInput()) {
            return null;
        }
        int iMin = this.in.available() <= 0 ? this.chunkSize : Math.min(this.chunkSize, this.in.available());
        ByteBuf byteBufBuffer = byteBufAllocator.buffer(iMin);
        try {
            this.offset += (long) byteBufBuffer.writeBytes(this.in, iMin);
            return byteBufBuffer;
        } catch (Throwable th) {
            byteBufBuffer.release();
            throw th;
        }
    }

    /* JADX WARN: Can't rename method to resolve collision */
    @Override // io.netty.handler.stream.ChunkedInput
    @Deprecated
    public ByteBuf readChunk(ChannelHandlerContext channelHandlerContext) {
        return readChunk(channelHandlerContext.alloc());
    }

    public long transferredBytes() {
        return this.offset;
    }
}
