#include <string.h>

#include "sort-internal.h"

static int
hash_cmp (const void *ap, const void *bp)
{
  const struct sigsum_hash *a = ap;
  const struct sigsum_hash *b = bp;
  return memcmp (a->h, b->h, sizeof (a->h));
}

bool
_sigsum_sort_by_hash (size_t n, size_t elem_size,
		      struct sigsum_hash *hashes)
{
  qsort (hashes, n, elem_size, hash_cmp);

  /* Check for duplicates. */
  const char *start = (const char *) hashes;
  for (size_t i = 1; i < n; i++)
    {
      const struct sigsum_hash *hash =
	(const struct sigsum_hash *) (start + i*elem_size);
      const struct sigsum_hash *prev_hash =
	(const struct sigsum_hash *) (start + (i-1)*elem_size);

      if (memcmp (prev_hash->h, hash->h, sizeof (hash->h)) == 0)
	return false;
    }
  return true;
}
