#include "ExternalHashTable.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <stdexcept>
#include <filesystem> // C++17 for directory operations
#include <sstream>
namespace external_hash_table {
ExternalHashTable::ExternalHashTable(const std::string& baseFilename, size_t tableSize, float loadFactor)
: baseFilename(baseFilename),
dataFilename(baseFilename + ".data"),
indexFilename(baseFilename + ".index"),
tableSize(tableSize),
loadFactor(loadFactor),
numEntries(0) {
// Create data and index files if they don't exist
std::fstream dataFileStream(dataFilename, std::ios::app); // creates if doesn't exist
dataFileStream.close();
std::fstream indexFileStream(indexFilename, std::ios::app); // creates if doesn't exist
indexFileStream.close();
// Open files in appropriate modes
dataFile.open(dataFilename, std::ios::in | std::ios::out | std::ios::binary); // read and write
indexFile.open(indexFilename, std::ios::in | std::ios::out | std::ios::binary); // read and write
if (!dataFile.is_open() || !indexFile.is_open()) {
throw std::runtime_error("Could not open data or index file.");
}
// Initialize the index table
indexTable.resize(tableSize, { -1, false }); // Initialize with offset -1 and not deleted.
// Load the index table from the index file if it exists. Otherwise, create a new index file.
if (std::filesystem::file_size(indexFilename) > 0) {
indexFile.seekg(0, std::ios::beg);
for (size_t i = 0; i < tableSize; ++i) {
indexFile.read(reinterpret_cast<char*>(&indexTable[i].offset), sizeof(long long));
indexFile.read(reinterpret_cast<char*>(&indexTable[i].deleted), sizeof(bool));
}
//Recalculate number of entries. Iterate through the index file and count non-deleted entries
numEntries = 0;
for (size_t i = 0; i < tableSize; ++i) {
if(indexTable[i].offset != -1 && !indexTable[i].deleted){
numEntries++;
}
}
}
else {
// Create a new index file (all entries are initially empty/invalid)
indexFile.seekp(0, std::ios::beg);
for (size_t i = 0; i < tableSize; ++i) {
indexFile.write(reinterpret_cast<char*>(&indexTable[i].offset), sizeof(long long));
indexFile.write(reinterpret_cast<char*>(&indexTable[i].deleted), sizeof(bool));
}
indexFile.flush();
}
}
ExternalHashTable::~ExternalHashTable() {
close();
}
void ExternalHashTable::close() {
if (dataFile.is_open()) dataFile.close();
if (indexFile.is_open()) indexFile.close();
}
size_t ExternalHashTable::hash(const std::string& key) const {
// djb2 hash function
size_t hashValue = 5381;
for (char c : key) {
hashValue = ((hashValue << 5) + hashValue) + c; // hash * 33 + c
}
return hashValue;
}
size_t ExternalHashTable::getBucketIndex(const std::string& key) const {
return hash(key) % tableSize;
}
long long ExternalHashTable::allocateRecord(const std::string& key, const std::string& value) {
// Serialize the key-value pair into a string: key<TAB>value<NULL>
std::string record = key + FIELD_SEPARATOR + value + RECORD_SEPARATOR;
// Get the current end position of the data file
dataFile.seekp(0, std::ios::end);
long long offset = dataFile.tellp();
// Write the record to the data file
dataFile.write(record.c_str(), record.length());
dataFile.flush();
return offset;
}
std::pair<std::string, std::string> ExternalHashTable::readRecord(long long offset) {
dataFile.seekg(offset, std::ios::beg);
std::string key = readUntilSeparator(dataFile, FIELD_SEPARATOR);
std::string value = readUntilSeparator(dataFile, RECORD_SEPARATOR);
return { key, value };
}
std::string ExternalHashTable::readUntilSeparator(std::fstream& file, char separator) {
std::string result;
char c;
while (file.get(c)) {
if (c == separator) {
break;
}
result += c;
}
return result;
}
void ExternalHashTable::updateRecord(long long offset, const std::string& key, const std::string& value) {
//For simplicity, we'll implement it as delete and insert. More efficient implementation would involve checking sizes.
deleteRecord(offset);
allocateRecord(key, value); //This will put it at the *end* of the data file. The index will need to be updated.
}
void ExternalHashTable::deleteRecord(long long offset) {
// We don't actually delete the data from the data file; we just mark the index entry as deleted.
// Other implementations may overwrite the data with a special "deleted" marker in the datafile.
// This implementation will cause the data file to grow indefinitely, but avoid complications with re-writing parts of the data file.
//This implementation doesn't actually touch the data file. The data is left as is. The index file is updated to mark the entry as deleted.
//Other implementations may choose to overwrite the data in the data file with a special "deleted" marker.
//The index entry will be marked as deleted in the index table.
//Find the corresponding bucket
for(size_t i = 0; i < tableSize; i++){
if(indexTable[i].offset == offset && !indexTable[i].deleted){ //Found it.
indexTable[i].deleted = true;
indexFile.seekp(i * (sizeof(long long) + sizeof(bool)), std::ios::beg);
indexFile.write(reinterpret_cast<char*>(&indexTable[i].offset), sizeof(long long));
indexFile.write(reinterpret_cast<char*>(&indexTable[i].deleted), sizeof(bool));
indexFile.flush();
numEntries--;
return;
}
}
//If not found, then the data was already deleted or did not exist.
}
size_t ExternalHashTable::findNextAvailableBucket(size_t bucketIndex) const {
size_t currentIndex = bucketIndex;
do {
if (indexTable[currentIndex].offset == -1 || indexTable[currentIndex].deleted) {
return currentIndex;
}
currentIndex = (currentIndex + 1) % tableSize; // Linear probing
} while (currentIndex != bucketIndex); // Stop if we've searched the whole table
throw std::runtime_error("Hash table is full."); // Should trigger a resize in a real implementation
}
size_t ExternalHashTable::findExistingBucket(const std::string& key, size_t& initialBucket) const {
initialBucket = getBucketIndex(key);
size_t currentIndex = initialBucket;
do {
if (indexTable[currentIndex].offset != -1 && !indexTable[currentIndex].deleted) {
long long offset = indexTable[currentIndex].offset;
std::pair<std::string, std::string> record = readRecord(offset);
if (record.first == key) {
return currentIndex;
}
}
currentIndex = (currentIndex + 1) % tableSize; // Linear probing
} while (currentIndex != initialBucket && (indexTable[currentIndex].offset != -1)); //Check if we wrapped around and if it is empty
return tableSize; // Not found
}
void ExternalHashTable::insert(const std::string& key, const std::string& value) {
checkAndResize(); // Check for resize condition before inserting
size_t bucketIndex = getBucketIndex(key);
size_t initialBucket = bucketIndex; // Save the initial bucket for collision resolution check
// Check if the key already exists
size_t existingBucket = findExistingBucket(key, initialBucket);
if (existingBucket != tableSize) {
// Key already exists, update the value
updateRecord(indexTable[existingBucket].offset, key, value);
return;
}
// Find the next available bucket using linear probing
bucketIndex = findNextAvailableBucket(bucketIndex);
// Allocate space in the data file and get the offset
long long offset = allocateRecord(key, value);
// Update the index table
indexTable[bucketIndex].offset = offset;
indexTable[bucketIndex].deleted = false;
// Write the updated index entry to the index file
indexFile.seekp(bucketIndex * (sizeof(long long) + sizeof(bool)), std::ios::beg);
indexFile.write(reinterpret_cast<char*>(&indexTable[bucketIndex].offset), sizeof(long long));
indexFile.write(reinterpret_cast<char*>(&indexTable[bucketIndex].deleted), sizeof(bool));
indexFile.flush();
numEntries++; // Increment the number of entries
}
std::string ExternalHashTable::get(const std::string& key) {
size_t initialBucket; // Will be populated by findExistingBucket
size_t bucketIndex = findExistingBucket(key, initialBucket);
if (bucketIndex != tableSize) {
long long offset = indexTable[bucketIndex].offset;
return readRecord(offset).second;
}
else {
throw std::out_of_range("Key not found.");
}
}
void ExternalHashTable::remove(const std::string& key) {
size_t initialBucket; // Will be populated by findExistingBucket
size_t bucketIndex = findExistingBucket(key, initialBucket);
if (bucketIndex != tableSize) {
deleteRecord(indexTable[bucketIndex].offset);
indexTable[bucketIndex].offset = -1; //reset offset in index table
indexTable[bucketIndex].deleted = true;
indexFile.seekp(bucketIndex * (sizeof(long long) + sizeof(bool)), std::ios::beg);
indexFile.write(reinterpret_cast<char*>(&indexTable[bucketIndex].offset), sizeof(long long));
indexFile.write(reinterpret_cast<char*>(&indexTable[bucketIndex].deleted), sizeof(bool));
indexFile.flush();
}
}
bool ExternalHashTable::contains(const std::string& key) {
size_t initialBucket; // Will be populated by findExistingBucket
size_t bucketIndex = findExistingBucket(key, initialBucket);
return bucketIndex != tableSize;
}
void ExternalHashTable::clear() {
//Reset everything to defaults, as if the hash table was just created.
//Does *not* delete the underlying data or index files.
//Clear the index table
indexTable.clear();
indexTable.resize(tableSize, { -1, false });
//Write the cleared table to the index file.
indexFile.seekp(0, std::ios::beg);
for (size_t i = 0; i < tableSize; ++i) {
indexFile.write(reinterpret_cast<char*>(&indexTable[i].offset), sizeof(long long));
indexFile.write(reinterpret_cast<char*>(&indexTable[i].deleted), sizeof(bool));
}
indexFile.flush();
numEntries = 0;
}
void ExternalHashTable::checkAndResize() {
if (static_cast<float>(numEntries) / tableSize > loadFactor) {
resizeTable();
}
}
void ExternalHashTable::resizeTable() {
// Save the current state
std::vector<IndexEntry> oldIndexTable = indexTable;
size_t oldTableSize = tableSize;
// Double the table size (or use a better strategy)
tableSize *= 2;
indexTable.resize(tableSize, { -1, false });
//Re-initialize index file
indexFile.seekp(0, std::ios::beg);
for (size_t i = 0; i < tableSize; ++i) {
indexFile.write(reinterpret_cast<char*>(&indexTable[i].offset), sizeof(long long));
indexFile.write(reinterpret_cast<char*>(&indexTable[i].deleted), sizeof(bool));
}
indexFile.flush();
// Reset the number of entries
numEntries = 0;
//Rehash and insert the old entries into the new table
for (size_t i = 0; i < oldTableSize; ++i) {
if (oldIndexTable[i].offset != -1 && !oldIndexTable[i].deleted) {
std::pair<std::string, std::string> record = readRecord(oldIndexTable[i].offset);
insert(record.first, record.second); // Re-insert into the new table, which will rehash them
}
}
std::cout << "Resized hash table to size: " << tableSize << std::endl;
}
void ExternalHashTable::printStats(){
std::cout << "Hash Table Statistics:" << std::endl;
std::cout << " Base Filename: " << baseFilename << std::endl;
std::cout << " Data Filename: " << dataFilename << std::endl;
std::cout << " Index Filename: " << indexFilename << std::endl;
std::cout << " Table Size: " << tableSize << std::endl;
std::cout << " Load Factor: " << loadFactor << std::endl;
std::cout << " Number of Entries: " << numEntries << std::endl;
std::cout << " Current Load: " << static_cast<float>(numEntries) / tableSize << std::endl;
}
} // namespace external_hash_table