lsearch.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /* Linear search functions.
  2. Copyright (C) 1996-2019 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. Contributed by Ulrich Drepper <drepper@cygnus.com>, 1996.
  5. The GNU C Library is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU Lesser General Public
  7. License as published by the Free Software Foundation; either
  8. version 2.1 of the License, or (at your option) any later version.
  9. The GNU C Library is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. Lesser General Public License for more details.
  13. You should have received a copy of the GNU Lesser General Public
  14. License along with the GNU C Library; if not, see
  15. <http://www.gnu.org/licenses/>. */
  16. #include <search.h>
  17. #include <string.h>
  18. void *
  19. lsearch (const void *key, void *base, size_t *nmemb, size_t size,
  20. __compar_fn_t compar)
  21. {
  22. void *result;
  23. /* Try to find it. */
  24. result = lfind (key, base, nmemb, size, compar);
  25. if (result == NULL)
  26. {
  27. /* Not available. Insert at the end. */
  28. result = memcpy (base + (*nmemb) * size, key, size);
  29. ++(*nmemb);
  30. }
  31. return result;
  32. }
  33. void *
  34. lfind (const void *key, const void *base, size_t *nmemb, size_t size,
  35. __compar_fn_t compar)
  36. {
  37. const void *result = base;
  38. size_t cnt = 0;
  39. while (cnt < *nmemb && (*compar) (key, result) != 0)
  40. {
  41. result += size;
  42. ++cnt;
  43. }
  44. return cnt < *nmemb ? (void *) result : NULL;
  45. }
  46. libc_hidden_def (lfind)