1 /* Copyright (c) 2017 Sichen Zhao <1473996754@qq.com> */
2 /*
3 FUNCTION
4 <<strnstr>>---find string segment
5
6 INDEX
7 strnstr
8
9 SYNOPSIS
10 #include <string.h>
11 size_t strnstr(const char *<[s1]>, const char *<[s2]>, size_t <[n]>);
12
13 DESCRIPTION
14 Locates the first occurrence in the string pointed to by <[s1]> of
15 the sequence of limited to the <[n]> characters in the string
16 pointed to by <[s2]>
17
18 RETURNS
19 Returns a pointer to the located string segment, or a null
20 pointer if the string <[s2]> is not found. If <[s2]> points to
21 a string with zero length, <[s1]> is returned.
22
23
24 PORTABILITY
25 <<strnstr>> is a BSD extension.
26
27 <<strnstr>> requires no supporting OS subroutines.
28
29 QUICKREF
30 strnstr pure
31
32 */
33
34 #define _GNU_SOURCE
35 #include <string.h>
36
37 /*
38 * Find the first occurrence of find in s, where the search is limited to the
39 * first slen characters of s.
40 */
41 char *
strnstr(const char * haystack,const char * needle,size_t haystack_len)42 strnstr(const char *haystack, const char *needle, size_t haystack_len)
43 {
44 size_t needle_len = strnlen(needle, haystack_len);
45
46 if (needle_len < haystack_len || !needle[needle_len]) {
47 char *x = memmem(haystack, haystack_len, needle, needle_len);
48 if (x && !memchr(haystack, 0, x - haystack))
49 return x;
50 }
51 return NULL;
52 }
53