add example for implementing own map

Sat, 05 Apr 2025 14:18:37 +0200

author
Mike Becker <universe@uap-core.de>
date
Sat, 05 Apr 2025 14:18:37 +0200
changeset 1274
03e9360e98f5
parent 1273
c35be6dc1667
child 1275
0f21abc52241

add example for implementing own map

relates to #451

docs/Writerside/topics/map.h.md file | annotate | diff | comparison | revisions
--- a/docs/Writerside/topics/map.h.md	Fri Apr 04 18:02:35 2025 +0200
+++ b/docs/Writerside/topics/map.h.md	Sat Apr 05 14:18:37 2025 +0200
@@ -289,6 +289,10 @@
 
 ## Implement own Map Structures 
 
+If the UCX [hash map](hash_map.h.md) implementation does not suit your needs,
+you can also implement your own map.
+To be compatible with the `CxMap` interface, it needs to store key/value pairs of the following form.
+
 ```C
 typedef struct {
     const CxHashKey *key;
@@ -296,9 +300,52 @@
 } CxMapEntry;
 ```
 
-<warning>
-TODO: example
-</warning>
+When you are declaring your map structure, a `CxMap` member must be embedded as first member of this structure.
+Secondly, you need to implement the `cx_map_class` and assign it when allocating your map.
+
+```C
+#include <cx/map.h>
+
+typedef struct {
+    CxMap base;
+    // ... data members for storing CxMapEntry elements go here ...
+} MyMap;
+
+// declare the class - implement the functions somewhere 
+static cx_map_class my_map_class = {
+        my_map_destructor,
+        my_map_clear,
+        my_map_put,
+        my_map_get,
+        my_map_remove,
+        my_map_iterator,
+};
+
+// this function will create the map
+CxMap *myMapCreate(const CxAllocator *allocator, size_t itemsize) {
+    if (allocator == NULL) {
+        allocator = cxDefaultAllocator;
+    }
+
+    // allocate memory
+    MyMap *map = cxCalloc(allocator, 1, sizeof(MyMap));
+    if (map == NULL) return NULL;
+
+    // initialize base members
+    map->base.cl = &my_map_class; // <--- assign class here
+    map->base.collection.allocator = allocator;
+    if (itemsize == CX_STORE_POINTERS) {
+        map->base.collection.elem_size = sizeof(void *);
+        map->base.collection.store_pointer = true;
+    } else {
+        map->base.collection.elem_size = itemsize;
+    }
+    
+    // ... initialization of data members go here ...
+
+    return (CxMap *) map;
+}
+```
 
 The required behavior for the implementations is described in the following table.
 You can always look at the source code of the UCX hash map to get inspiration.

mercurial