mdict: fix free on overwrite, add mdict_del()
authorMarko Kreen <markokr@gmail.com>
Tue, 1 Feb 2011 12:33:23 +0000 (14:33 +0200)
committerMarko Kreen <markokr@gmail.com>
Tue, 1 Feb 2011 12:38:09 +0000 (14:38 +0200)
usual/mdict.c
usual/mdict.h

index 726263aba738f21807ca6a72907e3d4b187b9464..fcece184c98ed705d59a8fe3fe93546f3340ccdb 100644 (file)
@@ -1,9 +1,5 @@
 /*
- * Low-level tools.
- *
- * - dict type
- * - urlenc/urldec for dict.
- * - Postgres array parser.
+ * A string to string dictionary.
  */
 
 #include <usual/mdict.h>
 
 #include <ctype.h>
 
-
-/*
- * Quick dicts for urlencode.
- * - fast lookup
- * - fast creation
- * - not very memory-efficient
- * - existing keys cannot be freed
- */
-
 struct MDict {
        struct CBTree *tree;
        CxMem *cx;
@@ -102,7 +89,7 @@ bool mdict_put_str(struct MDict *dict, const char *key, unsigned klen, const cha
        }
        el = cbtree_lookup(dict->tree, key, klen);
        if (el) {
-               mbuf_free(&el->val);
+               cx_free(dict->cx, mbuf_data(&el->val));
                mbuf_init_fixed_reader(&el->val, vptr, vlen);
        } else {
                kptr = cx_alloc(dict->cx, klen + 1);
@@ -123,6 +110,11 @@ bool mdict_put_str(struct MDict *dict, const char *key, unsigned klen, const cha
        return true;
 }
 
+bool mdict_del_key(struct MDict *dict, const char *key, unsigned klen)
+{
+       return cbtree_delete(dict->tree, key, klen);
+}
+
 /*
  * walk over key-val pairs
  */
@@ -242,7 +234,7 @@ bool mdict_urldecode(struct MDict *dict, const char *str, unsigned len)
                /* insert value */
                el = cbtree_lookup(dict->tree, k, klen);
                if (el) {
-                       mbuf_free(&el->val);
+                       cx_free(dict->cx, mbuf_data(&el->val));
                        mbuf_init_fixed_reader(&el->val, v, vlen);
                } else {
                        el = cx_alloc(dict->cx, sizeof(*el));
index 2f71cd8f86cafcf54d1e301b8011252664ac0089..87a63e23a0ec57eb336f1634c6e6eadf7dd5afed 100644 (file)
@@ -43,6 +43,9 @@ const char *mdict_get_str(struct MDict *dict, const char *key, unsigned klen);
 /** Put string to dict */
 bool mdict_put_str(struct MDict *dict, const char *key, unsigned klen, const char *val, unsigned vlen);
 
+/** Remove a key from dict */
+bool mdict_del_key(struct MDict *dict, const char *key, unsigned klen);
+
 /** Signature for walker callback */
 typedef bool (*mdict_walker_f)(void *arg, const struct MBuf *k, const struct MBuf *v);
 
@@ -76,6 +79,12 @@ static inline bool mdict_put_buf(struct MDict *dict, const char *key, const stru
        return mdict_put_str(dict, key, klen, val, vlen);
 }
 
+/** Remove value from dict */
+static inline bool mdict_del(struct MDict *dict, const char *key)
+{
+       return mdict_del_key(dict, key, strlen(key));
+}
+
 /** Urldecode string and add keys with values to dict */
 bool mdict_urldecode(struct MDict *dict, const char *str, unsigned len);