From aa29a5f1f9df18d42c387d046e7b6ef80d9bd6aa Mon Sep 17 00:00:00 2001 From: Wisdom Erhimwionsobo Date: Mon, 29 Sep 2025 11:57:56 +0200 Subject: [PATCH] libutil: Add util_startswith() to util_str MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add util_startswith to util_str to check if a string starts with the given prefix and returns a pointer to the rest of the string, or NULL if it does not. Signed-off-by: Wisdom Erhimwionsobo Reviewed-by: Jan Höppner Reviewed-by: Steffen Eiden Signed-off-by: Jan Höppner --- include/lib/util_str.h | 2 ++ libutil/util_str.c | 46 +++++++++++++++++++++++++++++++++++++++++- 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/include/lib/util_str.h b/include/lib/util_str.h index c8a32deb..0448c126 100644 --- a/include/lib/util_str.h +++ b/include/lib/util_str.h @@ -13,5 +13,7 @@ #define LIB_UTIL_STR_H void util_str_rm_whitespace(const char *src, char *dest); +const char *util_startswith(const char *s, const char *prefix); +const char *util_startswith_no_case(const char *s, const char *prefix); #endif /** LIB_UTIL_STR_H @} */ diff --git a/libutil/util_str.c b/libutil/util_str.c index 71f585e1..21538b37 100644 --- a/libutil/util_str.c +++ b/libutil/util_str.c @@ -3,14 +3,16 @@ * * Manipulate and work with strings * - * Copyright IBM Corp. 2025 + * Copyright IBM Corp. 2026 * * s390-tools is free software; you can redistribute it and/or modify * it under the terms of the MIT license. See LICENSE for details. */ #include +#include +#include "lib/util_panic.h" #include "lib/util_str.h" /** @@ -31,3 +33,45 @@ void util_str_rm_whitespace(const char *src, char *dest) } *dest = '\0'; } + +/** + * Check if string \a s starts with \a prefix + * + * @param[in] s String to check + * @param[in] prefix Prefix to match + * + * @returns Pointer to the character after the prefix if match is found, + * NULL otherwise + */ +const char *util_startswith(const char *s, const char *prefix) +{ + size_t sz; + + util_assert(s != NULL, "Internal error: s input is NULL"); + util_assert(prefix != NULL, "Internal error: prefix input is NULL"); + sz = strlen(prefix); + if (strncmp(s, prefix, sz) == 0) + return s + sz; + return NULL; +} + +/** + * Check if string \a s starts with \a prefix (case-insensitive) + * + * @param[in] s String to check + * @param[in] prefix Prefix to match (case-insensitive) + * + * @returns Pointer to the character after the prefix if match is found, + * NULL otherwise + */ +const char *util_startswith_no_case(const char *s, const char *prefix) +{ + size_t sz; + + util_assert(s != NULL, "Internal error: s input is NULL"); + util_assert(prefix != NULL, "Internal error: prefix input is NULL"); + sz = strlen(prefix); + if (strncasecmp(s, prefix, sz) == 0) + return s + sz; + return NULL; +}