From 76205b89e2a7889eb557bb4d86761e21bf04606c Mon Sep 17 00:00:00 2001 From: Simon Tatham Date: Sun, 12 Jun 2022 11:27:27 +0100 Subject: [PATCH] A few more ptrlen functions. ptrlen_contains and ptrlen_contains_only are useful for checking that a string is composed entirely of certain characters, or avoids them. ptrlen_end makes a pointer to the byte just past the end of the specified string. And it can be used with make_ptrlen_startend, which makes a ptrlen out of two pointers instead of a pointer and a length. --- misc.h | 17 +++++++++++++++++ utils/ptrlen.c | 16 ++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/misc.h b/misc.h index b4b9bd57..afde1502 100644 --- a/misc.h +++ b/misc.h @@ -169,6 +169,21 @@ static inline ptrlen make_ptrlen(const void *ptr, size_t len) return pl; } +static inline const void *ptrlen_end(ptrlen pl) +{ + return (const char *)pl.ptr + pl.len; +} + +static inline ptrlen make_ptrlen_startend(const void *startv, const void *endv) +{ + const char *start = (const char *)startv, *end = (const char *)endv; + assert(end >= start); + ptrlen pl; + pl.ptr = start; + pl.len = end - start; + return pl; +} + static inline ptrlen ptrlen_from_asciz(const char *str) { return make_ptrlen(str, strlen(str)); @@ -190,6 +205,8 @@ int ptrlen_strcmp(ptrlen pl1, ptrlen pl2); bool ptrlen_startswith(ptrlen whole, ptrlen prefix, ptrlen *tail); bool ptrlen_endswith(ptrlen whole, ptrlen suffix, ptrlen *tail); ptrlen ptrlen_get_word(ptrlen *input, const char *separators); +bool ptrlen_contains(ptrlen input, const char *characters); +bool ptrlen_contains_only(ptrlen input, const char *characters); char *mkstr(ptrlen pl); int string_length_for_printf(size_t); /* Derive two printf arguments from a ptrlen, suitable for "%.*s" */ diff --git a/utils/ptrlen.c b/utils/ptrlen.c index 7d4e12ec..37972e49 100644 --- a/utils/ptrlen.c +++ b/utils/ptrlen.c @@ -54,6 +54,22 @@ bool ptrlen_endswith(ptrlen whole, ptrlen suffix, ptrlen *tail) return false; } +bool ptrlen_contains(ptrlen input, const char *characters) +{ + for (const char *p = input.ptr, *end = p + input.len; p < end; p++) + if (strchr(characters, *p)) + return true; + return false; +} + +bool ptrlen_contains_only(ptrlen input, const char *characters) +{ + for (const char *p = input.ptr, *end = p + input.len; p < end; p++) + if (!strchr(characters, *p)) + return false; + return true; +} + ptrlen ptrlen_get_word(ptrlen *input, const char *separators) { const char *p = input->ptr, *end = p + input->len;