]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
string-util: rework empty_to_null() to not change "const" qualifier of input
authorLennart Poettering <lennart@poettering.net>
Wed, 21 Dec 2022 21:35:51 +0000 (22:35 +0100)
committerLennart Poettering <lennart@poettering.net>
Wed, 21 Dec 2022 21:41:16 +0000 (22:41 +0100)
This changes the definition from enpty_to_null() so that we are still
typesafe (i.e. only accept strings) but do not drop (or add) any const
to the returned string that wasn't also on the input.

Inspired by: https://github.com/systemd/systemd/pull/25805/commits/3196e2996f613a2e3568a791c503306b7c58d593

src/basic/string-util.h

index 46681ced99764a5abca7272169683cb974b9166e..a78b7960e3606986274293a6a4da726a3ad3168e 100644 (file)
@@ -53,9 +53,13 @@ static inline const char* enable_disable(bool b) {
         return b ? "enable" : "disable";
 }
 
-static inline const char *empty_to_null(const char *p) {
-        return isempty(p) ? NULL : p;
-}
+/* This macro's return pointer will have the "const" qualifier set or unset the same way as the input
+ * pointer. */
+#define empty_to_null(p)                                \
+        ({                                              \
+                const char *_p = (p);                   \
+                (typeof(p)) (isempty(_p) ? NULL : _p);  \
+        })
 
 static inline const char *empty_to_na(const char *p) {
         return isempty(p) ? "n/a" : p;
@@ -74,6 +78,11 @@ static inline bool empty_or_dash(const char *str) {
 static inline const char *empty_or_dash_to_null(const char *p) {
         return empty_or_dash(p) ? NULL : p;
 }
+#define empty_or_dash_to_null(p)                                \
+        ({                                                      \
+                const char *_p = (p);                           \
+                (typeof(p)) (empty_or_dash(_p) ? NULL : _p);    \
+        })
 
 char *first_word(const char *s, const char *word) _pure_;