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 107000 : static inline void free_ptr(void *ptr) {
15 107000 : void **p = (void **)ptr;
16 107000 : if (*p) {
17 105382 : free(*p);
18 105382 : *p = NULL;
19 : }
20 107000 : }
21 :
22 30402 : static inline void fclose_ptr(void *ptr) {
23 30402 : FILE **p = (FILE **)ptr;
24 30402 : if (*p) {
25 23809 : fclose(*p);
26 23808 : *p = NULL;
27 : }
28 30401 : }
29 :
30 3 : static inline void pclose_ptr(FILE **p) {
31 3 : if (p && *p) {
32 3 : pclose(*p);
33 3 : *p = NULL;
34 : }
35 3 : }
36 :
37 57050 : static inline void closedir_ptr(DIR **p) {
38 57050 : if (p && *p) {
39 5956 : closedir(*p);
40 5956 : *p = NULL;
41 : }
42 57050 : }
43 :
44 : #define RAII_STRING __attribute__((cleanup(free_ptr)))
45 : #define RAII_FILE __attribute__((cleanup(fclose_ptr)))
46 : #define RAII_PFILE __attribute__((cleanup(pclose_ptr)))
47 : #define RAII_DIR __attribute__((cleanup(closedir_ptr)))
48 :
49 : /* To avoid circular dependencies with Config, we use a generic cleanup for it
50 : * but it must be defined in each file that uses it or we use a macro. */
51 : #define RAII_WITH_CLEANUP(func) __attribute__((cleanup(func)))
52 :
53 : static inline void html_node_free_ptr(HtmlNode **p) {
54 : if (p && *p) { html_node_free(*p); *p = NULL; }
55 : }
56 : #define RAII_HTML_NODE __attribute__((cleanup(html_node_free_ptr)))
57 :
58 : #endif /* RAII_H */
|