6 // Databases (hash tables)
7 const int DB_BUCKETS = 8192;
8 void db_save(int db, string filename)
10 int fh = fopen(filename, FILE_WRITE);
13 LOG_WARNINGF("^1Can't write DB to %s\n", 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"));
28 #define HM_NEW(this) (this = db_create())
30 void db_put(int db, string key, string value);
32 int db_load(string filename)
34 int db = buf_create();
35 if (db < 0) return -1;
36 int fh = fopen(filename, FILE_READ);
37 if (fh < 0) return db;
39 if (stoi(l) == DB_BUCKETS)
41 for (int i = 0; (l = fgets(fh)); ++i)
43 if (l != "") bufstr_set(db, i, l);
48 // different count of buckets, or a dump?
49 // need to reorganize the database then (SLOW)
51 // note: we also parse the first line (l) in case the DB file is
52 // missing the bucket count
55 int n = tokenizebyseparator(l, "\\");
56 for (int j = 2; j < n; j += 2)
57 db_put(db, argv(j - 1), uri_unescape(argv(j)));
59 while ((l = fgets(fh)));
65 void db_dump(int db, string filename)
67 int fh = fopen(filename, FILE_WRITE);
68 if (fh < 0) LOG_FATALF("Can't dump DB to %s\n");
70 for (int i = 0, n = buf_getsize(db); i < n; ++i)
72 int m = tokenizebyseparator(bufstr_get(db, i), "\\");
73 for (int j = 2; j < m; j += 2)
74 fputs(fh, strcat("\\", argv(j - 1), "\\", argv(j), "\n"));
83 #define HM_DELETE(this) db_close(this)
85 string db_get(int db, string key)
87 int h = crc16(false, key) % DB_BUCKETS;
88 return uri_unescape(infoget(bufstr_get(db, h), key));
90 #define HM_gets(this, k) db_get(this, k)
92 #define db_remove(db, key) db_put(db, key, "")
94 void db_put(int db, string key, string value)
96 int h = crc16(false, key) % DB_BUCKETS;
97 bufstr_set(db, h, infoadd(bufstr_get(db, h), key, uri_escape(value)));
99 #define HM_sets(this, key, val) db_put(this, key, val)
103 LOG_INFO("LOAD...\n");
104 int db = db_load("foo.db");
105 LOG_INFO("LOADED. FILL...\n");
106 for (int i = 0; i < DB_BUCKETS; ++i)
107 db_put(db, ftos(random()), "X");
108 LOG_INFO("FILLED. SAVE...\n");
109 db_save(db, "foo.db");
110 LOG_INFO("SAVED. CLOSE...\n");
112 LOG_INFO("CLOSED.\n");