5 // Databases (hash tables)
6 const int DB_BUCKETS = 8192;
8 void db_save(int db, string filename)
10 int fh = fopen(filename, FILE_WRITE);
13 LOG_WARNF("^1Can't write DB to %s", filename);
16 fputs(fh, strcat(ftos(DB_BUCKETS), "\n"));
17 for (int i = 0, n = buf_getsize(db); i < n; ++i)
18 fputs(fh, strcat(bufstr_get(db, i), "\n"));
29 #define HM_NEW(this) (this = db_create())
32 void db_put(int db, string key, string value);
35 int db_load(string filename)
37 int db = buf_create();
38 if (db < 0) return -1;
39 int fh = fopen(filename, FILE_READ);
40 if (fh < 0) return db;
42 if (stoi(l) == DB_BUCKETS)
44 for (int i = 0; (l = fgets(fh)); ++i)
46 if (l != "") bufstr_set(db, i, l);
51 // different count of buckets, or a dump?
52 // need to reorganize the database then (SLOW)
54 // note: we also parse the first line (l) in case the DB file is
55 // missing the bucket count
58 int n = tokenizebyseparator(l, "\\");
59 for (int j = 2; j < n; j += 2)
60 db_put(db, argv(j - 1), uri_unescape(argv(j)));
62 while ((l = fgets(fh)));
69 void db_dump(int db, string filename)
71 int fh = fopen(filename, FILE_WRITE);
72 if (fh < 0) LOG_FATALF("Can't dump DB to %s");
74 for (int i = 0, n = buf_getsize(db); i < n; ++i)
76 int m = tokenizebyseparator(bufstr_get(db, i), "\\");
77 for (int j = 2; j < m; j += 2)
78 fputs(fh, strcat("\\", argv(j - 1), "\\", argv(j), "\n"));
88 #define HM_DELETE(this) db_close(this)
91 string db_get(int db, string key)
93 int h = crc16(false, key) % DB_BUCKETS;
94 return uri_unescape(infoget(bufstr_get(db, h), key));
96 #define HM_gets(this, k) db_get(this, k)
98 #define db_remove(db, key) db_put(db, key, "")
101 void db_put(int db, string key, string value)
103 int h = crc16(false, key) % DB_BUCKETS;
104 bufstr_set(db, h, infoadd(bufstr_get(db, h), key, uri_escape(value)));
106 #define HM_sets(this, key, val) db_put(this, key, val)
111 LOG_INFO("LOAD...\n");
112 int db = db_load("foo.db");
113 LOG_INFO("LOADED. FILL...\n");
114 for (int i = 0; i < DB_BUCKETS; ++i)
115 db_put(db, ftos(random()), "X");
116 LOG_INFO("FILLED. SAVE...\n");
117 db_save(db, "foo.db");
118 LOG_INFO("SAVED. CLOSE...\n");
120 LOG_INFO("CLOSED.\n");