# This class contains simple util methods.
class ByteIterableUtil
  # Compares two buffers.
  #
  # @param key1 first ByteIterable.
  # @param key2 second ByteIterable.
  # @return > 0 of key1 > key2, < 0 if key1 < key2 and 0 if they are equal.
  @compare$ByteIterable$ByteIterable: (key1, key2) ->
    return @compare$Buffer$int$Buffer$int key1.getBytesUnsafe(),
            key1.getLength(), key2.getBytesUnsafe(), key2.getLength()

  # Compares two buffers.
  #
  # @param key1 first buffer.
  # @param len1 length of first buffer.
  # @param key2 second buffer.
  # @param len2 length of second buffer.
  # @return > 0 of key1 > key2, < 0 if key1 < key2 and 0 if they are equal.
  @compare$Buffer$int$Buffer$int: (key1, len1, key2, len2) ->
    min = Math.min(len1, len2)
    for i in [0..min - 1]
      b1 = key1[i]
      b2 = key2[i]
      if (b1 != b2)
        return (b1 & 0xff) - (b2 & 0xff)
    return (len1 - len2)

  # Compares two buffers.
  #
  # @param key1 first buffer.
  # @param len1 length of first buffer.
  # @param offset1 offset inside first buffer.
  # @param key2 second buffer.
  # @param len2 length of second buffer.
  # @return > 0 of key1 > key2, < 0 if key1 < key2 and 0 if they are equal.
  @compare$Buffer$int$int$Buffer$int: (key1, len1, offset1, key2, len2) ->
    min = Math.min(len1 - offset1, len2)
    for i in [0..min - 1]
      b1 = key1[i + offset1]
      b2 = key2[i]
      if (b1 != b2)
        return (b1 & 0xff) - (b2 & 0xff)
    return (len1 - offset1 - len2)

exports.ByteIterableUtil = ByteIterableUtil
