| 1 | #include "xgdbm.hh" |
|---|
| 2 | #include <errno.h> |
|---|
| 3 | #include <string.h> |
|---|
| 4 | #include <sys/types.h> |
|---|
| 5 | #include <sys/stat.h> |
|---|
| 6 | #include <fcntl.h> |
|---|
| 7 | #include <iostream> |
|---|
| 8 | |
|---|
| 9 | #include "namespaces.hh" |
|---|
| 10 | |
|---|
| 11 | GDBM_FILE XGDBMWrapper::s_db; |
|---|
| 12 | int XGDBMWrapper::s_usecount; |
|---|
| 13 | |
|---|
| 14 | XGDBMWrapper::XGDBMWrapper(const string &fname, Mode mode) |
|---|
| 15 | { |
|---|
| 16 | if(!s_db) { |
|---|
| 17 | s_db = gdbm_open(const_cast<char *>(fname.c_str()), 2048, |
|---|
| 18 | mode==ReadWrite ? GDBM_WRITER|GDBM_WRCREAT|GDBM_FAST : GDBM_READER, |
|---|
| 19 | 0666 , 0); |
|---|
| 20 | if(!s_db) |
|---|
| 21 | throw XDBException("Unable to open database: "+string(strerror(errno))); |
|---|
| 22 | } |
|---|
| 23 | s_usecount++; |
|---|
| 24 | } |
|---|
| 25 | |
|---|
| 26 | XGDBMWrapper::~XGDBMWrapper() |
|---|
| 27 | { |
|---|
| 28 | if(!--s_usecount) { |
|---|
| 29 | cerr<<"Closing down"<<endl; |
|---|
| 30 | gdbm_close(s_db); |
|---|
| 31 | } |
|---|
| 32 | } |
|---|
| 33 | |
|---|
| 34 | bool XGDBMWrapper::get(const string &key, string &value) |
|---|
| 35 | { |
|---|
| 36 | datum kdatum={const_cast<char *>(key.c_str()),key.size()+1}; |
|---|
| 37 | |
|---|
| 38 | datum vdatum=gdbm_fetch(s_db,kdatum); |
|---|
| 39 | if(!vdatum.dptr) |
|---|
| 40 | return false; |
|---|
| 41 | value.assign(vdatum.dptr,vdatum.dsize); |
|---|
| 42 | free(vdatum.dptr); |
|---|
| 43 | return true; |
|---|
| 44 | } |
|---|
| 45 | |
|---|
| 46 | void XGDBMWrapper::put(const string &key, const string &value) |
|---|
| 47 | { |
|---|
| 48 | datum kdatum={const_cast<char *>(key.c_str()),key.size()+1}; |
|---|
| 49 | datum vdatum={const_cast<char *>(value.c_str()),value.size()}; |
|---|
| 50 | if(gdbm_store(s_db, kdatum, vdatum,GDBM_REPLACE)<0) |
|---|
| 51 | throw XDBException("Error storing key: "+string(strerror(errno))); |
|---|
| 52 | |
|---|
| 53 | } |
|---|
| 54 | |
|---|
| 55 | void XGDBMWrapper::del(const string &key) |
|---|
| 56 | { |
|---|
| 57 | } |
|---|
| 58 | |
|---|
| 59 | #ifdef TESTDRIVER |
|---|
| 60 | main() |
|---|
| 61 | { |
|---|
| 62 | try { |
|---|
| 63 | XDBWrapper *xdb=new XGDBMWrapper("wuh",XDBWrapper::ReadWrite); |
|---|
| 64 | xdb->put("ahu","toffe gast"); |
|---|
| 65 | xdb->append("ahu",", echt waar!"); |
|---|
| 66 | |
|---|
| 67 | string tst; |
|---|
| 68 | xdb->get("ahu",tst); |
|---|
| 69 | cout<<"Database zegt over ahu: '"<<tst<<"'"<<endl; |
|---|
| 70 | |
|---|
| 71 | xdb->append("ahu"," Toch niet!"); |
|---|
| 72 | xdb->get("ahu",tst); |
|---|
| 73 | cout<<"Database zegt over ahu: '"<<tst<<"'"<<endl; |
|---|
| 74 | delete xdb; |
|---|
| 75 | } |
|---|
| 76 | catch(XDBException &e) { |
|---|
| 77 | cerr<<"Fatal error: "<<e.what<<endl; |
|---|
| 78 | } |
|---|
| 79 | |
|---|
| 80 | } |
|---|
| 81 | |
|---|
| 82 | #endif /* TESTDRIVER */ |
|---|