strings.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/BuiltinWrappers.h>
  7. #include <assert.h>
  8. #include <ctype.h>
  9. #include <string.h>
  10. #include <strings.h>
  11. extern "C" {
  12. void bzero(void* dest, size_t n)
  13. {
  14. memset(dest, 0, n);
  15. }
  16. void bcopy(void const* src, void* dest, size_t n)
  17. {
  18. memmove(dest, src, n);
  19. }
  20. static char foldcase(char ch)
  21. {
  22. if (isalpha(ch))
  23. return tolower(ch);
  24. return ch;
  25. }
  26. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/strcasecmp.html
  27. int strcasecmp(char const* s1, char const* s2)
  28. {
  29. for (; foldcase(*s1) == foldcase(*s2); ++s1, ++s2) {
  30. if (*s1 == 0)
  31. return 0;
  32. }
  33. return foldcase(*(unsigned char const*)s1) < foldcase(*(unsigned char const*)s2) ? -1 : 1;
  34. }
  35. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/strncasecmp.html
  36. int strncasecmp(char const* s1, char const* s2, size_t n)
  37. {
  38. if (!n)
  39. return 0;
  40. do {
  41. if (foldcase(*s1) != foldcase(*s2++))
  42. return foldcase(*(unsigned char const*)s1) - foldcase(*(unsigned char const*)--s2);
  43. if (*s1++ == 0)
  44. break;
  45. } while (--n);
  46. return 0;
  47. }
  48. // https://pubs.opengroup.org/onlinepubs/009696799/functions/ffs.html
  49. int ffs(int i)
  50. {
  51. return bit_scan_forward(i);
  52. }
  53. // https://linux.die.net/man/3/ffsl (GNU extension)
  54. int ffsl(long int i)
  55. {
  56. return bit_scan_forward(i);
  57. }
  58. // https://linux.die.net/man/3/ffsll (GNU extension)
  59. int ffsll(long long int i)
  60. {
  61. return bit_scan_forward(i);
  62. }
  63. }