#include <string.h>

#include "key-map.h"

const struct sigsum_pubkey *
sigsum_key_map_lookup (const struct sigsum_key_map *map,
		       const struct sigsum_hash *key_hash,
		       size_t *idx)
{
  size_t i;

  /* Do a linear search for a hash with matching first byte. In the
     typical case, there will only be a single iteration of the below
     memcmp loop. Could be changed to use binary search, but that is
     likely overkill. */
  for (i = 0; i < map->num_keys && map->keys[i].hash.h[0] < key_hash->h[0]; i++)
    ;
  for (; i < map->num_keys; i++)
    {
      int c = memcmp (map->keys[i].hash.h, key_hash->h, sizeof (key_hash->h));
      if (!c)
	{
	  if (idx)
	    *idx = i;
	  return &map->keys[i].key;
	}
      if (c > 0)
	break;
    }
  return NULL;
}
