External Hash Table Library for String-to-String Dictionaries in C++
Below is a complete implementation of an external hash table library that stores string-to-string dictionaries using separate index and data files. This implementation handles variable-sized records and provides basic dictionary operations.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <functional>
#include <filesystem>
#include <cstdint>
#include <stdexcept>
namespace fs = std::filesystem;
class ExternalHashTable {
private:
std::string index_filename;
std::string data_filename;
size_t bucket_count;
std::hash<std::string> hasher;
// Structure for index entry
struct IndexEntry {
uint64_t key_hash;
uint64_t data_position;
uint32_t key_length;
uint32_t value_length;
};
// Open files in binary mode
std::fstream open_file(const std::string& filename, std::ios_base::openmode mode) {
std::fstream file;
file.open(filename, mode | std::ios::binary);
if (!file.is_open()) {
throw std::runtime_error("Failed to open file: " + filename);
}
return file;
}
// Initialize new files
void initialize_files() {
// Create index file with initial empty buckets
std::ofstream index_file(index_filename, std::ios::binary | std::ios::trunc);
if (!index_file) {
throw std::runtime_error("Failed to create index file");
}
// Initialize all buckets as empty (0 data position)
IndexEntry empty_entry = {0, 0, 0, 0};
for (size_t i = 0; i < bucket_count; ++i) {
index_file.write(reinterpret_cast<const char*>(&empty_entry), sizeof(IndexEntry));
}
// Create empty data file
std::ofstream data_file(data_filename, std::ios::binary | std::ios::trunc);
if (!data_file) {
throw std::runtime_error("Failed to create data file");
}
}
// Compute hash and bucket index
size_t get_bucket_index(const std::string& key) const {
size_t hash = hasher(key);
return hash % bucket_count;
}
// Read index entry from file
IndexEntry read_index_entry(std::fstream& index_file, size_t bucket_index) {
IndexEntry entry;
index_file.seekg(bucket_index * sizeof(IndexEntry));
index_file.read(reinterpret_cast<char*>(&entry), sizeof(IndexEntry));
return entry;
}
// Write index entry to file
void write_index_entry(std::fstream& index_file, size_t bucket_index, const IndexEntry& entry) {
index_file.seekp(bucket_index * sizeof(IndexEntry));
index_file.write(reinterpret_cast<const char*>(&entry), sizeof(IndexEntry));
}
// Read string from data file
std::string read_string(std::fstream& data_file, uint64_t position, uint32_t length) {
std::string str(length, '\0');
data_file.seekg(position);
data_file.read(&str[0], length);
return str;
}
// Write string to data file and return position
uint64_t write_string(std::fstream& data_file, const std::string& str) {
uint64_t position = data_file.tellp();
data_file.write(str.c_str(), str.size());
return position;
}
public:
// Constructor
ExternalHashTable(const std::string& index_file, const std::string& data_file, size_t initial_buckets = 1024)
: index_filename(index_file), data_filename(data_file), bucket_count(initial_buckets) {
// Check if files exist
bool index_exists = fs::exists(index_filename);
bool data_exists = fs::exists(data_filename);
if (!index_exists || !data_exists) {
if (index_exists) fs::remove(index_filename);
if (data_exists) fs::remove(data_filename);
initialize_files();
}
}
// Insert or update a key-value pair
void insert(const std::string& key, const std::string& value) {
auto index_file = open_file(index_filename, std::ios::in | std::ios::out);
auto data_file = open_file(data_filename, std::ios::in | std::ios::out | std::ios::app);
size_t bucket_index = get_bucket_index(key);
IndexEntry entry = read_index_entry(index_file, bucket_index);
// Check if key already exists
if (entry.data_position != 0) {
// Read existing key to check for match
std::string existing_key = read_string(data_file, entry.data_position, entry.key_length);
if (existing_key == key) {
// Key exists, update the value
uint64_t value_position = entry.data_position + entry.key_length;
data_file.seekp(value_position);
data_file.write(value.c_str(), value.size());
// Update value length in index
entry.value_length = static_cast<uint32_t>(value.size());
write_index_entry(index_file, bucket_index, entry);
return;
}
}
// Key doesn't exist or is in a different bucket (collision)
// Append new record to data file
uint64_t key_position = write_string(data_file, key);
uint64_t value_position = write_string(data_file, value);
// Create new index entry
IndexEntry new_entry;
new_entry.key_hash = hasher(key);
new_entry.data_position = key_position;
new_entry.key_length = static_cast<uint32_t>(key.size());
new_entry.value_length = static_cast<uint32_t>(value.size());
// Write to index
write_index_entry(index_file, bucket_index, new_entry);
}
// Find a value by key
bool find(const std::string& key, std::string& value) {
auto index_file = open_file(index_filename, std::ios::in);
auto data_file = open_file(data_filename, std::ios::in);
size_t bucket_index = get_bucket_index(key);
IndexEntry entry = read_index_entry(index_file, bucket_index);
if (entry.data_position == 0) {
return false; // Bucket is empty
}
// Read the key from data file
std::string stored_key = read_string(data_file, entry.data_position, entry.key_length);
if (stored_key == key) {
// Key matches, read the value
uint64_t value_position = entry.data_position + entry.key_length;
value = read_string(data_file, value_position, entry.value_length);
return true;
}
return false; // Key not found (collision or wrong key)
}
// Remove a key-value pair
bool remove(const std::string& key) {
auto index_file = open_file(index_filename, std::ios::in | std::ios::out);
auto data_file = open_file(data_filename, std::ios::in | std::ios::out);
size_t bucket_index = get_bucket_index(key);
IndexEntry entry = read_index_entry(index_file, bucket_index);
if (entry.data_position == 0) {
return false; // Bucket is empty
}
// Read the key from data file
std::string stored_key = read_string(data_file, entry.data_position, entry.key_length);
if (stored_key == key) {
// Key matches, mark as empty
IndexEntry empty_entry = {0, 0, 0, 0};
write_index_entry(index_file, bucket_index, empty_entry);
return true;
}
return false; // Key not found
}
// Get the number of buckets
size_t size() const {
return bucket_count;
}
// Resize the hash table (not implemented for simplicity)
// In a production environment, you would need to implement rehashing
void resize(size_t new_size) {
throw std::runtime_error("Resize not implemented in this example");
}
};
How to Use the Library
Here's an example of how to use the ExternalHashTable class:
int main() {
try {
// Create or open hash table files
ExternalHashTable dict("dictionary.idx", "dictionary.dat");
// Insert some key-value pairs
dict.insert("name", "John Doe");
dict.insert("age", "30");
dict.insert("city", "New York");
// Retrieve values
std::string value;
if (dict.find("name", value)) {
std::cout << "Name: " << value << std::endl;
}
if (dict.find("age", value)) {
std::cout << "Age: " << value << std::endl;
}
// Update a value
dict.insert("age", "31");
// Verify update
if (dict.find("age", value)) {
std::cout << "Updated Age: " << value << std::endl;
}
// Remove a key
dict.remove("city");
// Try to find removed key
if (!dict.find("city", value)) {
std::cout << "City not found (as expected)" << std::endl;
}
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
return 0;
}
Key Features
-
Separate Index and Data Files: The implementation uses two separate files - one for the index (hash table structure) and one for the actual data.
-
Variable-Sized Records: The library handles strings of any length by storing them in the data file and recording their positions and lengths in the index.
-
Basic Operations: Supports insert, find, and remove operations.
-
Collision Handling: Uses simple separate chaining (though in this basic implementation, collisions will overwrite existing entries).
-
File Management: Automatically creates files if they don't exist and initializes them properly.
Limitations and Possible Improvements
-
Collision Handling: The current implementation doesn't properly handle collisions. A production version would need to implement proper collision resolution (like separate chaining or open addressing).
-
Resizing: The resize functionality is not implemented. In a real-world scenario, you would need to implement rehashing when the load factor becomes too high.
-
Error Handling: While basic error handling is present, a production version would need more robust error checking.
-
Performance: For better performance, you might want to implement caching of frequently accessed entries.
-
Concurrency: This implementation isn't thread-safe. For concurrent access, you would need to add proper synchronization mechanisms.
This implementation provides a solid foundation that you can build upon to create a more robust external hash table library.