PipeWire  0.3.76
cleanup.h
1 /* Simple Plugin API */
2 /* SPDX-FileCopyrightText: Copyright © 2023 PipeWire authors */
3 /* SPDX-License-Identifier: MIT */
4 
5 #ifndef SPA_UTILS_CLEANUP_H
6 #define SPA_UTILS_CLEANUP_H
7 
8 #if !defined(__has_attribute) || !__has_attribute(__cleanup__)
9 #error "attribute `cleanup` is required"
10 #endif
11 
12 #define spa_cleanup(func) __attribute__((__cleanup__(func)))
13 
14 #define SPA_DEFINE_AUTO_CLEANUP(name, type, ...) \
15 typedef __typeof__(type) _spa_auto_cleanup_type_ ## name; \
16 static inline void _spa_auto_cleanup_func_ ## name (__typeof__(type) *thing) \
17 { \
18  __VA_ARGS__ \
19 }
20 
21 #define spa_auto(name) \
22  spa_cleanup(_spa_auto_cleanup_func_ ## name) \
23  _spa_auto_cleanup_type_ ## name
24 
25 #define SPA_DEFINE_AUTOPTR_CLEANUP(name, type, ...) \
26 typedef __typeof__(type) * _spa_autoptr_cleanup_type_ ## name; \
27 static inline void _spa_autoptr_cleanup_func_ ## name (__typeof__(type) **thing) \
28 { \
29  __VA_ARGS__ \
30 }
31 
32 #define spa_autoptr(name) \
33  spa_cleanup(_spa_autoptr_cleanup_func_ ## name) \
34  _spa_autoptr_cleanup_type_ ## name
35 
36 #define spa_exchange(var, new_value) \
37 __extension__ ({ \
38  __typeof__(var) _old_value = (var); \
39  (var) = (new_value); \
40  _old_value; \
41 })
42 
43 #define spa_steal_ptr(ptr) ((__typeof__(*(ptr)) *) spa_exchange((ptr), NULL))
44 #define spa_steal_fd(fd) spa_exchange((fd), -1)
45 
46 /* ========================================================================== */
47 
48 #include <stdlib.h>
49 
50 #define spa_clear_ptr(ptr, destructor) \
51 __extension__ ({ \
52  __typeof__(*(ptr)) *_old_value = spa_steal_ptr(ptr); \
53  if (_old_value) \
54  destructor(_old_value); \
55  (void) 0; \
56 })
57 
58 static inline void _spa_autofree_cleanup_func(void *p)
59 {
60  free(*(void **) p);
61 }
62 #define spa_autofree spa_cleanup(_spa_autofree_cleanup_func)
63 
64 /* ========================================================================== */
65 
66 #include <unistd.h>
67 
68 #define spa_clear_fd(fd) \
69 __extension__ ({ \
70  int _old_value = spa_steal_fd(fd), _res = 0; \
71  if (_old_value >= 0) \
72  _res = close(_old_value); \
73  _res; \
74 })
75 
76 static inline void _spa_autoclose_cleanup_func(int *fd)
77 {
78  spa_clear_fd(*fd);
79 }
80 #define spa_autoclose spa_cleanup(_spa_autoclose_cleanup_func)
81 
82 /* ========================================================================== */
83 
84 #include <stdio.h>
85 
86 SPA_DEFINE_AUTOPTR_CLEANUP(FILE, FILE, {
87  spa_clear_ptr(*thing, fclose);
88 })
89 
90 /* ========================================================================== */
91 
92 #include <dirent.h>
93 
94 SPA_DEFINE_AUTOPTR_CLEANUP(DIR, DIR, {
95  spa_clear_ptr(*thing, closedir);
96 })
97 
98 #endif /* SPA_UTILS_CLEANUP_H */