Back to index

glibc  2.9
lsearch.c
Go to the documentation of this file.
00001 /* Linear search functions.
00002    Copyright (C) 1996,97,98,2002 Free Software Foundation, Inc.
00003    This file is part of the GNU C Library.
00004    Contributed by Ulrich Drepper <drepper@cygnus.com>, 1996.
00005 
00006    The GNU C Library is free software; you can redistribute it and/or
00007    modify it under the terms of the GNU Lesser General Public
00008    License as published by the Free Software Foundation; either
00009    version 2.1 of the License, or (at your option) any later version.
00010 
00011    The GNU C Library is distributed in the hope that it will be useful,
00012    but WITHOUT ANY WARRANTY; without even the implied warranty of
00013    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00014    Lesser General Public License for more details.
00015 
00016    You should have received a copy of the GNU Lesser General Public
00017    License along with the GNU C Library; if not, write to the Free
00018    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
00019    02111-1307 USA.  */
00020 
00021 #include <search.h>
00022 #include <string.h>
00023 
00024 
00025 void *
00026 lsearch (const void *key, void *base, size_t *nmemb, size_t size,
00027         __compar_fn_t compar)
00028 {
00029   void *result;
00030 
00031   /* Try to find it.  */
00032   result = lfind (key, base, nmemb, size, compar);
00033   if (result == NULL)
00034     {
00035       /* Not available.  Insert at the end.  */
00036       result = memcpy (base + (*nmemb) * size, key, size);
00037       ++(*nmemb);
00038     }
00039 
00040   return result;
00041 }
00042 
00043 
00044 void *
00045 lfind (const void *key, const void *base, size_t *nmemb, size_t size,
00046        __compar_fn_t compar)
00047 {
00048   const void *result = base;
00049   size_t cnt = 0;
00050 
00051   while (cnt < *nmemb && (*compar) (key, result) != 0)
00052     {
00053       result += size;
00054       ++cnt;
00055     }
00056 
00057   return cnt < *nmemb ? (void *) result : NULL;
00058 }
00059 libc_hidden_def (lfind)