From 820debf45a3bc5567fc16a4f982bdf41df7d7ef2 Mon Sep 17 00:00:00 2001 From: Max Kellermann Date: Mon, 2 Mar 2015 22:26:46 +0100 Subject: util/StringUtil: add FindStringSuffix() --- src/PlaylistFile.cxx | 12 ++++-------- src/util/StringUtil.cxx | 15 +++++++++++++++ src/util/StringUtil.hxx | 8 ++++++++ 3 files changed, 27 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/PlaylistFile.cxx b/src/PlaylistFile.cxx index f9c3ab3f3..43dcca294 100644 --- a/src/PlaylistFile.cxx +++ b/src/PlaylistFile.cxx @@ -173,12 +173,9 @@ LoadPlaylistFileInfo(PlaylistInfo &info, return false; const auto *const name_fs_str = name_fs.c_str(); - const size_t name_length = name_fs.length(); - - if (name_length < ARRAY_SIZE(PLAYLIST_FILE_SUFFIX)) - return false; - - if (!StringEndsWith(name_fs_str, PLAYLIST_FILE_SUFFIX)) + const auto *const name_fs_end = + FindStringSuffix(name_fs_str, PLAYLIST_FILE_SUFFIX); + if (name_fs_end == nullptr) return false; FileInfo fi; @@ -186,8 +183,7 @@ LoadPlaylistFileInfo(PlaylistInfo &info, !fi.IsRegular()) return false; - PathTraitsFS::string name(name_fs_str, - name_length + 1 - ARRAY_SIZE(PLAYLIST_FILE_SUFFIX)); + PathTraitsFS::string name(name_fs_str, name_fs_end); std::string name_utf8 = PathToUTF8(name.c_str()); if (name_utf8.empty()) return false; diff --git a/src/util/StringUtil.cxx b/src/util/StringUtil.cxx index 4d538989f..107354b6e 100644 --- a/src/util/StringUtil.cxx +++ b/src/util/StringUtil.cxx @@ -96,6 +96,21 @@ StringEndsWith(const char *haystack, const char *needle) needle, needle_length) == 0; } +const char * +FindStringSuffix(const char *p, const char *suffix) +{ + const size_t p_length = strlen(p); + const size_t suffix_length = strlen(suffix); + + if (p_length < suffix_length) + return nullptr; + + const char *q = p + p_length - suffix_length; + return memcmp(q, suffix, suffix_length) == 0 + ? q + : nullptr; +} + char * CopyString(char *gcc_restrict dest, const char *gcc_restrict src, size_t size) { diff --git a/src/util/StringUtil.hxx b/src/util/StringUtil.hxx index 9f2dab935..4f44ab94a 100644 --- a/src/util/StringUtil.hxx +++ b/src/util/StringUtil.hxx @@ -90,6 +90,14 @@ gcc_pure bool StringEndsWith(const char *haystack, const char *needle); +/** + * Check if the given string ends with the specified suffix. If yes, + * returns the position of the suffix, and nullptr otherwise. + */ +gcc_pure +const char * +FindStringSuffix(const char *p, const char *suffix); + /** * Copy a string. If the buffer is too small, then the string is * truncated. This is a safer version of strncpy(). -- cgit v1.2.3