#pragma once
#include <map>
#include <cstdio>
#ifdef _WIN32
#include <sys/stat.h>
#else
#endif
template<typename Key,typename Value>
class MapStream
{
public:
std::map<Key,Value> m_mapTable;
typedef typename std::map<Key,Value>::iterator MapStreamIterator;
int GetFileSize(const char* filename)
{
struct stat f_stat;
if (stat(filename, &f_stat) == -1) {
return -1;
}
return f_stat.st_size;
}
bool Load(const char* filename)
{
FILE* fp = fopen(filename,"rb");
if (fp ==NULL)
return false;
int metasize = sizeof(Key) + sizeof(Value);
char buffer[sizeof(Key) + sizeof(Value)];
int readed;
Key* _key;
Value* _value;
m_mapTable.clear();
while (fread(buffer,1,metasize,fp)==metasize)
{
_key = (Key*)buffer;
_value = (Value*)&buffer[sizeof(Key)];
m_mapTable[*_key] = *_value;
}
fclose(fp);
return (GetFileSize(filename) == (m_mapTable.size()*metasize));
}
bool Save(const char* filename)
{
FILE* fp = fopen(filename,"wb");
if (fp ==NULL)
return false;
int metasize = sizeof(Key) + sizeof(Value);
char buffer[sizeof(Key) + sizeof(Value)];
int readed;
Key* _key;
Value* _value;
MapStreamIterator iter = m_mapTable.begin();
while (iter!=m_mapTable.end())
{
fwrite(&iter->first, 1,sizeof(Key),fp);
fwrite(&iter->second,1,sizeof(Value),fp);
iter++;
}
fclose(fp);
int filesize = GetFileSize(filename);
return (GetFileSize(filename) == (m_mapTable.size()*metasize));
}
Value& operator[] (const Key& _key)
{
return m_mapTable[_key];
}
Value* GetValue(const Key& _key)
{
MapStreamIterator iter = m_mapTable.find(_key);
if (iter!=m_mapTable.end())
return &iter->second;
return NULL;
}
void SetValue(const Key& _key,const Value& _value)
{
m_mapTable[_key] = _value;
}
void RemoveKey(const Key& _key)
{
m_mapTable.erase(_key);
}
int Count()
{
return m_mapTable.size();
}
};