string-util: add strlen_ptr() helper

strlen_ptr() is to strlen() what streq_ptr() is to streq(): i.e. it
handles NULL strings in a smart way.
This commit is contained in:
Lennart Poettering
2017-07-31 18:20:28 +02:00
parent 6f8cbcdb27
commit 7bf7ce28b5
8 changed files with 24 additions and 7 deletions
+3 -1
View File
@@ -23,9 +23,11 @@
#include <stdlib.h>
#include <string.h>
#include "string-util.h"
char *bus_label_escape(const char *s);
char *bus_label_unescape_n(const char *f, size_t l);
static inline char *bus_label_unescape(const char *f) {
return bus_label_unescape_n(f, f ? strlen(f) : 0);
return bus_label_unescape_n(f, strlen_ptr(f));
}
+1 -1
View File
@@ -314,7 +314,7 @@ int cunescape_length_with_prefix(const char *s, size_t length, const char *prefi
/* Undoes C style string escaping, and optionally prefixes it. */
pl = prefix ? strlen(prefix) : 0;
pl = strlen_ptr(prefix);
r = new(char, pl+length+1);
if (!r)
+2 -1
View File
@@ -25,6 +25,7 @@
#include "alloc-util.h"
#include "hexdecoct.h"
#include "macro.h"
#include "string-util.h"
#include "util.h"
char octchar(int x) {
@@ -569,7 +570,7 @@ static int base64_append_width(char **prefix, int plen,
lines = (len + width - 1) / width;
slen = sep ? strlen(sep) : 0;
slen = strlen_ptr(sep);
t = realloc(*prefix, plen + 1 + slen + (indent + width + 1) * lines);
if (!t)
return -ENOMEM;
+2 -2
View File
@@ -215,7 +215,7 @@ char *strnappend(const char *s, const char *suffix, size_t b) {
}
char *strappend(const char *s, const char *suffix) {
return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
return strnappend(s, suffix, strlen_ptr(suffix));
}
char *strjoin_real(const char *x, ...) {
@@ -707,7 +707,7 @@ char *strextend(char **x, ...) {
assert(x);
l = f = *x ? strlen(*x) : 0;
l = f = strlen_ptr(*x);
va_start(ap, x);
for (;;) {
+7
View File
@@ -200,3 +200,10 @@ DEFINE_TRIVIAL_CLEANUP_FUNC(char *, string_free_erase);
#define _cleanup_string_free_erase_ _cleanup_(string_free_erasep)
bool string_is_safe(const char *p) _pure_;
static inline size_t strlen_ptr(const char *s) {
if (!s)
return 0;
return strlen(s);
}