From 9f909603921d880e5e10741c82a97a607d9192a6 Mon Sep 17 00:00:00 2001 From: Jan Nieuwenhuizen Date: Tue, 29 May 2018 19:35:20 +0200 Subject: [PATCH] mlibc: Implement strstr. * lib/libc+tcc.c (_memmem, memmem): New function. Import from GNU LilyPond. (strstr): Implement using memmem. * include/string.h (_memmem, memmem): Declare. * AUTHORS: Add Han-Wen Nienhuys. --- AUTHORS | 3 ++- lib/libc+tcc.c | 44 ++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/AUTHORS b/AUTHORS index c3f0bcd9..ea7de2fb 100644 --- a/AUTHORS +++ b/AUTHORS @@ -5,7 +5,8 @@ All files except the imported files listed below Jeremiah Orians lib/libc.c (fopen) - +Han-Wen Nienhuys +lib/libc+tcc.c (_memmem, memmem) List of imported files diff --git a/lib/libc+tcc.c b/lib/libc+tcc.c index 100bfb17..1e1e2939 100644 --- a/lib/libc+tcc.c +++ b/lib/libc+tcc.c @@ -1,6 +1,7 @@ /* -*-comment-start: "//";comment-end:""-*- * Mes --- Maxwell Equations of Software * Copyright © 2017,2018 Jan (janneke) Nieuwenhuizen + * Copyright (C) 2018 Han-Wen Nienhuys * * This file is part of Mes. * @@ -287,11 +288,50 @@ strrchr (char const *s, int c) return 0; } +/** locate a substring. #memmem# finds the first occurrence of + #needle# in #haystack#. This is not ANSI-C. + + The prototype is not in accordance with the Linux Programmer's + Manual v1.15, but it is with /usr/include/string.h */ + +unsigned char * +_memmem (unsigned char const *haystack, int haystack_len, + unsigned char const *needle, int needle_len) +{ + unsigned char const *end_haystack = haystack + haystack_len - needle_len + 1; + unsigned char const *end_needle = needle + needle_len; + + /* Ahhh ... Some minimal lowlevel stuff. This *is* nice; Varation + is the spice of life */ + while (haystack < end_haystack) + { + unsigned char const *subneedle = needle; + unsigned char const *subhaystack = haystack; + while (subneedle < end_needle) + if (*subneedle++ != *subhaystack++) + goto next; + + /* Completed the needle. Gotcha. */ + return (unsigned char *) haystack; + next: + haystack++; + } + return 0; +} + +void * +memmem (void const *haystack, int haystack_len, + void const *needle, int needle_len) +{ + unsigned char const *haystack_byte_c = (unsigned char const *)haystack; + unsigned char const *needle_byte_c = (unsigned char const *)needle; + return _memmem (haystack_byte_c, haystack_len, needle_byte_c, needle_len); +} + char * strstr (char const *haystack, char const *needle) { - eputs ("strstr stub\n"); - return 0; + return memmem (haystack, strlen (haystack), needle, strlen (needle)); } double