package io.netty.buffer;

import g.a.a.a.a;
import io.netty.handler.codec.dns.DnsRecord;
import io.netty.handler.codec.memcache.binary.BinaryMemcacheOpcodes;
import io.netty.handler.codec.memcache.binary.DefaultBinaryMemcacheRequest;
import io.netty.util.AsciiString;
import io.netty.util.ByteProcessor;
import io.netty.util.CharsetUtil;
import io.netty.util.Recycler;
import io.netty.util.concurrent.FastThreadLocal;
import io.netty.util.internal.MathUtil;
import io.netty.util.internal.ObjectUtil;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.StringUtil;
import io.netty.util.internal.SystemPropertyUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import java.util.Arrays;
import java.util.Locale;

/* JADX INFO: loaded from: classes.dex */
public final class ByteBufUtil {
    private static final FastThreadLocal<CharBuffer> CHAR_BUFFERS;
    public static final ByteBufAllocator DEFAULT_ALLOCATOR;
    private static final ByteProcessor FIND_NON_ASCII;
    private static final int MAX_BYTES_PER_CHAR_UTF8;
    private static final int MAX_CHAR_BUFFER_SIZE;
    private static final int THREAD_LOCAL_BUFFER_SIZE;
    public static final int WRITE_CHUNK_SIZE = 8192;
    private static final byte WRITE_UTF_UNKNOWN = 63;
    private static final InternalLogger logger;

    public static final class HexUtil {
        private static final char[] BYTE2CHAR = new char[256];
        private static final char[] HEXDUMP_TABLE = new char[1024];
        private static final String[] HEXPADDING = new String[16];
        private static final String[] HEXDUMP_ROWPREFIXES = new String[4096];
        private static final String[] BYTE2HEX = new String[256];
        private static final String[] BYTEPADDING = new String[16];

        static {
            char[] charArray = "0123456789abcdef".toCharArray();
            int i2 = 0;
            for (int i3 = 0; i3 < 256; i3++) {
                char[] cArr = HEXDUMP_TABLE;
                int i4 = i3 << 1;
                cArr[i4] = charArray[(i3 >>> 4) & 15];
                cArr[i4 + 1] = charArray[i3 & 15];
            }
            int i5 = 0;
            while (true) {
                String[] strArr = HEXPADDING;
                if (i5 >= strArr.length) {
                    break;
                }
                int length = strArr.length - i5;
                StringBuilder sb = new StringBuilder(length * 3);
                for (int i6 = 0; i6 < length; i6++) {
                    sb.append("   ");
                }
                HEXPADDING[i5] = sb.toString();
                i5++;
            }
            int i7 = 0;
            while (true) {
                String[] strArr2 = HEXDUMP_ROWPREFIXES;
                if (i7 >= strArr2.length) {
                    break;
                }
                StringBuilder sb2 = new StringBuilder(12);
                sb2.append(StringUtil.NEWLINE);
                sb2.append(Long.toHexString((((long) (i7 << 4)) & 4294967295L) | 4294967296L));
                sb2.setCharAt(sb2.length() - 9, '|');
                sb2.append('|');
                strArr2[i7] = sb2.toString();
                i7++;
            }
            int i8 = 0;
            while (true) {
                String[] strArr3 = BYTE2HEX;
                if (i8 >= strArr3.length) {
                    break;
                }
                StringBuilder sbE = a.E(' ');
                sbE.append(StringUtil.byteToHexStringPadded(i8));
                strArr3[i8] = sbE.toString();
                i8++;
            }
            int i9 = 0;
            while (true) {
                String[] strArr4 = BYTEPADDING;
                if (i9 >= strArr4.length) {
                    break;
                }
                int length2 = strArr4.length - i9;
                StringBuilder sb3 = new StringBuilder(length2);
                for (int i10 = 0; i10 < length2; i10++) {
                    sb3.append(' ');
                }
                BYTEPADDING[i9] = sb3.toString();
                i9++;
            }
            while (true) {
                char[] cArr2 = BYTE2CHAR;
                if (i2 >= cArr2.length) {
                    return;
                }
                if (i2 <= 31 || i2 >= 127) {
                    cArr2[i2] = '.';
                } else {
                    cArr2[i2] = (char) i2;
                }
                i2++;
            }
        }

        private HexUtil() {
        }

        private static void appendHexDumpRowPrefix(StringBuilder sb, int i2, int i3) {
            String[] strArr = HEXDUMP_ROWPREFIXES;
            if (i2 < strArr.length) {
                sb.append(strArr[i2]);
                return;
            }
            sb.append(StringUtil.NEWLINE);
            sb.append(Long.toHexString((((long) i3) & 4294967295L) | 4294967296L));
            sb.setCharAt(sb.length() - 9, '|');
            sb.append('|');
        }

        /* JADX INFO: Access modifiers changed from: private */
        public static void appendPrettyHexDump(StringBuilder sb, ByteBuf byteBuf, int i2, int i3) {
            if (MathUtil.isOutOfBounds(i2, i3, byteBuf.capacity())) {
                StringBuilder sbI = a.I("expected: 0 <= offset(", i2, ") <= offset + length(", i3, ") <= buf.capacity(");
                sbI.append(byteBuf.capacity());
                sbI.append(')');
                throw new IndexOutOfBoundsException(sbI.toString());
            }
            if (i3 == 0) {
                return;
            }
            StringBuilder sbF = a.F("         +-------------------------------------------------+");
            String str = StringUtil.NEWLINE;
            sbF.append(str);
            sbF.append("         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |");
            sbF.append(str);
            sbF.append("+--------+-------------------------------------------------+----------------+");
            sb.append(sbF.toString());
            int i4 = i3 >>> 4;
            int i5 = i3 & 15;
            for (int i6 = 0; i6 < i4; i6++) {
                int i7 = (i6 << 4) + i2;
                appendHexDumpRowPrefix(sb, i6, i7);
                int i8 = i7 + 16;
                for (int i9 = i7; i9 < i8; i9++) {
                    sb.append(BYTE2HEX[byteBuf.getUnsignedByte(i9)]);
                }
                sb.append(" |");
                while (i7 < i8) {
                    sb.append(BYTE2CHAR[byteBuf.getUnsignedByte(i7)]);
                    i7++;
                }
                sb.append('|');
            }
            if (i5 != 0) {
                int i10 = (i4 << 4) + i2;
                appendHexDumpRowPrefix(sb, i4, i10);
                int i11 = i10 + i5;
                for (int i12 = i10; i12 < i11; i12++) {
                    sb.append(BYTE2HEX[byteBuf.getUnsignedByte(i12)]);
                }
                sb.append(HEXPADDING[i5]);
                sb.append(" |");
                while (i10 < i11) {
                    sb.append(BYTE2CHAR[byteBuf.getUnsignedByte(i10)]);
                    i10++;
                }
                sb.append(BYTEPADDING[i5]);
                sb.append('|');
            }
            sb.append(StringUtil.NEWLINE + "+--------+-------------------------------------------------+----------------+");
        }

        /* JADX INFO: Access modifiers changed from: private */
        public static String hexDump(ByteBuf byteBuf, int i2, int i3) {
            if (i3 < 0) {
                throw new IllegalArgumentException(a.l("length: ", i3));
            }
            if (i3 == 0) {
                return "";
            }
            int i4 = i2 + i3;
            char[] cArr = new char[i3 << 1];
            int i5 = 0;
            while (i2 < i4) {
                System.arraycopy(HEXDUMP_TABLE, byteBuf.getUnsignedByte(i2) << 1, cArr, i5, 2);
                i2++;
                i5 += 2;
            }
            return new String(cArr);
        }

        /* JADX INFO: Access modifiers changed from: private */
        public static String hexDump(byte[] bArr, int i2, int i3) {
            if (i3 < 0) {
                throw new IllegalArgumentException(a.l("length: ", i3));
            }
            if (i3 == 0) {
                return "";
            }
            int i4 = i2 + i3;
            char[] cArr = new char[i3 << 1];
            int i5 = 0;
            while (i2 < i4) {
                System.arraycopy(HEXDUMP_TABLE, (bArr[i2] & 255) << 1, cArr, i5, 2);
                i2++;
                i5 += 2;
            }
            return new String(cArr);
        }

        /* JADX INFO: Access modifiers changed from: private */
        public static String prettyHexDump(ByteBuf byteBuf, int i2, int i3) {
            if (i3 == 0) {
                return "";
            }
            StringBuilder sb = new StringBuilder(((i3 / 16) + (i3 % 15 == 0 ? 0 : 1) + 4) * 80);
            appendPrettyHexDump(sb, byteBuf, i2, i3);
            return sb.toString();
        }
    }

    public static final class ThreadLocalDirectByteBuf extends UnpooledDirectByteBuf {
        private static final Recycler<ThreadLocalDirectByteBuf> RECYCLER = new Recycler<ThreadLocalDirectByteBuf>() { // from class: io.netty.buffer.ByteBufUtil.ThreadLocalDirectByteBuf.1
            /* JADX WARN: Can't rename method to resolve collision */
            @Override // io.netty.util.Recycler
            public ThreadLocalDirectByteBuf newObject(Recycler.Handle<ThreadLocalDirectByteBuf> handle) {
                return new ThreadLocalDirectByteBuf(handle);
            }
        };
        private final Recycler.Handle<ThreadLocalDirectByteBuf> handle;

        private ThreadLocalDirectByteBuf(Recycler.Handle<ThreadLocalDirectByteBuf> handle) {
            super(UnpooledByteBufAllocator.DEFAULT, 256, Integer.MAX_VALUE);
            this.handle = handle;
        }

        public static ThreadLocalDirectByteBuf newInstance() {
            ThreadLocalDirectByteBuf threadLocalDirectByteBuf = RECYCLER.get();
            threadLocalDirectByteBuf.setRefCnt(1);
            return threadLocalDirectByteBuf;
        }

        @Override // io.netty.buffer.UnpooledDirectByteBuf, io.netty.buffer.AbstractReferenceCountedByteBuf
        public void deallocate() {
            if (capacity() > ByteBufUtil.THREAD_LOCAL_BUFFER_SIZE) {
                super.deallocate();
            } else {
                clear();
                this.handle.recycle(this);
            }
        }
    }

    public static final class ThreadLocalUnsafeDirectByteBuf extends UnpooledUnsafeDirectByteBuf {
        private static final Recycler<ThreadLocalUnsafeDirectByteBuf> RECYCLER = new Recycler<ThreadLocalUnsafeDirectByteBuf>() { // from class: io.netty.buffer.ByteBufUtil.ThreadLocalUnsafeDirectByteBuf.1
            /* JADX WARN: Can't rename method to resolve collision */
            @Override // io.netty.util.Recycler
            public ThreadLocalUnsafeDirectByteBuf newObject(Recycler.Handle<ThreadLocalUnsafeDirectByteBuf> handle) {
                return new ThreadLocalUnsafeDirectByteBuf(handle);
            }
        };
        private final Recycler.Handle<ThreadLocalUnsafeDirectByteBuf> handle;

        private ThreadLocalUnsafeDirectByteBuf(Recycler.Handle<ThreadLocalUnsafeDirectByteBuf> handle) {
            super(UnpooledByteBufAllocator.DEFAULT, 256, Integer.MAX_VALUE);
            this.handle = handle;
        }

        public static ThreadLocalUnsafeDirectByteBuf newInstance() {
            ThreadLocalUnsafeDirectByteBuf threadLocalUnsafeDirectByteBuf = RECYCLER.get();
            threadLocalUnsafeDirectByteBuf.setRefCnt(1);
            return threadLocalUnsafeDirectByteBuf;
        }

        @Override // io.netty.buffer.UnpooledUnsafeDirectByteBuf, io.netty.buffer.AbstractReferenceCountedByteBuf
        public void deallocate() {
            if (capacity() > ByteBufUtil.THREAD_LOCAL_BUFFER_SIZE) {
                super.deallocate();
            } else {
                clear();
                this.handle.recycle(this);
            }
        }
    }

    static {
        ByteBufAllocator byteBufAllocator;
        InternalLogger internalLoggerFactory = InternalLoggerFactory.getInstance((Class<?>) ByteBufUtil.class);
        logger = internalLoggerFactory;
        CHAR_BUFFERS = new FastThreadLocal<CharBuffer>() { // from class: io.netty.buffer.ByteBufUtil.1
            @Override // io.netty.util.concurrent.FastThreadLocal
            public CharBuffer initialValue() {
                return CharBuffer.allocate(1024);
            }
        };
        MAX_BYTES_PER_CHAR_UTF8 = (int) CharsetUtil.encoder(CharsetUtil.UTF_8).maxBytesPerChar();
        String strTrim = SystemPropertyUtil.get("io.netty.allocator.type", PlatformDependent.isAndroid() ? "unpooled" : "pooled").toLowerCase(Locale.US).trim();
        if ("unpooled".equals(strTrim)) {
            byteBufAllocator = UnpooledByteBufAllocator.DEFAULT;
        } else {
            if (!"pooled".equals(strTrim)) {
                byteBufAllocator = PooledByteBufAllocator.DEFAULT;
                internalLoggerFactory.debug("-Dio.netty.allocator.type: pooled (unknown: {})", strTrim);
                DEFAULT_ALLOCATOR = byteBufAllocator;
                int i2 = SystemPropertyUtil.getInt("io.netty.threadLocalDirectBufferSize", 0);
                THREAD_LOCAL_BUFFER_SIZE = i2;
                internalLoggerFactory.debug("-Dio.netty.threadLocalDirectBufferSize: {}", Integer.valueOf(i2));
                int i3 = SystemPropertyUtil.getInt("io.netty.maxThreadLocalCharBufferSize", 16384);
                MAX_CHAR_BUFFER_SIZE = i3;
                internalLoggerFactory.debug("-Dio.netty.maxThreadLocalCharBufferSize: {}", Integer.valueOf(i3));
                FIND_NON_ASCII = new ByteProcessor() { // from class: io.netty.buffer.ByteBufUtil.2
                    @Override // io.netty.util.ByteProcessor
                    public boolean process(byte b2) {
                        return b2 >= 0;
                    }
                };
            }
            byteBufAllocator = PooledByteBufAllocator.DEFAULT;
        }
        internalLoggerFactory.debug("-Dio.netty.allocator.type: {}", strTrim);
        DEFAULT_ALLOCATOR = byteBufAllocator;
        int i22 = SystemPropertyUtil.getInt("io.netty.threadLocalDirectBufferSize", 0);
        THREAD_LOCAL_BUFFER_SIZE = i22;
        internalLoggerFactory.debug("-Dio.netty.threadLocalDirectBufferSize: {}", Integer.valueOf(i22));
        int i32 = SystemPropertyUtil.getInt("io.netty.maxThreadLocalCharBufferSize", 16384);
        MAX_CHAR_BUFFER_SIZE = i32;
        internalLoggerFactory.debug("-Dio.netty.maxThreadLocalCharBufferSize: {}", Integer.valueOf(i32));
        FIND_NON_ASCII = new ByteProcessor() { // from class: io.netty.buffer.ByteBufUtil.2
            @Override // io.netty.util.ByteProcessor
            public boolean process(byte b2) {
                return b2 >= 0;
            }
        };
    }

    private ByteBufUtil() {
    }

    public static void appendPrettyHexDump(StringBuilder sb, ByteBuf byteBuf) {
        appendPrettyHexDump(sb, byteBuf, byteBuf.readerIndex(), byteBuf.readableBytes());
    }

    public static void appendPrettyHexDump(StringBuilder sb, ByteBuf byteBuf, int i2, int i3) {
        HexUtil.appendPrettyHexDump(sb, byteBuf, i2, i3);
    }

    public static int compare(ByteBuf byteBuf, ByteBuf byteBuf2) {
        int i2 = byteBuf.readableBytes();
        int i3 = byteBuf2.readableBytes();
        int iMin = Math.min(i2, i3);
        int i4 = iMin >>> 2;
        int i5 = iMin & 3;
        int i6 = byteBuf.readerIndex();
        int i7 = byteBuf2.readerIndex();
        if (i4 > 0) {
            boolean z2 = byteBuf.order() == ByteOrder.BIG_ENDIAN;
            int i8 = i4 << 2;
            long jCompareUintBigEndian = byteBuf.order() == byteBuf2.order() ? z2 ? compareUintBigEndian(byteBuf, byteBuf2, i6, i7, i8) : compareUintLittleEndian(byteBuf, byteBuf2, i6, i7, i8) : z2 ? compareUintBigEndianA(byteBuf, byteBuf2, i6, i7, i8) : compareUintBigEndianB(byteBuf, byteBuf2, i6, i7, i8);
            if (jCompareUintBigEndian != 0) {
                return (int) Math.min(2147483647L, Math.max(-2147483648L, jCompareUintBigEndian));
            }
            i6 += i8;
            i7 += i8;
        }
        int i9 = i5 + i6;
        while (i6 < i9) {
            int unsignedByte = byteBuf.getUnsignedByte(i6) - byteBuf2.getUnsignedByte(i7);
            if (unsignedByte != 0) {
                return unsignedByte;
            }
            i6++;
            i7++;
        }
        return i2 - i3;
    }

    private static long compareUintBigEndian(ByteBuf byteBuf, ByteBuf byteBuf2, int i2, int i3, int i4) {
        int i5 = i4 + i2;
        while (i2 < i5) {
            long unsignedInt = byteBuf.getUnsignedInt(i2) - byteBuf2.getUnsignedInt(i3);
            if (unsignedInt != 0) {
                return unsignedInt;
            }
            i2 += 4;
            i3 += 4;
        }
        return 0L;
    }

    private static long compareUintBigEndianA(ByteBuf byteBuf, ByteBuf byteBuf2, int i2, int i3, int i4) {
        int i5 = i4 + i2;
        while (i2 < i5) {
            long unsignedInt = byteBuf.getUnsignedInt(i2) - byteBuf2.getUnsignedIntLE(i3);
            if (unsignedInt != 0) {
                return unsignedInt;
            }
            i2 += 4;
            i3 += 4;
        }
        return 0L;
    }

    private static long compareUintBigEndianB(ByteBuf byteBuf, ByteBuf byteBuf2, int i2, int i3, int i4) {
        int i5 = i4 + i2;
        while (i2 < i5) {
            long unsignedIntLE = byteBuf.getUnsignedIntLE(i2) - byteBuf2.getUnsignedInt(i3);
            if (unsignedIntLE != 0) {
                return unsignedIntLE;
            }
            i2 += 4;
            i3 += 4;
        }
        return 0L;
    }

    private static long compareUintLittleEndian(ByteBuf byteBuf, ByteBuf byteBuf2, int i2, int i3, int i4) {
        int i5 = i4 + i2;
        while (i2 < i5) {
            long unsignedIntLE = byteBuf.getUnsignedIntLE(i2) - byteBuf2.getUnsignedIntLE(i3);
            if (unsignedIntLE != 0) {
                return unsignedIntLE;
            }
            i2 += 4;
            i3 += 4;
        }
        return 0L;
    }

    public static void copy(AsciiString asciiString, int i2, ByteBuf byteBuf, int i3) {
        if (!MathUtil.isOutOfBounds(i2, i3, asciiString.length())) {
            ((ByteBuf) ObjectUtil.checkNotNull(byteBuf, "dst")).writeBytes(asciiString.array(), asciiString.arrayOffset() + i2, i3);
            return;
        }
        StringBuilder sbI = a.I("expected: 0 <= srcIdx(", i2, ") <= srcIdx + length(", i3, ") <= srcLen(");
        sbI.append(asciiString.length());
        sbI.append(')');
        throw new IndexOutOfBoundsException(sbI.toString());
    }

    public static void copy(AsciiString asciiString, int i2, ByteBuf byteBuf, int i3, int i4) {
        if (!MathUtil.isOutOfBounds(i2, i4, asciiString.length())) {
            ((ByteBuf) ObjectUtil.checkNotNull(byteBuf, "dst")).setBytes(i3, asciiString.array(), asciiString.arrayOffset() + i2, i4);
            return;
        }
        StringBuilder sbI = a.I("expected: 0 <= srcIdx(", i2, ") <= srcIdx + length(", i4, ") <= srcLen(");
        sbI.append(asciiString.length());
        sbI.append(')');
        throw new IndexOutOfBoundsException(sbI.toString());
    }

    public static void copy(AsciiString asciiString, ByteBuf byteBuf) {
        copy(asciiString, 0, byteBuf, asciiString.length());
    }

    public static byte decodeHexByte(CharSequence charSequence, int i2) {
        return StringUtil.decodeHexByte(charSequence, i2);
    }

    public static byte[] decodeHexDump(CharSequence charSequence) {
        return StringUtil.decodeHexDump(charSequence, 0, charSequence.length());
    }

    public static byte[] decodeHexDump(CharSequence charSequence, int i2, int i3) {
        return StringUtil.decodeHexDump(charSequence, i2, i3);
    }

    public static String decodeString(ByteBuf byteBuf, int i2, int i3, Charset charset) {
        if (i3 == 0) {
            return "";
        }
        CharsetDecoder charsetDecoderDecoder = CharsetUtil.decoder(charset);
        int iMaxCharsPerByte = (int) (((double) i3) * ((double) charsetDecoderDecoder.maxCharsPerByte()));
        FastThreadLocal<CharBuffer> fastThreadLocal = CHAR_BUFFERS;
        CharBuffer charBufferAllocate = fastThreadLocal.get();
        if (charBufferAllocate.length() < iMaxCharsPerByte) {
            charBufferAllocate = CharBuffer.allocate(iMaxCharsPerByte);
            if (iMaxCharsPerByte <= MAX_CHAR_BUFFER_SIZE) {
                fastThreadLocal.set(charBufferAllocate);
            }
        } else {
            charBufferAllocate.clear();
        }
        if (byteBuf.nioBufferCount() == 1) {
            decodeString(charsetDecoderDecoder, byteBuf.nioBuffer(i2, i3), charBufferAllocate);
        } else {
            ByteBuf byteBufHeapBuffer = byteBuf.alloc().heapBuffer(i3);
            try {
                byteBufHeapBuffer.writeBytes(byteBuf, i2, i3);
                decodeString(charsetDecoderDecoder, byteBufHeapBuffer.internalNioBuffer(byteBufHeapBuffer.readerIndex(), i3), charBufferAllocate);
            } finally {
                byteBufHeapBuffer.release();
            }
        }
        return charBufferAllocate.flip().toString();
    }

    private static void decodeString(CharsetDecoder charsetDecoder, ByteBuffer byteBuffer, CharBuffer charBuffer) {
        try {
            CoderResult coderResultDecode = charsetDecoder.decode(byteBuffer, charBuffer, true);
            if (!coderResultDecode.isUnderflow()) {
                coderResultDecode.throwException();
            }
            CoderResult coderResultFlush = charsetDecoder.flush(charBuffer);
            if (coderResultFlush.isUnderflow()) {
                return;
            }
            coderResultFlush.throwException();
        } catch (CharacterCodingException e2) {
            throw new IllegalStateException(e2);
        }
    }

    public static ByteBuf encodeString(ByteBufAllocator byteBufAllocator, CharBuffer charBuffer, Charset charset) {
        return encodeString0(byteBufAllocator, false, charBuffer, charset, 0);
    }

    public static ByteBuf encodeString(ByteBufAllocator byteBufAllocator, CharBuffer charBuffer, Charset charset, int i2) {
        return encodeString0(byteBufAllocator, false, charBuffer, charset, i2);
    }

    public static ByteBuf encodeString0(ByteBufAllocator byteBufAllocator, boolean z2, CharBuffer charBuffer, Charset charset, int i2) {
        CharsetEncoder charsetEncoderEncoder = CharsetUtil.encoder(charset);
        int iRemaining = ((int) (((double) charBuffer.remaining()) * ((double) charsetEncoderEncoder.maxBytesPerChar()))) + i2;
        ByteBuf byteBufHeapBuffer = z2 ? byteBufAllocator.heapBuffer(iRemaining) : byteBufAllocator.buffer(iRemaining);
        try {
            try {
                ByteBuffer byteBufferInternalNioBuffer = byteBufHeapBuffer.internalNioBuffer(byteBufHeapBuffer.readerIndex(), iRemaining);
                int iPosition = byteBufferInternalNioBuffer.position();
                CoderResult coderResultEncode = charsetEncoderEncoder.encode(charBuffer, byteBufferInternalNioBuffer, true);
                if (!coderResultEncode.isUnderflow()) {
                    coderResultEncode.throwException();
                }
                CoderResult coderResultFlush = charsetEncoderEncoder.flush(byteBufferInternalNioBuffer);
                if (!coderResultFlush.isUnderflow()) {
                    coderResultFlush.throwException();
                }
                byteBufHeapBuffer.writerIndex((byteBufHeapBuffer.writerIndex() + byteBufferInternalNioBuffer.position()) - iPosition);
                return byteBufHeapBuffer;
            } catch (CharacterCodingException e2) {
                throw new IllegalStateException(e2);
            }
        } catch (Throwable th) {
            byteBufHeapBuffer.release();
            throw th;
        }
    }

    public static boolean ensureWritableSuccess(int i2) {
        return i2 == 0 || i2 == 2;
    }

    public static boolean equals(ByteBuf byteBuf, int i2, ByteBuf byteBuf2, int i3, int i4) {
        if (i2 < 0 || i3 < 0 || i4 < 0) {
            throw new IllegalArgumentException("All indexes and lengths must be non-negative");
        }
        if (byteBuf.writerIndex() - i4 < i2 || byteBuf2.writerIndex() - i4 < i3) {
            return false;
        }
        int i5 = i4 >>> 3;
        if (byteBuf.order() == byteBuf2.order()) {
            while (i5 > 0) {
                if (byteBuf.getLong(i2) != byteBuf2.getLong(i3)) {
                    return false;
                }
                i2 += 8;
                i3 += 8;
                i5--;
            }
        } else {
            while (i5 > 0) {
                if (byteBuf.getLong(i2) != swapLong(byteBuf2.getLong(i3))) {
                    return false;
                }
                i2 += 8;
                i3 += 8;
                i5--;
            }
        }
        for (int i6 = i4 & 7; i6 > 0; i6--) {
            if (byteBuf.getByte(i2) != byteBuf2.getByte(i3)) {
                return false;
            }
            i2++;
            i3++;
        }
        return true;
    }

    public static boolean equals(ByteBuf byteBuf, ByteBuf byteBuf2) {
        int i2 = byteBuf.readableBytes();
        if (i2 != byteBuf2.readableBytes()) {
            return false;
        }
        return equals(byteBuf, byteBuf.readerIndex(), byteBuf2, byteBuf2.readerIndex(), i2);
    }

    private static int firstIndexOf(ByteBuf byteBuf, int i2, int i3, byte b2) {
        int iMax = Math.max(i2, 0);
        if (iMax >= i3 || byteBuf.capacity() == 0) {
            return -1;
        }
        return byteBuf.forEachByte(iMax, i3 - iMax, new ByteProcessor.IndexOfProcessor(b2));
    }

    private static void getBytes(ByteBuffer byteBuffer, byte[] bArr, int i2, int i3, OutputStream outputStream, int i4) throws IOException {
        do {
            int iMin = Math.min(i3, i4);
            byteBuffer.get(bArr, i2, iMin);
            outputStream.write(bArr, i2, iMin);
            i4 -= iMin;
        } while (i4 > 0);
    }

    public static byte[] getBytes(ByteBuf byteBuf) {
        return getBytes(byteBuf, byteBuf.readerIndex(), byteBuf.readableBytes());
    }

    public static byte[] getBytes(ByteBuf byteBuf, int i2, int i3) {
        return getBytes(byteBuf, i2, i3, true);
    }

    public static byte[] getBytes(ByteBuf byteBuf, int i2, int i3, boolean z2) {
        if (MathUtil.isOutOfBounds(i2, i3, byteBuf.capacity())) {
            StringBuilder sbI = a.I("expected: 0 <= start(", i2, ") <= start + length(", i3, ") <= buf.capacity(");
            sbI.append(byteBuf.capacity());
            sbI.append(')');
            throw new IndexOutOfBoundsException(sbI.toString());
        }
        if (!byteBuf.hasArray()) {
            byte[] bArr = new byte[i3];
            byteBuf.getBytes(i2, bArr);
            return bArr;
        }
        if (!z2 && i2 == 0 && i3 == byteBuf.capacity()) {
            return byteBuf.array();
        }
        int iArrayOffset = byteBuf.arrayOffset() + i2;
        return Arrays.copyOfRange(byteBuf.array(), iArrayOffset, i3 + iArrayOffset);
    }

    public static int hashCode(ByteBuf byteBuf) {
        int iSwapInt;
        int i2 = byteBuf.readableBytes();
        int i3 = i2 >>> 2;
        int i4 = i2 & 3;
        int i5 = byteBuf.readerIndex();
        if (byteBuf.order() == ByteOrder.BIG_ENDIAN) {
            iSwapInt = 1;
            while (i3 > 0) {
                iSwapInt = (iSwapInt * 31) + byteBuf.getInt(i5);
                i5 += 4;
                i3--;
            }
        } else {
            iSwapInt = 1;
            while (i3 > 0) {
                iSwapInt = (iSwapInt * 31) + swapInt(byteBuf.getInt(i5));
                i5 += 4;
                i3--;
            }
        }
        while (i4 > 0) {
            iSwapInt = (iSwapInt * 31) + byteBuf.getByte(i5);
            i4--;
            i5++;
        }
        if (iSwapInt == 0) {
            return 1;
        }
        return iSwapInt;
    }

    public static String hexDump(ByteBuf byteBuf) {
        return hexDump(byteBuf, byteBuf.readerIndex(), byteBuf.readableBytes());
    }

    public static String hexDump(ByteBuf byteBuf, int i2, int i3) {
        return HexUtil.hexDump(byteBuf, i2, i3);
    }

    public static String hexDump(byte[] bArr) {
        return hexDump(bArr, 0, bArr.length);
    }

    public static String hexDump(byte[] bArr, int i2, int i3) {
        return HexUtil.hexDump(bArr, i2, i3);
    }

    public static int indexOf(ByteBuf byteBuf, int i2, int i3, byte b2) {
        return i2 <= i3 ? firstIndexOf(byteBuf, i2, i3, b2) : lastIndexOf(byteBuf, i2, i3, b2);
    }

    public static int indexOf(ByteBuf byteBuf, ByteBuf byteBuf2) {
        int i2 = (byteBuf2.readableBytes() - byteBuf.readableBytes()) + 1;
        for (int i3 = 0; i3 < i2; i3++) {
            if (equals(byteBuf, byteBuf.readerIndex(), byteBuf2, byteBuf2.readerIndex() + i3, byteBuf.readableBytes())) {
                return byteBuf2.readerIndex() + i3;
            }
        }
        return -1;
    }

    private static boolean isAscii(ByteBuf byteBuf, int i2, int i3) {
        return byteBuf.forEachByte(i2, i3, FIND_NON_ASCII) == -1;
    }

    public static boolean isText(ByteBuf byteBuf, int i2, int i3, Charset charset) {
        ObjectUtil.checkNotNull(byteBuf, "buf");
        ObjectUtil.checkNotNull(charset, "charset");
        int i4 = byteBuf.readableBytes() + byteBuf.readerIndex();
        if (i2 < 0 || i3 < 0 || i2 > i4 - i3) {
            throw new IndexOutOfBoundsException(a.o("index: ", i2, " length: ", i3));
        }
        if (charset.equals(CharsetUtil.UTF_8)) {
            return isUtf8(byteBuf, i2, i3);
        }
        if (charset.equals(CharsetUtil.US_ASCII)) {
            return isAscii(byteBuf, i2, i3);
        }
        CodingErrorAction codingErrorAction = CodingErrorAction.REPORT;
        CharsetDecoder charsetDecoderDecoder = CharsetUtil.decoder(charset, codingErrorAction, codingErrorAction);
        try {
            if (byteBuf.nioBufferCount() == 1) {
                charsetDecoderDecoder.decode(byteBuf.nioBuffer(i2, i3));
            } else {
                ByteBuf byteBufHeapBuffer = byteBuf.alloc().heapBuffer(i3);
                try {
                    byteBufHeapBuffer.writeBytes(byteBuf, i2, i3);
                    charsetDecoderDecoder.decode(byteBufHeapBuffer.internalNioBuffer(byteBufHeapBuffer.readerIndex(), i3));
                } finally {
                    byteBufHeapBuffer.release();
                }
            }
            return true;
        } catch (CharacterCodingException unused) {
            return false;
        }
    }

    public static boolean isText(ByteBuf byteBuf, Charset charset) {
        return isText(byteBuf, byteBuf.readerIndex(), byteBuf.readableBytes(), charset);
    }

    private static boolean isUtf8(ByteBuf byteBuf, int i2, int i3) {
        int i4;
        int i5 = i3 + i2;
        while (i2 < i5) {
            int i6 = i2 + 1;
            byte b2 = byteBuf.getByte(i2);
            if ((b2 & DefaultBinaryMemcacheRequest.REQUEST_MAGIC_BYTE) == 0) {
                i2 = i6;
            } else if ((b2 & 224) == 192) {
                if (i6 >= i5) {
                    return false;
                }
                int i7 = i6 + 1;
                if ((byteBuf.getByte(i6) & 192) != 128 || (b2 & 255) < 194) {
                    return false;
                }
                i2 = i7;
            } else if ((b2 & 240) == 224) {
                if (i6 > i5 - 2) {
                    return false;
                }
                int i8 = i6 + 1;
                byte b3 = byteBuf.getByte(i6);
                int i9 = i8 + 1;
                byte b4 = byteBuf.getByte(i8);
                if ((b3 & 192) != 128 || (b4 & 192) != 128) {
                    return false;
                }
                int i10 = b2 & BinaryMemcacheOpcodes.PREPEND;
                if (i10 == 0 && (b3 & 255) < 160) {
                    return false;
                }
                if (i10 == 13 && (b3 & 255) > 159) {
                    return false;
                }
                i2 = i9;
            } else {
                if ((b2 & 248) != 240 || i6 > i5 - 3) {
                    return false;
                }
                int i11 = i6 + 1;
                byte b5 = byteBuf.getByte(i6);
                int i12 = i11 + 1;
                byte b6 = byteBuf.getByte(i11);
                int i13 = i12 + 1;
                byte b7 = byteBuf.getByte(i12);
                if ((b5 & 192) != 128 || (b6 & 192) != 128 || (b7 & 192) != 128 || (i4 = b2 & 255) > 244 || ((i4 == 240 && (b5 & 255) < 144) || (i4 == 244 && (b5 & 255) > 143))) {
                    return false;
                }
                i2 = i13;
            }
        }
        return true;
    }

    private static int lastIndexOf(ByteBuf byteBuf, int i2, int i3, byte b2) {
        int iMin = Math.min(i2, byteBuf.capacity());
        if (iMin < 0 || byteBuf.capacity() == 0) {
            return -1;
        }
        return byteBuf.forEachByteDesc(i3, iMin - i3, new ByteProcessor.IndexOfProcessor(b2));
    }

    public static String prettyHexDump(ByteBuf byteBuf) {
        return prettyHexDump(byteBuf, byteBuf.readerIndex(), byteBuf.readableBytes());
    }

    public static String prettyHexDump(ByteBuf byteBuf, int i2, int i3) {
        return HexUtil.prettyHexDump(byteBuf, i2, i3);
    }

    public static ByteBuf readBytes(ByteBufAllocator byteBufAllocator, ByteBuf byteBuf, int i2) {
        ByteBuf byteBufBuffer = byteBufAllocator.buffer(i2);
        try {
            byteBuf.readBytes(byteBufBuffer);
            return byteBufBuffer;
        } catch (Throwable th) {
            byteBufBuffer.release();
            throw th;
        }
    }

    public static void readBytes(ByteBufAllocator byteBufAllocator, ByteBuffer byteBuffer, int i2, int i3, OutputStream outputStream) throws IOException {
        if (byteBuffer.hasArray()) {
            outputStream.write(byteBuffer.array(), byteBuffer.arrayOffset() + i2, i3);
            return;
        }
        int iMin = Math.min(i3, 8192);
        byteBuffer.clear().position(i2);
        if (!byteBufAllocator.isDirectBufferPooled()) {
            getBytes(byteBuffer, new byte[iMin], 0, iMin, outputStream, i3);
            return;
        }
        ByteBuf byteBufHeapBuffer = byteBufAllocator.heapBuffer(iMin);
        try {
            getBytes(byteBuffer, byteBufHeapBuffer.array(), byteBufHeapBuffer.arrayOffset(), iMin, outputStream, i3);
        } finally {
            byteBufHeapBuffer.release();
        }
    }

    public static int reserveAndWriteUtf8(ByteBuf byteBuf, CharSequence charSequence, int i2) {
        while (!(byteBuf instanceof AbstractByteBuf)) {
            if (!(byteBuf instanceof WrappedByteBuf)) {
                byte[] bytes = charSequence.toString().getBytes(CharsetUtil.UTF_8);
                byteBuf.writeBytes(bytes);
                return bytes.length;
            }
            byteBuf = byteBuf.unwrap();
        }
        AbstractByteBuf abstractByteBuf = (AbstractByteBuf) byteBuf;
        abstractByteBuf.ensureWritable0(i2);
        int iWriteUtf8 = writeUtf8(abstractByteBuf, abstractByteBuf.writerIndex, charSequence, charSequence.length());
        abstractByteBuf.writerIndex += iWriteUtf8;
        return iWriteUtf8;
    }

    public static ByteBuf setShortBE(ByteBuf byteBuf, int i2, int i3) {
        return byteBuf.order() == ByteOrder.BIG_ENDIAN ? byteBuf.setShort(i2, i3) : byteBuf.setShortLE(i2, i3);
    }

    public static int swapInt(int i2) {
        return Integer.reverseBytes(i2);
    }

    public static long swapLong(long j2) {
        return Long.reverseBytes(j2);
    }

    public static int swapMedium(int i2) {
        int i3 = ((i2 >>> 16) & DnsRecord.CLASS_ANY) | ((i2 << 16) & 16711680) | (65280 & i2);
        return (8388608 & i3) != 0 ? i3 | (-16777216) : i3;
    }

    public static short swapShort(short s2) {
        return Short.reverseBytes(s2);
    }

    public static ByteBuf threadLocalDirectBuffer() {
        if (THREAD_LOCAL_BUFFER_SIZE <= 0) {
            return null;
        }
        return PlatformDependent.hasUnsafe() ? ThreadLocalUnsafeDirectByteBuf.newInstance() : ThreadLocalDirectByteBuf.newInstance();
    }

    public static int utf8Bytes(CharSequence charSequence) {
        if (charSequence instanceof AsciiString) {
            return charSequence.length();
        }
        int length = charSequence.length();
        int i2 = 0;
        while (i2 < length && charSequence.charAt(i2) < 128) {
            i2++;
        }
        return i2 < length ? i2 + utf8Bytes(charSequence, i2, length) : i2;
    }

    private static int utf8Bytes(CharSequence charSequence, int i2, int i3) {
        int i4 = 0;
        while (i2 < i3) {
            char cCharAt = charSequence.charAt(i2);
            if (cCharAt < 2048) {
                i4 = ((127 - cCharAt) >>> 31) + 1 + i4;
            } else if (!StringUtil.isSurrogate(cCharAt)) {
                i4 += 3;
            } else if (Character.isHighSurrogate(cCharAt)) {
                i2++;
                try {
                    i4 = !Character.isLowSurrogate(charSequence.charAt(i2)) ? i4 + 2 : i4 + 4;
                } catch (IndexOutOfBoundsException unused) {
                    return i4 + 1;
                }
            } else {
                i4++;
            }
            i2++;
        }
        return i4;
    }

    public static int utf8MaxBytes(int i2) {
        return i2 * MAX_BYTES_PER_CHAR_UTF8;
    }

    public static int utf8MaxBytes(CharSequence charSequence) {
        return utf8MaxBytes(charSequence.length());
    }

    public static int writeAscii(AbstractByteBuf abstractByteBuf, int i2, CharSequence charSequence, int i3) {
        int i4 = 0;
        while (i4 < i3) {
            abstractByteBuf._setByte(i2, AsciiString.c2b(charSequence.charAt(i4)));
            i4++;
            i2++;
        }
        return i3;
    }

    public static int writeAscii(ByteBuf byteBuf, CharSequence charSequence) {
        int length = charSequence.length();
        if (charSequence instanceof AsciiString) {
            AsciiString asciiString = (AsciiString) charSequence;
            byteBuf.writeBytes(asciiString.array(), asciiString.arrayOffset(), length);
            return length;
        }
        while (!(byteBuf instanceof AbstractByteBuf)) {
            if (!(byteBuf instanceof WrappedByteBuf)) {
                byte[] bytes = charSequence.toString().getBytes(CharsetUtil.US_ASCII);
                byteBuf.writeBytes(bytes);
                return bytes.length;
            }
            byteBuf = byteBuf.unwrap();
        }
        AbstractByteBuf abstractByteBuf = (AbstractByteBuf) byteBuf;
        abstractByteBuf.ensureWritable0(length);
        int iWriteAscii = writeAscii(abstractByteBuf, abstractByteBuf.writerIndex, charSequence, length);
        abstractByteBuf.writerIndex += iWriteAscii;
        return iWriteAscii;
    }

    public static ByteBuf writeAscii(ByteBufAllocator byteBufAllocator, CharSequence charSequence) {
        ByteBuf byteBufBuffer = byteBufAllocator.buffer(charSequence.length());
        writeAscii(byteBufBuffer, charSequence);
        return byteBufBuffer;
    }

    public static ByteBuf writeMediumBE(ByteBuf byteBuf, int i2) {
        return byteBuf.order() == ByteOrder.BIG_ENDIAN ? byteBuf.writeMedium(i2) : byteBuf.writeMediumLE(i2);
    }

    public static ByteBuf writeShortBE(ByteBuf byteBuf, int i2) {
        return byteBuf.order() == ByteOrder.BIG_ENDIAN ? byteBuf.writeShort(i2) : byteBuf.writeShortLE(i2);
    }

    public static int writeUtf8(AbstractByteBuf abstractByteBuf, int i2, CharSequence charSequence, int i3) {
        int i4;
        int i5;
        int i6 = 0;
        int i7 = i2;
        while (i6 < i3) {
            char cCharAt = charSequence.charAt(i6);
            if (cCharAt < 128) {
                abstractByteBuf._setByte(i7, (byte) cCharAt);
                i7++;
            } else {
                if (cCharAt < 2048) {
                    i4 = i7 + 1;
                    abstractByteBuf._setByte(i7, (byte) ((cCharAt >> 6) | 192));
                    i7 = i4 + 1;
                    i5 = cCharAt & '?';
                } else {
                    if (!StringUtil.isSurrogate(cCharAt)) {
                        int i8 = i7 + 1;
                        abstractByteBuf._setByte(i7, (byte) ((cCharAt >> '\f') | 224));
                        int i9 = i8 + 1;
                        abstractByteBuf._setByte(i8, (byte) ((63 & (cCharAt >> 6)) | 128));
                        abstractByteBuf._setByte(i9, (byte) ((cCharAt & '?') | 128));
                        i7 = i9 + 1;
                    } else if (Character.isHighSurrogate(cCharAt)) {
                        i6++;
                        try {
                            char cCharAt2 = charSequence.charAt(i6);
                            if (Character.isLowSurrogate(cCharAt2)) {
                                int codePoint = Character.toCodePoint(cCharAt, cCharAt2);
                                int i10 = i7 + 1;
                                abstractByteBuf._setByte(i7, (byte) ((codePoint >> 18) | 240));
                                int i11 = i10 + 1;
                                abstractByteBuf._setByte(i10, (byte) (((codePoint >> 12) & 63) | 128));
                                i4 = i11 + 1;
                                abstractByteBuf._setByte(i11, (byte) (((codePoint >> 6) & 63) | 128));
                                i7 = i4 + 1;
                                i5 = codePoint & 63;
                            } else {
                                int i12 = i7 + 1;
                                abstractByteBuf._setByte(i7, 63);
                                i7 = i12 + 1;
                                abstractByteBuf._setByte(i12, Character.isHighSurrogate(cCharAt2) ? '?' : cCharAt2);
                            }
                        } catch (IndexOutOfBoundsException unused) {
                            abstractByteBuf._setByte(i7, 63);
                            i7++;
                        }
                    } else {
                        abstractByteBuf._setByte(i7, 63);
                        i7++;
                    }
                }
                abstractByteBuf._setByte(i4, (byte) (i5 | 128));
            }
            i6++;
        }
        return i7 - i2;
    }

    public static int writeUtf8(ByteBuf byteBuf, CharSequence charSequence) {
        return reserveAndWriteUtf8(byteBuf, charSequence, utf8MaxBytes(charSequence));
    }

    public static ByteBuf writeUtf8(ByteBufAllocator byteBufAllocator, CharSequence charSequence) {
        ByteBuf byteBufBuffer = byteBufAllocator.buffer(utf8MaxBytes(charSequence));
        writeUtf8(byteBufBuffer, charSequence);
        return byteBufBuffer;
    }
}
