Example #1
0
static void
mt_hash_insert_pair(MtHash* hash, MtPair* pair)
{
  assert(hash != NULL);
  assert(pair != NULL);

  size_t index = pair->key->hash % hash->size;
  MtPair* element = hash->buckets[index];

  // No Collision
  if (element == NULL)
  {
    hash->buckets[index] = pair;
    ++hash->length;

    // Expand the hash if necessary
    if (hash->length >= 0.75 * hash->size)
      mt_hash_double_size(hash);
  }

  // Collision handling, linear probing
  while (element != NULL)
  {
    // Key already exists in the hash, replace the value
    if (mt_string_compare(element->key, pair->key) == 0)
    {
      hash->buckets[index] = pair;
      return;
    }

    ++index;
    index %= hash->size;
    element = hash->buckets[index];
  }
}
Example #2
0
void
mt_hash_remove(MtHash* hash, MtString* key)
{
  assert(hash != NULL);
  assert(key != NULL);

  if (key->hash == 0)
    key->hash = Murmur3(mt_string_get_utf8(key), mt_string_get_length(key));

  size_t index = key->hash % hash->size;
  MtPair* element = hash->buckets[index];

  while (element != NULL)
  {
    if (mt_string_compare(key, element->key) == 0)
    {
      hash->buckets[index] = NULL;
      --hash->length;
      return;
    }

    ++index;
    index %= hash->size;
    element = hash->buckets[index];
  }
}
Example #3
0
MtPair* mt_hash_search(MtHash* hash, MtString* key)
{
  assert(hash != NULL);
  assert(key != NULL);

  if (key->hash == 0)
    key->hash = Murmur3(mt_string_get_utf8(key), mt_string_get_length(key));

  size_t index = key->hash % hash->size;

  MtHashElement* element = &hash->buckets[index];
  assert(element != NULL);

  // Key Collides
  if (element->data != NULL)
  {
    // If it is a tree, search the tree for the key
    if (element->is_tree)
    {
      return mt_tree_search((MtTree*) element->data, key);
    }
    else if (mt_string_compare(((MtPair*) element->data)->key, key) == 0)
    {
      return (MtPair*) element->data;
    }
  }

  // Nothing was found
  return NULL;
}
Example #4
0
MtPair* mt_hash_search(MtHash* hash, MtString* key)
{
  assert(hash != NULL);
  assert(key != NULL);

  if (key->hash == 0)
    key->hash = Murmur3(mt_string_get_utf8(key), mt_string_get_length(key));

  size_t index = key->hash % hash->size;
  MtPair* element = hash->buckets[index];

  while (element != NULL)
  {
    if (mt_string_compare(key, element->key) == 0)
      return element;

    ++index;
    index %= hash->size;
    element = hash->buckets[index];
  }

  // Nothing was found
  return NULL;
}