Hash Table

A Hash Table implementation in C

C

Project Details

Hash Table

A Hash Table implementation in C.


Author: Afaan Bilal


Compile & Run

gcc src/ht/*.c src/main.c -o main && ./main

Output:

A Hash Table implementation in C

k1: value 1
k2: value 2
k3: value 3

Not present key: (null)
Not present key with default: default

Removed key: (null)
Removed key with default: default

Usage

Include the header:

#include "ht/hash_table.h"

Create a hash table:

HashTable *ht = HashTable_new();

Remember to delete the hash table to free the memory:

HashTable_delete(ht);

Insert an item:

HashTable_insert(ht, "key", "value");

Get the value:

char *v = HashTable_get(ht, "key"); // returns NULL if key not present

Get the value with default:

char *v = HashTable_get_default(ht, "key", "default"); // returns "default" if key not present

Remove an item:

HashTable_remove(ht, "key");

HashTable will automatically resize based upon load (<0.1 to resize down with a minimum size of 50, >0.7 to resize up).

However, you may create a sized table directly if you know how many items you'll be storing beforehand with:

// Creates a hash table with base size 100 (actual size will be a prime number >= 100)
HashTable *ht = HashTable_new_sized(100);

You may also manually resize the table up / down by:

// Resize to roughly double the current size
HashTable_resize_up(ht);

// Resize to roughly half the current size (unless size is already minimum)
HashTable_resize_down(ht);

Contributing

All contributions are welcome. Please create an issue first for any feature request
or bug. Then fork the repository, create a branch and make any changes to fix the bug
or add the feature and create a pull request. That's it!
Thanks!


License

Hash Table is released under the MIT License.
Check out the full license here.

License

MIT License

Copyright (c) 2023 Afaan Bilal

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.