diff --git a/src/libratbag-private.h b/src/libratbag-private.h index d5dfd878..7e251cdc 100644 --- a/src/libratbag-private.h +++ b/src/libratbag-private.h @@ -33,6 +33,28 @@ #include "libratbag-util.h" #include "libratbag-hidraw.h" +static inline void +cleanup_device(struct ratbag_device **d) +{ + ratbag_device_unref(*d); +} + +static inline void +cleanup_profile(struct ratbag_profile **p) +{ + ratbag_profile_unref(*p); +} + +static inline void +cleanup_resolution(struct ratbag_resolution **r) +{ + ratbag_resolution_unref(*r); +} + +#define _cleanup_device_ _cleanup_(cleanup_device) +#define _cleanup_profile_ _cleanup_(cleanup_profile) +#define _cleanup_resolution_ _cleanup_(cleanup_resolution) + #define BUS_ANY 0xffff #define VENDOR_ANY 0xffff #define PRODUCT_ANY 0xffff diff --git a/src/libratbag-util.h b/src/libratbag-util.h index bd8d70e6..cbe4a329 100644 --- a/src/libratbag-util.h +++ b/src/libratbag-util.h @@ -80,6 +80,14 @@ int list_empty(const struct list *list); #define streq(s1, s2) (strcmp((s1), (s2)) == 0) #define strneq(s1, s2, n) (strncmp((s1), (s2), (n)) == 0) +static inline void +cleanup_free(void *p) { + free(*(void**)p); +} + +#define _cleanup_(x) __attribute__((cleanup(x))) +#define _cleanup_free_ _cleanup_(cleanup_free) + static inline char* strncpy_safe(char *dest, const char *src, size_t n) { diff --git a/src/libratbag.c b/src/libratbag.c index ae676efd..ebe9dd36 100644 --- a/src/libratbag.c +++ b/src/libratbag.c @@ -90,7 +90,7 @@ log_buffer(struct ratbag *ratbag, const char *header, uint8_t *buf, size_t len) { - char *output_buf; + _cleanup_free_ char *output_buf = NULL; char *sep = ""; unsigned int i, n; unsigned int buf_len; @@ -114,8 +114,6 @@ log_buffer(struct ratbag *ratbag, } log_msg(ratbag, priority, "%s\n", output_buf); - - free(output_buf); } LIBRATBAG_EXPORT void @@ -208,8 +206,8 @@ static inline bool ratbag_sanity_check_device(struct ratbag_device *device) { struct ratbag *ratbag = device->ratbag; - struct ratbag_profile *profile = NULL; - struct ratbag_resolution *res = NULL; + _cleanup_profile_ struct ratbag_profile *profile = NULL; + _cleanup_resolution_ struct ratbag_resolution *res = NULL; bool has_active = false; bool has_default = false; unsigned int nres, nprofiles; @@ -278,9 +276,6 @@ ratbag_sanity_check_device(struct ratbag_device *device) rc = true; out: - ratbag_profile_unref(profile); - ratbag_resolution_unref(res); - return rc; }