package com.flurry.org.apache.avro.util;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.LinkedList;
import java.util.List;

/* loaded from: /storage/emulated/0/Documents/jadec/sources/com.UBI.A90.WW/dex-files/0.dex */
public class ByteBufferOutputStream extends OutputStream {
    public static final int BUFFER_SIZE = 8192;
    private List<ByteBuffer> buffers;

    public ByteBufferOutputStream() {
        reset();
    }

    public List<ByteBuffer> getBufferList() {
        List<ByteBuffer> result = this.buffers;
        reset();
        for (ByteBuffer buffer : result) {
            buffer.flip();
        }
        return result;
    }

    public void prepend(List<ByteBuffer> lists) {
        for (ByteBuffer buffer : lists) {
            buffer.position(buffer.limit());
        }
        this.buffers.addAll(0, lists);
    }

    public void append(List<ByteBuffer> lists) {
        for (ByteBuffer buffer : lists) {
            buffer.position(buffer.limit());
        }
        this.buffers.addAll(lists);
    }

    public void reset() {
        this.buffers = new LinkedList();
        this.buffers.add(ByteBuffer.allocate(BUFFER_SIZE));
    }

    public void write(ByteBuffer buffer) {
        this.buffers.add(buffer);
    }

    @Override // java.io.OutputStream
    public void write(int b) {
        ByteBuffer buffer = this.buffers.get(this.buffers.size() - 1);
        if (buffer.remaining() < 1) {
            buffer = ByteBuffer.allocate(BUFFER_SIZE);
            this.buffers.add(buffer);
        }
        buffer.put((byte) b);
    }

    @Override // java.io.OutputStream
    public void write(byte[] b, int off, int len) {
        ByteBuffer buffer = this.buffers.get(this.buffers.size() - 1);
        int remaining = buffer.remaining();
        while (len > remaining) {
            buffer.put(b, off, remaining);
            len -= remaining;
            off += remaining;
            buffer = ByteBuffer.allocate(BUFFER_SIZE);
            this.buffers.add(buffer);
            remaining = buffer.remaining();
        }
        buffer.put(b, off, len);
    }

    public void writeBuffer(ByteBuffer buffer) throws IOException {
        if (buffer.remaining() < 8192) {
            write(buffer.array(), buffer.position(), buffer.remaining());
            return;
        }
        ByteBuffer dup = buffer.duplicate();
        dup.position(buffer.limit());
        this.buffers.add(dup);
    }
}
