Line data Source code
1 : #ifndef RAII_H
2 : #define RAII_H
3 :
4 : #include <stdlib.h>
5 : #include <stdio.h>
6 : #include <dirent.h>
7 : #include "html_parser.h"
8 :
9 : /**
10 : * Cleanup functions for GNU RAII attributes.
11 : * These are called when a variable with the __attribute__((cleanup(func))) goes out of scope.
12 : */
13 :
14 4975 : static inline void free_ptr(void *ptr) {
15 4975 : void **p = (void **)ptr;
16 4975 : if (*p) {
17 4923 : free(*p);
18 4923 : *p = NULL;
19 : }
20 4975 : }
21 :
22 238 : static inline void fclose_ptr(void *ptr) {
23 238 : FILE **p = (FILE **)ptr;
24 238 : if (*p) {
25 118 : fclose(*p);
26 118 : *p = NULL;
27 : }
28 238 : }
29 :
30 2 : static inline void closedir_ptr(DIR **p) {
31 2 : if (p && *p) {
32 1 : closedir(*p);
33 1 : *p = NULL;
34 : }
35 2 : }
36 :
37 : #define RAII_STRING __attribute__((cleanup(free_ptr)))
38 : #define RAII_FILE __attribute__((cleanup(fclose_ptr)))
39 : #define RAII_DIR __attribute__((cleanup(closedir_ptr)))
40 :
41 : /* To avoid circular dependencies with Config, we use a generic cleanup for it
42 : * but it must be defined in each file that uses it or we use a macro. */
43 : #define RAII_WITH_CLEANUP(func) __attribute__((cleanup(func)))
44 :
45 17 : static inline void html_node_free_ptr(HtmlNode **p) {
46 17 : if (p && *p) { html_node_free(*p); *p = NULL; }
47 17 : }
48 : #define RAII_HTML_NODE __attribute__((cleanup(html_node_free_ptr)))
49 :
50 : #endif // RAII_H
|