~drizzle-trunk/drizzle/development

1 by brian
clean slate
1
/* Copyright (C) 2000 MySQL AB
2
3
   This program is free software; you can redistribute it and/or modify
4
   it under the terms of the GNU General Public License as published by
5
   the Free Software Foundation; version 2 of the License.
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
   along with this program; if not, write to the Free Software
14
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
16
#include <my_global.h>
17
#include <m_string.h>
18
19
/*
20
  my_memmem, port of a GNU extension.
21
22
  Returns a pointer to the beginning of the substring, needle, or NULL if the
23
  substring is not found in haystack.
24
*/
25
26
void *my_memmem(const void *haystack, size_t haystacklen,
27
                const void *needle, size_t needlelen)
28
{
29
  const unsigned char *cursor;
30
  const unsigned char *last_possible_needle_location =
31
    (unsigned char *)haystack + haystacklen - needlelen;
32
33
  /* Easy answers */
34
  if (needlelen > haystacklen) return(NULL);
35
  if (needle == NULL) return(NULL);
36
  if (haystack == NULL) return(NULL);
37
  if (needlelen == 0) return(NULL);
38
  if (haystacklen == 0) return(NULL);
39
40
  for (cursor = haystack; cursor <= last_possible_needle_location; cursor++) {
41
    if (memcmp(needle, cursor, needlelen) == 0) {
42
      return((void *) cursor);
43
    }
44
  }
45
  return(NULL);
46
}
47
48
  
49
50
#ifdef MAIN
51
#include <assert.h>
52
53
int main(int argc, char *argv[]) {
54
  char haystack[10], needle[3];
55
56
  memmove(haystack, "0123456789", 10);
57
58
  memmove(needle, "no", 2);
59
  assert(my_memmem(haystack, 10, needle, 2) == NULL);
60
61
  memmove(needle, "345", 3);
62
  assert(my_memmem(haystack, 10, needle, 3) != NULL);
63
64
  memmove(needle, "789", 3);
65
  assert(my_memmem(haystack, 10, needle, 3) != NULL);
66
  assert(my_memmem(haystack, 9, needle, 3) == NULL);
67
68
  memmove(needle, "012", 3);
69
  assert(my_memmem(haystack, 10, needle, 3) != NULL);
70
  assert(my_memmem(NULL, 10, needle, 3) == NULL);
71
72
  assert(my_memmem(NULL, 10, needle, 3) == NULL);
73
  assert(my_memmem(haystack, 0, needle, 3) == NULL);
74
  assert(my_memmem(haystack, 10, NULL, 3) == NULL);
75
  assert(my_memmem(haystack, 10, needle, 0) == NULL);
76
77
  assert(my_memmem(haystack, 1, needle, 3) == NULL);
78
79
  printf("success\n");
80
  return(0);
81
}
82
83
#endif