5 // Databases (hash tables)
6 const int DB_BUCKETS = 8192;
7 void db_save(int db, string filename)
9 int fh = fopen(filename, FILE_WRITE);
12 LOG_WARNINGF("^1Can't write DB to %s\n", filename);
15 fputs(fh, strcat(ftos(DB_BUCKETS), "\n"));
16 for (int i = 0, n = buf_getsize(db); i < n; ++i)
17 fputs(fh, strcat(bufstr_get(db, i), "\n"));
27 #define HM_NEW(this) (this = db_create())
29 void db_put(int db, string key, string value);
31 int db_load(string filename)
33 int db = buf_create();
34 if (db < 0) return -1;
35 int fh = fopen(filename, FILE_READ);
36 if (fh < 0) return db;
38 if (stoi(l) == DB_BUCKETS)
40 for (int i = 0; (l = fgets(fh)); ++i)
42 if (l != "") bufstr_set(db, i, l);
47 // different count of buckets, or a dump?
48 // need to reorganize the database then (SLOW)
50 // note: we also parse the first line (l) in case the DB file is
51 // missing the bucket count
54 int n = tokenizebyseparator(l, "\\");
55 for (int j = 2; j < n; j += 2)
56 db_put(db, argv(j - 1), uri_unescape(argv(j)));
58 while ((l = fgets(fh)));
64 void db_dump(int db, string filename)
66 int fh = fopen(filename, FILE_WRITE);
67 if (fh < 0) LOG_FATALF("Can't dump DB to %s\n");
69 for (int i = 0, n = buf_getsize(db); i < n; ++i)
71 int m = tokenizebyseparator(bufstr_get(db, i), "\\");
72 for (int j = 2; j < m; j += 2)
73 fputs(fh, strcat("\\", argv(j - 1), "\\", argv(j), "\n"));
82 #define HM_DELETE(this) db_close(this)
84 string db_get(int db, string key)
86 int h = crc16(false, key) % DB_BUCKETS;
87 return uri_unescape(infoget(bufstr_get(db, h), key));
89 #define HM_gets(this, k) db_get(this, k)
91 #define db_remove(db, key) db_put(db, key, "")
93 void db_put(int db, string key, string value)
95 int h = crc16(false, key) % DB_BUCKETS;
96 bufstr_set(db, h, infoadd(bufstr_get(db, h), key, uri_escape(value)));
98 #define HM_sets(this, key, val) db_put(this, key, val)
102 LOG_INFO("LOAD...\n");
103 int db = db_load("foo.db");
104 LOG_INFO("LOADED. FILL...\n");
105 for (int i = 0; i < DB_BUCKETS; ++i)
106 db_put(db, ftos(random()), "X");
107 LOG_INFO("FILLED. SAVE...\n");
108 db_save(db, "foo.db");
109 LOG_INFO("SAVED. CLOSE...\n");
111 LOG_INFO("CLOSED.\n");