[RFC/PATCH 05/10] libbb: add ends_with() function
Bartosz Golaszewski
bartekgola at gmail.com
Thu Aug 13 13:57:25 UTC 2015
This function checks if given key can be found at the end of the string.
Signed-off-by: Bartosz Golaszewski <bartekgola at gmail.com>
---
include/libbb.h | 1 +
libbb/compare_string_array.c | 30 ++++++++++++++++++++++++++++++
2 files changed, 31 insertions(+)
diff --git a/include/libbb.h b/include/libbb.h
index a56b684..7b41c9b 100644
--- a/include/libbb.h
+++ b/include/libbb.h
@@ -422,6 +422,7 @@ const char *bb_basename(const char *name) FAST_FUNC;
char *last_char_is(const char *s, int c) FAST_FUNC;
const char* endofname(const char *name) FAST_FUNC;
char *is_prefixed_with(const char *string, const char *key) FAST_FUNC;
+int ends_with(const char *str, const char *key) FAST_FUNC;
int ndelay_on(int fd) FAST_FUNC;
int ndelay_off(int fd) FAST_FUNC;
diff --git a/libbb/compare_string_array.c b/libbb/compare_string_array.c
index e24815a..a2d77c7 100644
--- a/libbb/compare_string_array.c
+++ b/libbb/compare_string_array.c
@@ -23,6 +23,19 @@ char* FAST_FUNC is_prefixed_with(const char *string, const char *key)
#endif
}
+int FAST_FUNC ends_with(const char *str, const char *key)
+{
+ size_t str_len = strlen(str), key_len = strlen(key);
+
+ if (str_len >= key_len) {
+ if (strcmp(str + str_len - key_len, key) == 0) {
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
/* returns the array index of the string */
/* (index of first match is returned, or -1) */
int FAST_FUNC index_in_str_array(const char *const string_array[], const char *key)
@@ -110,3 +123,20 @@ smallint FAST_FUNC yesno(const char *str)
return ret / 3;
}
#endif
+
+#if ENABLE_UNIT_TEST
+
+BBUNIT_DEFINE_TEST(ends_with)
+{
+ BBUNIT_ASSERT_TRUE(ends_with("foo bar", "bar"));
+ BBUNIT_ASSERT_TRUE(ends_with("foo", "foo"));
+ BBUNIT_ASSERT_TRUE(ends_with("foo", ""));
+ BBUNIT_ASSERT_TRUE(ends_with("", ""));
+
+ BBUNIT_ASSERT_FALSE(ends_with("foo", "bar foo"));
+ BBUNIT_ASSERT_FALSE(ends_with("foo foo", "bar"));
+
+ BBUNIT_ENDTEST;
+}
+
+#endif /* ENABLE_UNIT_TEST */
--
2.1.4
More information about the busybox
mailing list