summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--common/util.c25
-rw-r--r--include/util.h10
-rw-r--r--test/utils_str.c15
3 files changed, 50 insertions, 0 deletions
diff --git a/common/util.c b/common/util.c
index 40a107883e..b9f11aad27 100644
--- a/common/util.c
+++ b/common/util.c
@@ -94,6 +94,31 @@ __stdlib_compat int strncasecmp(const char *s1, const char *s2, size_t size)
}
+__stdlib_compat char *strstr(const char *s1, const char *s2)
+{
+ const char *p, *q, *r;
+ size_t len1 = strlen(s1);
+ size_t len2 = strlen(s2);
+
+ if (len1 == 0 || len2 == 0 || len1 < len2)
+ return NULL;
+
+ r = s1 + len1 - len2 + 1;
+ for (; s1 < r; s1++) {
+ if (*s1 == *s2) {
+ p = s1 + 1;
+ q = s2 + 1;
+ for (; q < s2 + len2;) {
+ if (*p++ != *q++)
+ break;
+ }
+ if (*q == '\0')
+ return (char *)s1;
+ }
+ }
+ return NULL;
+}
+
__stdlib_compat int atoi(const char *nptr)
{
int result = 0;
diff --git a/include/util.h b/include/util.h
index 60bb00510a..10d9b3661d 100644
--- a/include/util.h
+++ b/include/util.h
@@ -95,6 +95,16 @@ void *memmove(void *dest, const void *src, size_t len);
void *memchr(const void *buffer, int c, size_t n);
int strcasecmp(const char *s1, const char *s2);
int strncasecmp(const char *s1, const char *s2, size_t size);
+
+/**
+ * Find the first occurrence of the substring <s2> in the string <s1>
+ *
+ * @param s1 String where <s2> is searched.
+ * @param s2 Substring to be located in <s1>
+ * @return Pointer to the located substring or NULL if not found.
+ */
+char *strstr(const char *s1, const char *s2);
+
size_t strlen(const char *s);
size_t strnlen(const char *s, size_t maxlen);
char *strncpy(char *dest, const char *src, size_t n);
diff --git a/test/utils_str.c b/test/utils_str.c
index 6498ef85d5..4cb6875b5c 100644
--- a/test/utils_str.c
+++ b/test/utils_str.c
@@ -27,6 +27,20 @@ static int test_isprint(void)
isprint(' ') && !isprint('\0') && !isprint('\n'));
}
+static int test_strstr(void)
+{
+ const char s1[] = "abcde";
+
+ TEST_ASSERT(strstr(s1, "ab") == s1);
+ TEST_ASSERT(strstr(s1, "") == NULL);
+ TEST_ASSERT(strstr("", "ab") == NULL);
+ TEST_ASSERT(strstr("", "x") == NULL);
+ TEST_ASSERT(strstr(s1, "de") == &s1[3]);
+ TEST_ASSERT(strstr(s1, "def") == NULL);
+
+ return EC_SUCCESS;
+}
+
static int test_strtoi(void)
{
char *e;
@@ -252,6 +266,7 @@ void run_test(void)
RUN_TEST(test_isalpha);
RUN_TEST(test_isprint);
+ RUN_TEST(test_strstr);
RUN_TEST(test_strtoi);
RUN_TEST(test_strtoul);
RUN_TEST(test_parse_bool);