/**
   * Compares the two specified buffers as described in {@link
   * ChannelBuffer#compareTo(ChannelBuffer)}. This method is useful when implementing a new buffer
   * type.
   */
  public static int compare(ChannelBuffer bufferA, ChannelBuffer bufferB) {
    final int aLen = bufferA.readableBytes();
    final int bLen = bufferB.readableBytes();
    final int minLength = Math.min(aLen, bLen);
    final int uintCount = minLength >>> 2;
    final int byteCount = minLength & 3;

    int aIndex = bufferA.readerIndex();
    int bIndex = bufferB.readerIndex();

    if (bufferA.order() == bufferB.order()) {
      for (int i = uintCount; i > 0; i--) {
        long va = bufferA.getUnsignedInt(aIndex);
        long vb = bufferB.getUnsignedInt(bIndex);
        if (va > vb) {
          return 1;
        } else if (va < vb) {
          return -1;
        }
        aIndex += 4;
        bIndex += 4;
      }
    } else {
      for (int i = uintCount; i > 0; i--) {
        long va = bufferA.getUnsignedInt(aIndex);
        long vb = swapInt(bufferB.getInt(bIndex)) & 0xFFFFFFFFL;
        if (va > vb) {
          return 1;
        } else if (va < vb) {
          return -1;
        }
        aIndex += 4;
        bIndex += 4;
      }
    }

    for (int i = byteCount; i > 0; i--) {
      short va = bufferA.getUnsignedByte(aIndex);
      short vb = bufferB.getUnsignedByte(bIndex);
      if (va > vb) {
        return 1;
      } else if (va < vb) {
        return -1;
      }
      aIndex++;
      bIndex++;
    }

    return aLen - bLen;
  }
  /**
   * Returns a <a href="http://en.wikipedia.org/wiki/Hex_dump">hex dump</a> of the specified
   * buffer's sub-region.
   */
  public static String hexDump(ChannelBuffer buffer, int fromIndex, int length) {
    if (length < 0) {
      throw new IllegalArgumentException("length: " + length);
    }
    if (length == 0) {
      return "";
    }

    int endIndex = fromIndex + length;
    char[] buf = new char[length << 1];

    int srcIdx = fromIndex;
    int dstIdx = 0;
    for (; srcIdx < endIndex; srcIdx++, dstIdx += 2) {
      System.arraycopy(HEXDUMP_TABLE, buffer.getUnsignedByte(srcIdx) << 1, buf, dstIdx, 2);
    }

    return new String(buf);
  }