diff mbox series

[v4,3/5] string: add strends() helper to check if a string ends with a suffix

Message ID 20240930113045.28616-4-ansuelsmth@gmail.com
State New
Headers show
Series [v4,1/5] block: add support for defining read-only partitions | expand

Commit Message

Christian Marangi Sept. 30, 2024, 11:30 a.m. UTC
Add strends() helper to check if a string ends with a suffix. The
unreadable strends is chosen to keep consistency with the parallel
strstarts helper used to check if a string starts with a prefix.

To prevent out-of-bounds read, len of string is checked against the
prefix length before comparing the 2 string at the offset.

Suggested-by: Rasmus Villemoes <linux@rasmusvillemoes.dk>
Signed-off-by: Christian Marangi <ansuelsmth@gmail.com>
---
 include/linux/string.h | 13 +++++++++++++
 1 file changed, 13 insertions(+)
diff mbox series

Patch

diff --git a/include/linux/string.h b/include/linux/string.h
index 0dd27afcfaf7..2c3df6ffb326 100644
--- a/include/linux/string.h
+++ b/include/linux/string.h
@@ -353,6 +353,19 @@  static inline bool strstarts(const char *str, const char *prefix)
 	return strncmp(str, prefix, strlen(prefix)) == 0;
 }
 
+/**
+ * strends - does @str end with @suffix?
+ * @str: string to examine
+ * @suffix: suffix to look for.
+ */
+static inline bool strends(const char *str, const char *suffix)
+{
+	size_t n = strlen(str);
+	size_t m = strlen(suffix);
+
+	return n >= m && !memcmp(str + n - m, suffix, m);
+}
+
 size_t memweight(const void *ptr, size_t bytes);
 
 /**