From 7d56c8fe1ddfe13edc1ccc8a70f41fbea1d6e39d Mon Sep 17 00:00:00 2001 From: Campbell Barton Date: Mon, 5 Jun 2023 12:17:13 +1000 Subject: [PATCH] BLI_string: add BLI_strchr_or_end Returning the pointer to the null byte when the character isn't found is useful when handling null terminated strings that contain newlines. This means the return value is never null and the line span always ends at the resulting value. --- source/blender/blenlib/BLI_string.h | 10 ++++++++++ source/blender/blenlib/intern/string.c | 15 +++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/source/blender/blenlib/BLI_string.h b/source/blender/blenlib/BLI_string.h index 5f237418171..5afeabb0867 100644 --- a/source/blender/blenlib/BLI_string.h +++ b/source/blender/blenlib/BLI_string.h @@ -114,6 +114,16 @@ size_t BLI_strcpy_rlen(char *__restrict dst, const char *__restrict src) ATTR_WA char *BLI_strncat(char *__restrict dst, const char *__restrict src, size_t dst_maxncpy) ATTR_NONNULL(1, 2); +/** + * A version of `strchr` that returns the end of the string (point to `\0`) + * if the character is not found. + * + * Useful for stepping over newlines up until the last line. + */ +const char *BLI_strchr_or_end(const char *str, + char ch) ATTR_WARN_UNUSED_RESULT ATTR_RETURNS_NONNULL + ATTR_NONNULL(1); + /** * Return the range of the quoted string (excluding quotes) `str` after `prefix`. * diff --git a/source/blender/blenlib/intern/string.c b/source/blender/blenlib/intern/string.c index b9af76c4ac0..0e25312279a 100644 --- a/source/blender/blenlib/intern/string.c +++ b/source/blender/blenlib/intern/string.c @@ -988,6 +988,21 @@ size_t BLI_strnlen(const char *s, const size_t maxlen) /** \} */ +/* -------------------------------------------------------------------- */ +/** \name String Scanning + * \{ */ + +const char *BLI_strchr_or_end(const char *str, const char ch) +{ + const char *p = str; + while (!ELEM(*p, ch, '\0')) { + p++; + } + return p; +} + +/** \} */ + /* -------------------------------------------------------------------- */ /** \name String Case Conversion * \{ */