memmem.c (2227B)
1 /* -*-comment-start: "//";comment-end:""-*- 2 * GNU Mes --- Maxwell Equations of Software 3 * Copyright © 1997--2015,2017,2018 Jan (janneke) Nieuwenhuizen <janneke@gnu.org> 4 * Copyright (C) 1997--2015,2018 Han-Wen Nienhuys <hanwen@xs4all.nl> 5 * 6 * This file is part of GNU Mes. 7 * 8 * GNU Mes is free software; you can redistribute it and/or modify it 9 * under the terms of the GNU General Public License as published by 10 * the Free Software Foundation; either version 3 of the License, or (at 11 * your option) any later version. 12 * 13 * GNU Mes is distributed in the hope that it will be useful, but 14 * WITHOUT ANY WARRANTY; without even the implied warranty of 15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 * GNU General Public License for more details. 17 * 18 * You should have received a copy of the GNU General Public License 19 * along with GNU Mes. If not, see <http://www.gnu.org/licenses/>. 20 */ 21 22 #include <string.h> 23 24 /** locate a substring. #memmem# finds the first occurrence of 25 #needle# in #haystack#. This is not ANSI-C. 26 27 The prototype is not in accordance with the Linux Programmer's 28 Manual v1.15, but it is with /usr/include/string.h */ 29 30 unsigned char * 31 _memmem (unsigned char const *haystack, int haystack_len, unsigned char const *needle, int needle_len) 32 { 33 unsigned char const *end_haystack = haystack + haystack_len - needle_len + 1; 34 unsigned char const *end_needle = needle + needle_len; 35 36 /* Ahhh ... Some minimal lowlevel stuff. This *is* nice; Varation 37 is the spice of life */ 38 while (haystack < end_haystack) 39 { 40 unsigned char const *subneedle = needle; 41 unsigned char const *subhaystack = haystack; 42 while (subneedle < end_needle) 43 if (*subneedle++ != *subhaystack++) 44 goto next; 45 46 /* Completed the needle. Gotcha. */ 47 return (unsigned char *) haystack; 48 next: 49 haystack++; 50 } 51 return 0; 52 } 53 54 void * 55 memmem (void const *haystack, int haystack_len, void const *needle, int needle_len) 56 { 57 unsigned char const *haystack_byte_c = (unsigned char const *) haystack; 58 unsigned char const *needle_byte_c = (unsigned char const *) needle; 59 return _memmem (haystack_byte_c, haystack_len, needle_byte_c, needle_len); 60 }