package com.google.firebase.crashlytics.internal.metadata;

import Z0.o;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.util.NoSuchElementException;
import java.util.logging.Level;
import java.util.logging.Logger;

/* JADX INFO: loaded from: classes3.dex */
class QueueFile implements Closeable {
    static final int HEADER_LENGTH = 16;
    private static final int INITIAL_LENGTH = 4096;
    private static final Logger LOGGER = Logger.getLogger(QueueFile.class.getName());
    private final byte[] buffer;
    private int elementCount;
    int fileLength;
    private Element first;
    private Element last;
    private final RandomAccessFile raf;

    public static class Element {
        static final int HEADER_LENGTH = 4;
        static final Element NULL = new Element(0, 0);
        final int length;
        final int position;

        public Element(int i6, int i7) {
            this.position = i6;
            this.length = i7;
        }

        public String toString() {
            StringBuilder sb = new StringBuilder();
            sb.append(getClass().getSimpleName());
            sb.append("[position = ");
            sb.append(this.position);
            sb.append(", length = ");
            return o.q(sb, this.length, "]");
        }
    }

    public final class ElementInputStream extends InputStream {
        private int position;
        private int remaining;

        @Override // java.io.InputStream
        public int read(byte[] bArr, int i6, int i7) throws IOException {
            QueueFile.nonNull(bArr, "buffer");
            if ((i6 | i7) < 0 || i7 > bArr.length - i6) {
                throw new ArrayIndexOutOfBoundsException();
            }
            int i8 = this.remaining;
            if (i8 <= 0) {
                return -1;
            }
            if (i7 > i8) {
                i7 = i8;
            }
            QueueFile.this.ringRead(this.position, bArr, i6, i7);
            this.position = QueueFile.this.wrapPosition(this.position + i7);
            this.remaining -= i7;
            return i7;
        }

        private ElementInputStream(Element element) {
            this.position = QueueFile.this.wrapPosition(element.position + 4);
            this.remaining = element.length;
        }

        @Override // java.io.InputStream
        public int read() throws IOException {
            if (this.remaining == 0) {
                return -1;
            }
            QueueFile.this.raf.seek(this.position);
            int i6 = QueueFile.this.raf.read();
            this.position = QueueFile.this.wrapPosition(this.position + 1);
            this.remaining--;
            return i6;
        }
    }

    public interface ElementReader {
        void read(InputStream inputStream, int i6);
    }

    public QueueFile(File file) throws IOException {
        this.buffer = new byte[16];
        if (!file.exists()) {
            initialize(file);
        }
        this.raf = open(file);
        readHeader();
    }

    private void expandIfNecessary(int i6) throws IOException {
        int i7 = i6 + 4;
        int iRemainingBytes = remainingBytes();
        if (iRemainingBytes >= i7) {
            return;
        }
        int i8 = this.fileLength;
        do {
            iRemainingBytes += i8;
            i8 <<= 1;
        } while (iRemainingBytes < i7);
        setLength(i8);
        Element element = this.last;
        int iWrapPosition = wrapPosition(element.position + 4 + element.length);
        if (iWrapPosition < this.first.position) {
            FileChannel channel = this.raf.getChannel();
            channel.position(this.fileLength);
            long j4 = iWrapPosition - 4;
            if (channel.transferTo(16L, j4, channel) != j4) {
                throw new AssertionError("Copied insufficient number of bytes!");
            }
        }
        int i9 = this.last.position;
        int i10 = this.first.position;
        if (i9 < i10) {
            int i11 = (this.fileLength + i9) - 16;
            writeHeader(i8, this.elementCount, i10, i11);
            this.last = new Element(i11, this.last.length);
        } else {
            writeHeader(i8, this.elementCount, i10, i9);
        }
        this.fileLength = i8;
    }

    private static void initialize(File file) throws IOException {
        File file2 = new File(file.getPath() + ".tmp");
        RandomAccessFile randomAccessFileOpen = open(file2);
        try {
            randomAccessFileOpen.setLength(4096L);
            randomAccessFileOpen.seek(0L);
            byte[] bArr = new byte[16];
            writeInts(bArr, 4096, 0, 0, 0);
            randomAccessFileOpen.write(bArr);
            randomAccessFileOpen.close();
            if (!file2.renameTo(file)) {
                throw new IOException("Rename failed!");
            }
        } catch (Throwable th) {
            randomAccessFileOpen.close();
            throw th;
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static <T> T nonNull(T t6, String str) {
        if (t6 != null) {
            return t6;
        }
        throw new NullPointerException(str);
    }

    private static RandomAccessFile open(File file) {
        return new RandomAccessFile(file, "rwd");
    }

    private Element readElement(int i6) throws IOException {
        if (i6 == 0) {
            return Element.NULL;
        }
        this.raf.seek(i6);
        return new Element(i6, this.raf.readInt());
    }

    private void readHeader() throws IOException {
        this.raf.seek(0L);
        this.raf.readFully(this.buffer);
        int i6 = readInt(this.buffer, 0);
        this.fileLength = i6;
        if (i6 > this.raf.length()) {
            throw new IOException("File is truncated. Expected length: " + this.fileLength + ", Actual length: " + this.raf.length());
        }
        this.elementCount = readInt(this.buffer, 4);
        int i7 = readInt(this.buffer, 8);
        int i8 = readInt(this.buffer, 12);
        this.first = readElement(i7);
        this.last = readElement(i8);
    }

    private static int readInt(byte[] bArr, int i6) {
        return ((bArr[i6] & 255) << 24) + ((bArr[i6 + 1] & 255) << 16) + ((bArr[i6 + 2] & 255) << 8) + (bArr[i6 + 3] & 255);
    }

    private int remainingBytes() {
        return this.fileLength - usedBytes();
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void ringRead(int i6, byte[] bArr, int i7, int i8) throws IOException {
        int iWrapPosition = wrapPosition(i6);
        int i9 = iWrapPosition + i8;
        int i10 = this.fileLength;
        if (i9 <= i10) {
            this.raf.seek(iWrapPosition);
            this.raf.readFully(bArr, i7, i8);
            return;
        }
        int i11 = i10 - iWrapPosition;
        this.raf.seek(iWrapPosition);
        this.raf.readFully(bArr, i7, i11);
        this.raf.seek(16L);
        this.raf.readFully(bArr, i7 + i11, i8 - i11);
    }

    private void ringWrite(int i6, byte[] bArr, int i7, int i8) throws IOException {
        int iWrapPosition = wrapPosition(i6);
        int i9 = iWrapPosition + i8;
        int i10 = this.fileLength;
        if (i9 <= i10) {
            this.raf.seek(iWrapPosition);
            this.raf.write(bArr, i7, i8);
            return;
        }
        int i11 = i10 - iWrapPosition;
        this.raf.seek(iWrapPosition);
        this.raf.write(bArr, i7, i11);
        this.raf.seek(16L);
        this.raf.write(bArr, i7 + i11, i8 - i11);
    }

    private void setLength(int i6) throws IOException {
        this.raf.setLength(i6);
        this.raf.getChannel().force(true);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public int wrapPosition(int i6) {
        int i7 = this.fileLength;
        return i6 < i7 ? i6 : (i6 + 16) - i7;
    }

    private void writeHeader(int i6, int i7, int i8, int i9) throws IOException {
        writeInts(this.buffer, i6, i7, i8, i9);
        this.raf.seek(0L);
        this.raf.write(this.buffer);
    }

    private static void writeInt(byte[] bArr, int i6, int i7) {
        bArr[i6] = (byte) (i7 >> 24);
        bArr[i6 + 1] = (byte) (i7 >> 16);
        bArr[i6 + 2] = (byte) (i7 >> 8);
        bArr[i6 + 3] = (byte) i7;
    }

    private static void writeInts(byte[] bArr, int... iArr) {
        int i6 = 0;
        for (int i7 : iArr) {
            writeInt(bArr, i6, i7);
            i6 += 4;
        }
    }

    public void add(byte[] bArr) {
        add(bArr, 0, bArr.length);
    }

    public synchronized void clear() {
        try {
            writeHeader(4096, 0, 0, 0);
            this.elementCount = 0;
            Element element = Element.NULL;
            this.first = element;
            this.last = element;
            if (this.fileLength > 4096) {
                setLength(4096);
            }
            this.fileLength = 4096;
        } catch (Throwable th) {
            throw th;
        }
    }

    @Override // java.io.Closeable, java.lang.AutoCloseable
    public synchronized void close() {
        this.raf.close();
    }

    public synchronized void forEach(ElementReader elementReader) {
        int iWrapPosition = this.first.position;
        for (int i6 = 0; i6 < this.elementCount; i6++) {
            Element element = readElement(iWrapPosition);
            elementReader.read(new ElementInputStream(element), element.length);
            iWrapPosition = wrapPosition(element.position + 4 + element.length);
        }
    }

    public boolean hasSpaceFor(int i6, int i7) {
        return (usedBytes() + 4) + i6 <= i7;
    }

    public synchronized boolean isEmpty() {
        return this.elementCount == 0;
    }

    public synchronized byte[] peek() {
        if (isEmpty()) {
            return null;
        }
        Element element = this.first;
        int i6 = element.length;
        byte[] bArr = new byte[i6];
        ringRead(element.position + 4, bArr, 0, i6);
        return bArr;
    }

    public synchronized void remove() {
        try {
            if (isEmpty()) {
                throw new NoSuchElementException();
            }
            if (this.elementCount == 1) {
                clear();
            } else {
                Element element = this.first;
                int iWrapPosition = wrapPosition(element.position + 4 + element.length);
                ringRead(iWrapPosition, this.buffer, 0, 4);
                int i6 = readInt(this.buffer, 0);
                writeHeader(this.fileLength, this.elementCount - 1, iWrapPosition, this.last.position);
                this.elementCount--;
                this.first = new Element(iWrapPosition, i6);
            }
        } catch (Throwable th) {
            throw th;
        }
    }

    public synchronized int size() {
        return this.elementCount;
    }

    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append("[fileLength=");
        sb.append(this.fileLength);
        sb.append(", size=");
        sb.append(this.elementCount);
        sb.append(", first=");
        sb.append(this.first);
        sb.append(", last=");
        sb.append(this.last);
        sb.append(", element lengths=[");
        try {
            forEach(new ElementReader() { // from class: com.google.firebase.crashlytics.internal.metadata.QueueFile.1
                boolean first = true;

                @Override // com.google.firebase.crashlytics.internal.metadata.QueueFile.ElementReader
                public void read(InputStream inputStream, int i6) {
                    if (this.first) {
                        this.first = false;
                    } else {
                        sb.append(", ");
                    }
                    sb.append(i6);
                }
            });
        } catch (IOException e6) {
            LOGGER.log(Level.WARNING, "read error", (Throwable) e6);
        }
        sb.append("]]");
        return sb.toString();
    }

    public int usedBytes() {
        if (this.elementCount == 0) {
            return 16;
        }
        Element element = this.last;
        int i6 = element.position;
        int i7 = this.first.position;
        return i6 >= i7 ? (i6 - i7) + 4 + element.length + 16 : (((i6 + 4) + element.length) + this.fileLength) - i7;
    }

    public synchronized void add(byte[] bArr, int i6, int i7) {
        int iWrapPosition;
        try {
            nonNull(bArr, "buffer");
            if ((i6 | i7) < 0 || i7 > bArr.length - i6) {
                throw new IndexOutOfBoundsException();
            }
            expandIfNecessary(i7);
            boolean zIsEmpty = isEmpty();
            if (zIsEmpty) {
                iWrapPosition = 16;
            } else {
                Element element = this.last;
                iWrapPosition = wrapPosition(element.position + 4 + element.length);
            }
            Element element2 = new Element(iWrapPosition, i7);
            writeInt(this.buffer, 0, i7);
            ringWrite(element2.position, this.buffer, 0, 4);
            ringWrite(element2.position + 4, bArr, i6, i7);
            writeHeader(this.fileLength, this.elementCount + 1, zIsEmpty ? element2.position : this.first.position, element2.position);
            this.last = element2;
            this.elementCount++;
            if (zIsEmpty) {
                this.first = element2;
            }
        } catch (Throwable th) {
            throw th;
        }
    }

    public QueueFile(RandomAccessFile randomAccessFile) throws IOException {
        this.buffer = new byte[16];
        this.raf = randomAccessFile;
        readHeader();
    }

    public synchronized void peek(ElementReader elementReader) {
        if (this.elementCount > 0) {
            elementReader.read(new ElementInputStream(this.first), this.first.length);
        }
    }
}
