Browse code

core: _strnstr() and _strnistr() defined in core

- alternative to strnstr() which is not in all OSes, pluse the
insensitive option

(cherry picked from commit 7772e14fc298956f57429a67ea4524818b22a158)

Daniel-Constantin Mierla authored on 15/03/2016 11:37:37
Showing 2 changed files
... ...
@@ -1,5 +1,6 @@
1 1
 /*
2 2
  *
3
+ * Copyright (C) 2015 kamailio.org
3 4
  * Copyright (C) 2014 Victor Seva <vseva@sipwise.com>
4 5
  *
5 6
  * This file is part of kamailio, a free SIP server.
... ...
@@ -48,3 +49,53 @@ int str_append(str *orig, str *suffix, str *dest)
48 48
 	memcpy(dest->s+orig->len, suffix->s, suffix->len);
49 49
 	return 0;
50 50
 }
51
+
52
+/*
53
+* Find the first occurrence of find in s, where the search is limited to the
54
+* first slen characters of s.
55
+*/
56
+char * _strnstr(const char* s, const char* find, size_t slen)
57
+{
58
+	char c, sc;
59
+	size_t len;
60
+
61
+	if ((c = *find++) != '\0') {
62
+		len = strlen(find);
63
+		do {
64
+			do {
65
+				if (slen-- < 1 || (sc = *s++) == '\0')
66
+					return (NULL);
67
+			} while (sc != c);
68
+			if (len > slen)
69
+				return (NULL);
70
+		} while (strncmp(s, find, len) != 0);
71
+		s--;
72
+	}
73
+	return ((char *)s);
74
+}
75
+
76
+/*
77
+ * Find the first case insensitive occurrence of find in s, where the
78
+ * search is limited to the first slen characters of s.
79
+ * Based on FreeBSD strnstr.
80
+ */
81
+char* _strnistr(const char *s, const char *find, size_t slen)
82
+{
83
+	char c, sc;
84
+	size_t len;
85
+
86
+	if ((c = *find++) != '\0') {
87
+		len = strlen(find);
88
+		do {
89
+			do {
90
+				if ((sc = *s++) == '\0' || slen-- < 1)
91
+					return (NULL);
92
+			} while (sc != c);
93
+			if (len > slen)
94
+				return (NULL);
95
+		} while (strncasecmp(s, find, len) != 0);
96
+		s--;
97
+	}
98
+	return ((char *)s);
99
+}
100
+
... ...
@@ -21,6 +21,8 @@
21 21
 #ifndef str_h
22 22
 #define str_h
23 23
 
24
+#include <string.h>
25
+
24 26
 /** @defgroup str_string Counted-Length Strings 
25 27
  * @{
26 28
  * 
... ...
@@ -125,4 +127,7 @@ typedef struct _str str;
125 125
  */
126 126
 int str_append(str *orig, str *suffix, str *dest);
127 127
 
128
+char* _strnstr(const char *s, const char *find, size_t slen);
129
+char* _strnistr(const char *s, const char *find, size_t slen);
130
+
128 131
 #endif