suricata
util-memrchr.c
Go to the documentation of this file.
1 /* Copyright (C) 2007-2013 Open Information Security Foundation
2  *
3  * You can copy, redistribute or modify this Program under the terms of
4  * the GNU General Public License version 2 as published by the Free
5  * Software Foundation.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * version 2 along with this program; if not, write to the Free Software
14  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
15  * 02110-1301, USA.
16  */
17 
18 /**
19  * \file
20  *
21  * \author Victor Julien <victor@inliniac.net>
22  *
23  */
24 
25 #include "suricata-common.h"
26 #include "util-unittest.h"
27 #include "util-memrchr.h"
28 
29 #if !defined(HAVE_MEMRCHR) || defined(UNITTESTS)
30 static void *SCMemrchrFallback(const void *s, int c, size_t n)
31 {
32  const unsigned char *p = (const unsigned char *)s + n;
33  const unsigned char uc = (unsigned char)c;
34 
35  while (p > (const unsigned char *)s) {
36  p--;
37  if (*p == uc)
38  return (void *)p;
39  }
40  return NULL;
41 }
42 #endif
43 
44 #ifndef HAVE_MEMRCHR
45 void *memrchr(const void *s, int c, size_t n)
46 {
47  return SCMemrchrFallback(s, c, n);
48 }
49 #endif /* HAVE_MEMRCHR */
50 
51 #ifdef UNITTESTS
52 static int MemrchrTest01 (void)
53 {
54  char buf[] = { 'x', 'y', 'z' };
55  char one_byte[] = { 'q' };
56  char dup[] = { 'a', 'b', 'a' };
57  unsigned char high_byte[] = { 0x80, 'x', 0x80 };
58 
59  FAIL_IF(SCMemrchrFallback(buf, 'x', sizeof(buf)) != &buf[0]);
60  FAIL_IF(SCMemrchrFallback(buf, 'z', sizeof(buf)) != &buf[2]);
61  FAIL_IF(SCMemrchrFallback(buf, 'y', sizeof(buf)) != &buf[1]);
62  FAIL_IF(SCMemrchrFallback(buf, 'a', sizeof(buf)) != NULL);
63  FAIL_IF(SCMemrchrFallback(one_byte, 'q', sizeof(one_byte)) != &one_byte[0]);
64  FAIL_IF(SCMemrchrFallback(one_byte, 'q', 0) != NULL);
65  FAIL_IF(SCMemrchrFallback(dup, 'a', sizeof(dup)) != &dup[2]);
66  FAIL_IF(SCMemrchrFallback(high_byte, 0x80, sizeof(high_byte)) != &high_byte[2]);
67 
68  PASS;
69 }
70 #endif
71 
73 {
74 #ifdef UNITTESTS
75  UtRegisterTest("MemrchrTest01", MemrchrTest01);
76 #endif
77 }
UtRegisterTest
void UtRegisterTest(const char *name, int(*TestFn)(void))
Register unit test.
Definition: util-unittest.c:103
p
Packet * p
Definition: fuzz_iprep.c:21
MemrchrRegisterTests
void MemrchrRegisterTests(void)
Definition: util-memrchr.c:72
util-unittest.h
PASS
#define PASS
Pass the test.
Definition: util-unittest.h:105
memrchr
void * memrchr(const void *s, int c, size_t n)
Definition: util-memrchr.c:45
FAIL_IF
#define FAIL_IF(expr)
Fail a test if expression evaluates to true.
Definition: util-unittest.h:71
suricata-common.h
util-memrchr.h