Class ByteBufUtil

java.lang.Object
io.netty.buffer.ByteBufUtil

public final class ByteBufUtil extends Object
A collection of utility methods that is related with handling ByteBuf, such as the generation of hex dump and swapping an integer's byte order.
  • Field Details

    • logger

      private static final InternalLogger logger
    • BYTE_ARRAYS

      private static final FastThreadLocal<byte[]> BYTE_ARRAYS
    • WRITE_UTF_UNKNOWN

      private static final byte WRITE_UTF_UNKNOWN
      See Also:
    • MAX_CHAR_BUFFER_SIZE

      private static final int MAX_CHAR_BUFFER_SIZE
    • THREAD_LOCAL_BUFFER_SIZE

      private static final int THREAD_LOCAL_BUFFER_SIZE
    • MAX_BYTES_PER_CHAR_UTF8

      private static final int MAX_BYTES_PER_CHAR_UTF8
    • WRITE_CHUNK_SIZE

      static final int WRITE_CHUNK_SIZE
      See Also:
    • DEFAULT_ALLOCATOR

      static final ByteBufAllocator DEFAULT_ALLOCATOR
    • MAX_TL_ARRAY_LEN

      static final int MAX_TL_ARRAY_LEN
      See Also:
    • FIND_NON_ASCII

      private static final ByteProcessor FIND_NON_ASCII
      Aborts on a byte which is not a valid ASCII character.
  • Constructor Details

    • ByteBufUtil

      private ByteBufUtil()
  • Method Details

    • threadLocalTempArray

      static byte[] threadLocalTempArray(int minLength)
      Allocates a new array if minLength > MAX_TL_ARRAY_LEN
    • isAccessible

      public static boolean isAccessible(ByteBuf buffer)
      Returns:
      whether the specified buffer has a nonzero ref count
    • ensureAccessible

      public static ByteBuf ensureAccessible(ByteBuf buffer)
      Returns:
      the passed in buffer
      Throws:
      IllegalReferenceCountException - if the buffer has a zero ref count
    • hexDump

      public static String hexDump(ByteBuf buffer)
      Returns a hex dump of the specified buffer's readable bytes.
    • hexDump

      public static String hexDump(ByteBuf buffer, int fromIndex, int length)
      Returns a hex dump of the specified buffer's sub-region.
    • hexDump

      public static String hexDump(byte[] array)
      Returns a hex dump of the specified byte array.
    • hexDump

      public static String hexDump(byte[] array, int fromIndex, int length)
      Returns a hex dump of the specified byte array's sub-region.
    • decodeHexByte

      public static byte decodeHexByte(CharSequence s, int pos)
      Decode a 2-digit hex byte from within a string.
    • decodeHexDump

      public static byte[] decodeHexDump(CharSequence hexDump)
      Decodes a string generated by hexDump(byte[])
    • decodeHexDump

      public static byte[] decodeHexDump(CharSequence hexDump, int fromIndex, int length)
      Decodes part of a string generated by hexDump(byte[])
    • ensureWritableSuccess

      public static boolean ensureWritableSuccess(int ensureWritableResult)
      Used to determine if the return value of ByteBuf.ensureWritable(int, boolean) means that there is adequate space and a write operation will succeed.
      Parameters:
      ensureWritableResult - The return value from ByteBuf.ensureWritable(int, boolean).
      Returns:
      true if ensureWritableResult means that there is adequate space and a write operation will succeed.
    • hashCode

      public static int hashCode(ByteBuf buffer)
      Calculates the hash code of the specified buffer. This method is useful when implementing a new buffer type.
    • indexOf

      public static int indexOf(ByteBuf needle, ByteBuf haystack)
      Returns the reader index of needle in haystack, or -1 if needle is not in haystack. This method uses the Two-Way string matching algorithm, which yields O(1) space complexity and excellent performance.
    • maxSuf

      private static long maxSuf(ByteBuf x, int m, int start, boolean isSuffix)
    • equals

      public static boolean equals(ByteBuf a, int aStartIndex, ByteBuf b, int bStartIndex, int length)
      Returns true if and only if the two specified buffers are identical to each other for length bytes starting at aStartIndex index for the a buffer and bStartIndex index for the b buffer. A more compact way to express this is:

      a[aStartIndex : aStartIndex + length] == b[bStartIndex : bStartIndex + length]

    • equals

      public static boolean equals(ByteBuf bufferA, ByteBuf bufferB)
      Returns true if and only if the two specified buffers are identical to each other as described in ByteBuf.equals(Object). This method is useful when implementing a new buffer type.
    • compare

      public static int compare(ByteBuf bufferA, ByteBuf bufferB)
      Compares the two specified buffers as described in ByteBuf.compareTo(ByteBuf). This method is useful when implementing a new buffer type.
    • compareUintBigEndian

      private static long compareUintBigEndian(ByteBuf bufferA, ByteBuf bufferB, int aIndex, int bIndex, int uintCountIncrement)
    • compareUintLittleEndian

      private static long compareUintLittleEndian(ByteBuf bufferA, ByteBuf bufferB, int aIndex, int bIndex, int uintCountIncrement)
    • compareUintBigEndianA

      private static long compareUintBigEndianA(ByteBuf bufferA, ByteBuf bufferB, int aIndex, int bIndex, int uintCountIncrement)
    • compareUintBigEndianB

      private static long compareUintBigEndianB(ByteBuf bufferA, ByteBuf bufferB, int aIndex, int bIndex, int uintCountIncrement)
    • uintFromLE

      private static long uintFromLE(long value)
    • unrolledFirstIndexOf

      private static int unrolledFirstIndexOf(AbstractByteBuf buffer, int fromIndex, int byteCount, byte value)
    • firstIndexOf

      static int firstIndexOf(AbstractByteBuf buffer, int fromIndex, int toIndex, byte value)
      This is using a SWAR (SIMD Within A Register) batch read technique to minimize bound-checks and improve memory usage while searching for value.
    • linearFirstIndexOf

      private static int linearFirstIndexOf(AbstractByteBuf buffer, int fromIndex, int toIndex, byte value)
    • indexOf

      public static int indexOf(ByteBuf buffer, int fromIndex, int toIndex, byte value)
      The default implementation of ByteBuf.indexOf(int, int, byte). This method is useful when implementing a new buffer type.
    • swapShort

      public static short swapShort(short value)
      Toggles the endianness of the specified 16-bit short integer.
    • swapMedium

      public static int swapMedium(int value)
      Toggles the endianness of the specified 24-bit medium integer.
    • swapInt

      public static int swapInt(int value)
      Toggles the endianness of the specified 32-bit integer.
    • swapLong

      public static long swapLong(long value)
      Toggles the endianness of the specified 64-bit long integer.
    • writeShortBE

      public static ByteBuf writeShortBE(ByteBuf buf, int shortValue)
      Writes a big-endian 16-bit short integer to the buffer.
    • setShortBE

      public static ByteBuf setShortBE(ByteBuf buf, int index, int shortValue)
      Sets a big-endian 16-bit short integer to the buffer.
    • writeMediumBE

      public static ByteBuf writeMediumBE(ByteBuf buf, int mediumValue)
      Writes a big-endian 24-bit medium integer to the buffer.
    • readUnsignedShortBE

      public static int readUnsignedShortBE(ByteBuf buf)
      Reads a big-endian unsigned 16-bit short integer from the buffer.
    • readIntBE

      public static int readIntBE(ByteBuf buf)
      Reads a big-endian 32-bit integer from the buffer.
    • readBytes

      public static ByteBuf readBytes(ByteBufAllocator alloc, ByteBuf buffer, int length)
      Read the given amount of bytes into a new ByteBuf that is allocated from the ByteBufAllocator.
    • lastIndexOf

      static int lastIndexOf(AbstractByteBuf buffer, int fromIndex, int toIndex, byte value)
    • linearLastIndexOf

      private static int linearLastIndexOf(AbstractByteBuf buffer, int fromIndex, int toIndex, byte value)
    • unrolledLastIndexOf

      private static int unrolledLastIndexOf(AbstractByteBuf buffer, int fromIndex, int byteCount, byte value)
    • checkCharSequenceBounds

      private static CharSequence checkCharSequenceBounds(CharSequence seq, int start, int end)
    • writeUtf8

      public static ByteBuf writeUtf8(ByteBufAllocator alloc, CharSequence seq)
      Encode a CharSequence in UTF-8 and write it to a ByteBuf allocated with alloc.
      Parameters:
      alloc - The allocator used to allocate a new ByteBuf.
      seq - The characters to write into a buffer.
      Returns:
      The ByteBuf which contains the UTF-8 encoded result.
    • writeUtf8

      public static int writeUtf8(ByteBuf buf, CharSequence seq)
      Encode a CharSequence in UTF-8 and write it to a ByteBuf.

      It behaves like reserveAndWriteUtf8(ByteBuf, CharSequence, int) with reserveBytes computed by utf8MaxBytes(CharSequence).
      This method returns the actual number of bytes written.

    • writeUtf8

      public static int writeUtf8(ByteBuf buf, CharSequence seq, int start, int end)
      Equivalent to writeUtf8(buf, seq.subSequence(start, end)) but avoids subsequence object allocation.
    • reserveAndWriteUtf8

      public static int reserveAndWriteUtf8(ByteBuf buf, CharSequence seq, int reserveBytes)
      Encode a CharSequence in UTF-8 and write it into reserveBytes of a ByteBuf.

      The reserveBytes must be computed (ie eagerly using utf8MaxBytes(CharSequence) or exactly with utf8Bytes(CharSequence)) to ensure this method to not fail: for performance reasons the index checks will be performed using just reserveBytes.
      This method returns the actual number of bytes written.

    • reserveAndWriteUtf8

      public static int reserveAndWriteUtf8(ByteBuf buf, CharSequence seq, int start, int end, int reserveBytes)
      Equivalent to reserveAndWriteUtf8(buf, seq.subSequence(start, end), reserveBytes) but avoids subsequence object allocation if possible.
      Returns:
      actual number of bytes written
    • reserveAndWriteUtf8Seq

      private static int reserveAndWriteUtf8Seq(ByteBuf buf, CharSequence seq, int start, int end, int reserveBytes)
    • writeUtf8

      static int writeUtf8(AbstractByteBuf buffer, int writerIndex, int reservedBytes, CharSequence seq, int len)
    • writeUtf8

      static int writeUtf8(AbstractByteBuf buffer, int writerIndex, int reservedBytes, CharSequence seq, int start, int end)
    • writeAsciiString

      static void writeAsciiString(AbstractByteBuf buffer, int writerIndex, AsciiString seq, int start, int end)
    • safeDirectWriteUtf8

      private static int safeDirectWriteUtf8(ByteBuffer buffer, int writerIndex, CharSequence seq, int start, int end)
    • safeWriteUtf8

      private static int safeWriteUtf8(AbstractByteBuf buffer, int writerIndex, CharSequence seq, int start, int end)
    • safeArrayWriteUtf8

      private static int safeArrayWriteUtf8(byte[] buffer, int writerIndex, CharSequence seq, int start, int end)
    • unsafeWriteUtf8

      private static int unsafeWriteUtf8(byte[] buffer, long memoryOffset, int writerIndex, CharSequence seq, int start, int end)
    • utf8MaxBytes

      public static int utf8MaxBytes(int seqLength)
      Returns max bytes length of UTF8 character sequence of the given length.
    • utf8MaxBytes

      public static int utf8MaxBytes(CharSequence seq)
      Returns max bytes length of UTF8 character sequence.

      It behaves like utf8MaxBytes(int) applied to seq CharSequence.length().

    • utf8Bytes

      public static int utf8Bytes(CharSequence seq)
      Returns the exact bytes length of UTF8 character sequence.

      This method is producing the exact length according to writeUtf8(ByteBuf, CharSequence).

    • utf8Bytes

      public static int utf8Bytes(CharSequence seq, int start, int end)
      Equivalent to utf8Bytes(seq.subSequence(start, end)) but avoids subsequence object allocation.

      This method is producing the exact length according to writeUtf8(ByteBuf, CharSequence, int, int).

    • utf8ByteCount

      private static int utf8ByteCount(CharSequence seq, int start, int end)
    • utf8BytesNonAscii

      private static int utf8BytesNonAscii(CharSequence seq, int start, int end)
    • writeAscii

      public static ByteBuf writeAscii(ByteBufAllocator alloc, CharSequence seq)
      Encode a CharSequence in ASCII and write it to a ByteBuf allocated with alloc.
      Parameters:
      alloc - The allocator used to allocate a new ByteBuf.
      seq - The characters to write into a buffer.
      Returns:
      The ByteBuf which contains the ASCII encoded result.
    • writeAscii

      public static int writeAscii(ByteBuf buf, CharSequence seq)
      Encode a CharSequence in ASCII and write it to a ByteBuf. This method returns the actual number of bytes written.
    • writeAscii

      static int writeAscii(AbstractByteBuf buffer, int writerIndex, CharSequence seq, int len)
    • writeAsciiCharSequence

      private static int writeAsciiCharSequence(AbstractByteBuf buffer, int writerIndex, CharSequence seq, int len)
    • encodeString

      public static ByteBuf encodeString(ByteBufAllocator alloc, CharBuffer src, Charset charset)
      Encode the given CharBuffer using the given Charset into a new ByteBuf which is allocated via the ByteBufAllocator.
    • encodeString

      public static ByteBuf encodeString(ByteBufAllocator alloc, CharBuffer src, Charset charset, int extraCapacity)
      Encode the given CharBuffer using the given Charset into a new ByteBuf which is allocated via the ByteBufAllocator.
      Parameters:
      alloc - The ByteBufAllocator to allocate ByteBuf.
      src - The CharBuffer to encode.
      charset - The specified Charset.
      extraCapacity - the extra capacity to alloc except the space for decoding.
    • encodeString0

      static ByteBuf encodeString0(ByteBufAllocator alloc, boolean enforceHeap, CharBuffer src, Charset charset, int extraCapacity)
    • decodeString

      static String decodeString(ByteBuf src, int readerIndex, int len, Charset charset)
    • threadLocalDirectBuffer

      public static ByteBuf threadLocalDirectBuffer()
      Returns a cached thread-local direct buffer, if available.
      Returns:
      a cached thread-local direct buffer, if available. null otherwise.
    • getBytes

      public static byte[] getBytes(ByteBuf buf)
      Create a copy of the underlying storage from buf into a byte array. The copy will start at ByteBuf.readerIndex() and copy ByteBuf.readableBytes() bytes.
    • getBytes

      public static byte[] getBytes(ByteBuf buf, int start, int length)
      Create a copy of the underlying storage from buf into a byte array. The copy will start at start and copy length bytes.
    • getBytes

      public static byte[] getBytes(ByteBuf buf, int start, int length, boolean copy)
      Return an array of the underlying storage from buf into a byte array. The copy will start at start and copy length bytes. If copy is true a copy will be made of the memory. If copy is false the underlying storage will be shared, if possible.
    • copy

      public static void copy(AsciiString src, ByteBuf dst)
      Copies the all content of src to a ByteBuf using ByteBuf.writeBytes(byte[], int, int).
      Parameters:
      src - the source string to copy
      dst - the destination buffer
    • copy

      public static void copy(AsciiString src, int srcIdx, ByteBuf dst, int dstIdx, int length)
      Copies the content of src to a ByteBuf using ByteBuf.setBytes(int, byte[], int, int). Unlike the copy(AsciiString, ByteBuf) and copy(AsciiString, int, ByteBuf, int) methods, this method do not increase a writerIndex of dst buffer.
      Parameters:
      src - the source string to copy
      srcIdx - the starting offset of characters to copy
      dst - the destination buffer
      dstIdx - the starting offset in the destination buffer
      length - the number of characters to copy
    • copy

      public static void copy(AsciiString src, int srcIdx, ByteBuf dst, int length)
      Copies the content of src to a ByteBuf using ByteBuf.writeBytes(byte[], int, int).
      Parameters:
      src - the source string to copy
      srcIdx - the starting offset of characters to copy
      dst - the destination buffer
      length - the number of characters to copy
    • prettyHexDump

      public static String prettyHexDump(ByteBuf buffer)
      Returns a multi-line hexadecimal dump of the specified ByteBuf that is easy to read by humans.
    • prettyHexDump

      public static String prettyHexDump(ByteBuf buffer, int offset, int length)
      Returns a multi-line hexadecimal dump of the specified ByteBuf that is easy to read by humans, starting at the given offset using the given length.
    • appendPrettyHexDump

      public static void appendPrettyHexDump(StringBuilder dump, ByteBuf buf)
      Appends the prettified multi-line hexadecimal dump of the specified ByteBuf to the specified StringBuilder that is easy to read by humans.
    • appendPrettyHexDump

      public static void appendPrettyHexDump(StringBuilder dump, ByteBuf buf, int offset, int length)
      Appends the prettified multi-line hexadecimal dump of the specified ByteBuf to the specified StringBuilder that is easy to read by humans, starting at the given offset using the given length.
    • isText

      public static boolean isText(ByteBuf buf, Charset charset)
      Returns true if the given ByteBuf is valid text using the given Charset, otherwise return false.
      Parameters:
      buf - The given ByteBuf.
      charset - The specified Charset.
    • isText

      public static boolean isText(ByteBuf buf, int index, int length, Charset charset)
      Returns true if the specified ByteBuf starting at index with length is valid text using the given Charset, otherwise return false.
      Parameters:
      buf - The given ByteBuf.
      index - The start index of the specified buffer.
      length - The length of the specified buffer.
      charset - The specified Charset.
      Throws:
      IndexOutOfBoundsException - if index + length is greater than buf.readableBytes
    • isAscii

      private static boolean isAscii(ByteBuf buf, int index, int length)
      Returns true if the specified ByteBuf starting at index with length is valid ASCII text, otherwise return false.
      Parameters:
      buf - The given ByteBuf.
      index - The start index of the specified buffer.
      length - The length of the specified buffer.
    • isUtf8

      private static boolean isUtf8(ByteBuf buf, int index, int length)
      Returns true if the specified ByteBuf starting at index with length is valid UTF8 text, otherwise return false.
      Parameters:
      buf - The given ByteBuf.
      index - The start index of the specified buffer.
      length - The length of the specified buffer.
      See Also:
      • UTF-8 Definition
         1. Bytes format of UTF-8
        
         The table below summarizes the format of these different octet types.
         The letter x indicates bits available for encoding bits of the character number.
        
         Char. number range  |        UTF-8 octet sequence
            (hexadecimal)    |              (binary)
         --------------------+---------------------------------------------
         0000 0000-0000 007F | 0xxxxxxx
         0000 0080-0000 07FF | 110xxxxx 10xxxxxx
         0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
         0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
         
         2. Syntax of UTF-8 Byte Sequences
        
         UTF8-octets = *( UTF8-char )
         UTF8-char   = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
         UTF8-1      = %x00-7F
         UTF8-2      = %xC2-DF UTF8-tail
         UTF8-3      = %xE0 %xA0-BF UTF8-tail /
                       %xE1-EC 2( UTF8-tail ) /
                       %xED %x80-9F UTF8-tail /
                       %xEE-EF 2( UTF8-tail )
         UTF8-4      = %xF0 %x90-BF 2( UTF8-tail ) /
                       %xF1-F3 3( UTF8-tail ) /
                       %xF4 %x80-8F 2( UTF8-tail )
         UTF8-tail   = %x80-BF
         
    • readBytes

      static void readBytes(ByteBufAllocator allocator, ByteBuffer buffer, int position, int length, OutputStream out) throws IOException
      Read bytes from the given ByteBuffer into the given OutputStream using the position and length. The position and limit of the given ByteBuffer may be adjusted.
      Throws:
      IOException
    • getBytes

      private static void getBytes(ByteBuffer inBuffer, byte[] in, int inOffset, int inLen, OutputStream out, int outLen) throws IOException
      Throws:
      IOException
    • setLeakListener

      public static void setLeakListener(ResourceLeakDetector.LeakListener leakListener)
      Parameters:
      leakListener - If leakListener is not null, it will be notified once a ByteBuf leak is detected.