nmdb: Cast to avoid known const violation warnings in tdb and bdb backends
[nmdb.git] / nmdb / be-tdb.c
blobbd81789a842f73eb8fa51178d0a6a015189e2372
2 #if BE_ENABLE_TDB
4 #include <string.h> /* memcpy() */
5 #include <stdlib.h> /* malloc() and friends */
7 /* tdb.h needs mode_t defined externally, and it is defined in one of these
8 (which are the ones required for open() */
9 #include <sys/types.h>
10 #include <sys/stat.h>
11 #include <fcntl.h>
12 #include <tdb.h>
14 #include "be.h"
16 /* Local operations names are prepended with an 'x' so they don't collide with
17 * tdb real functions */
19 int xtdb_set(struct db_conn *db, const unsigned char *key, size_t ksize,
20 unsigned char *val, size_t vsize);
21 int xtdb_get(struct db_conn *db, const unsigned char *key, size_t ksize,
22 unsigned char *val, size_t *vsize);
23 int xtdb_del(struct db_conn *db, const unsigned char *key, size_t ksize);
24 int xtdb_close(struct db_conn *db);
27 struct db_conn *xtdb_open(const char *name, int flags)
29 struct db_conn *db;
30 TDB_CONTEXT *tdb_db;
32 tdb_db = tdb_open(name, 0, 0, O_CREAT | O_RDWR, 0640);
33 if (tdb_db == NULL)
34 return NULL;
36 db = malloc(sizeof(struct db_conn));
37 if (db == NULL) {
38 tdb_close(tdb_db);
39 return NULL;
42 db->conn = tdb_db;
43 db->set = xtdb_set;
44 db->get = xtdb_get;
45 db->del = xtdb_del;
46 db->close = xtdb_close;
48 return db;
51 int xtdb_close(struct db_conn *db)
53 int rv;
55 rv = tdb_close(db->conn);
56 free(db);
57 return rv == 0;
60 int xtdb_set(struct db_conn *db, const unsigned char *key, size_t ksize,
61 unsigned char *val, size_t vsize)
63 TDB_DATA k, v;
65 /* we can't maintain "const"ness here because tdb's prototypes; the
66 * same applies to get and del, so we just cast */
67 k.dptr = (unsigned char *) key;
68 k.dsize = ksize;
69 v.dptr = (unsigned char *) val;
70 v.dsize = vsize;
72 return tdb_store(db->conn, k, v, TDB_REPLACE) == 0;
75 int xtdb_get(struct db_conn *db, const unsigned char *key, size_t ksize,
76 unsigned char *val, size_t *vsize)
78 TDB_DATA k, v;
80 k.dptr = (unsigned char *) key;
81 k.dsize = ksize;
83 v = tdb_fetch(db->conn, k);
84 if (v.dptr == NULL)
85 return 0;
87 if (v.dsize > *vsize)
88 return 0;
90 *vsize = v.dsize;
91 memcpy(val, v.dptr, v.dsize);
92 free(v.dptr);
93 return 1;
96 int xtdb_del(struct db_conn *db, const unsigned char *key, size_t ksize)
98 TDB_DATA k;
100 k.dptr = (unsigned char *) key;
101 k.dsize = ksize;
103 return tdb_delete(db->conn, k) == 0;
106 #else
108 #include <stddef.h> /* NULL */
110 struct db_conn *xtdb_open(const char *name, int flags)
112 return NULL;
115 #endif