]> git.lizzy.rs Git - dragonstd.git/blob - map.h
Callback rework
[dragonstd.git] / map.h
1 /*
2         Map
3         ---
4
5         Thread safe map/set, using a Tree.
6         Useful for managing big amounts of objects with add, get and del access from multiple                   threads.
7 */
8
9 #ifndef _DRAGONSTD_MAP_H_ // include guard
10 #define _DRAGONSTD_MAP_H_
11
12 #include <stdbool.h>       // for bool
13 #include <pthread.h>       // for pthread_rwlock_t
14 #include "bits/callback.h" // for Transformer, Comparator, Callback
15 #include "tree.h"          // for Tree
16
17 typedef struct {
18         /* private */
19         Tree tre;             // search tree to manage data
20         pthread_rwlock_t tlk; // lock to protect tree
21         bool cnl;             // cancel state
22         pthread_rwlock_t clk; // lock to protect cancel state
23 } Map;
24
25 void map_ini(Map *map);
26 /*
27         Initializes the map.
28
29         The map should be uninitialized before passed to this function.
30         This function should be called before any other function is called on the tree.
31 */
32
33 void map_dst(Map *map);
34 /*
35         Destroys the map.
36
37         The map should not be used afterwards.
38         Make sure to cancel the map before destroying it, to avoid memory leaks.
39 */
40
41 void map_cnl(Map *map, Callback iter, void *arg, Transformer trans, TreeTraversionOrder order);
42 /*
43         [Thread Safe]
44         Cancels and clears the map.
45
46         All subsequent calls to add, get and del have no effect and return NULL.
47
48         Traverses the map and deletes all elements.
49         Calls func on every element, with the extra argument arg.
50
51         The map is empty afterwards.
52         If no callback is given, the traversion order is irrelevant.
53 */
54
55 bool map_add(Map *map, void *dat, Comparator cmp, Transformer trans);
56 /*
57         [Thread Safe]
58         Add an element to the map.
59
60         If an equal element is already in the map, don't add anything.
61         Return whether an element has been added.
62 */
63
64 void *map_get(Map *map, void *key, Comparator cmp, Transformer trans);
65 /*
66         [Thread Safe]
67         Get an element from the map, or return NULL if none found.
68 */
69
70 bool map_del(Map *map, void *key, Comparator cmp, Callback call, void *arg);
71 /*
72         [Thread Safe]
73         Delete an element from the map if it is found.
74         Return whether an element has been deleted.
75 */
76
77 void map_trv(Map *map, Callback iter, void *arg, Transformer trans, TreeTraversionOrder order);
78 /*
79         [Thread Safe]
80         Traverse the map.
81         Calls iter on every element, with the extra argument arg.
82 */
83
84
85 #endif