strings.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <assert.h>
  7. #include <ctype.h>
  8. #include <string.h>
  9. #include <strings.h>
  10. extern "C" {
  11. void bzero(void* dest, size_t n)
  12. {
  13. memset(dest, 0, n);
  14. }
  15. void bcopy(const void* src, void* dest, size_t n)
  16. {
  17. memmove(dest, src, n);
  18. }
  19. static char foldcase(char ch)
  20. {
  21. if (isalpha(ch))
  22. return tolower(ch);
  23. return ch;
  24. }
  25. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/strcasecmp.html
  26. int strcasecmp(const char* s1, const char* s2)
  27. {
  28. for (; foldcase(*s1) == foldcase(*s2); ++s1, ++s2) {
  29. if (*s1 == 0)
  30. return 0;
  31. }
  32. return foldcase(*(const unsigned char*)s1) < foldcase(*(const unsigned char*)s2) ? -1 : 1;
  33. }
  34. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/strncasecmp.html
  35. int strncasecmp(const char* s1, const char* s2, size_t n)
  36. {
  37. if (!n)
  38. return 0;
  39. do {
  40. if (foldcase(*s1) != foldcase(*s2++))
  41. return foldcase(*(const unsigned char*)s1) - foldcase(*(const unsigned char*)--s2);
  42. if (*s1++ == 0)
  43. break;
  44. } while (--n);
  45. return 0;
  46. }
  47. }