string.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Taken from:
  4. * linux/lib/string.c
  5. *
  6. * Copyright (C) 1991, 1992 Linus Torvalds
  7. */
  8. #include <linux/ctype.h>
  9. #include <linux/kernel.h>
  10. #include <linux/types.h>
  11. #include <linux/string.h>
  12. #ifndef __HAVE_ARCH_STRSTR
  13. /**
  14. * strstr - Find the first substring in a %NUL terminated string
  15. * @s1: The string to be searched
  16. * @s2: The string to search for
  17. */
  18. char *strstr(const char *s1, const char *s2)
  19. {
  20. size_t l1, l2;
  21. l2 = strlen(s2);
  22. if (!l2)
  23. return (char *)s1;
  24. l1 = strlen(s1);
  25. while (l1 >= l2) {
  26. l1--;
  27. if (!memcmp(s1, s2, l2))
  28. return (char *)s1;
  29. s1++;
  30. }
  31. return NULL;
  32. }
  33. #endif
  34. #ifndef __HAVE_ARCH_STRNCMP
  35. /**
  36. * strncmp - Compare two length-limited strings
  37. * @cs: One string
  38. * @ct: Another string
  39. * @count: The maximum number of bytes to compare
  40. */
  41. int strncmp(const char *cs, const char *ct, size_t count)
  42. {
  43. unsigned char c1, c2;
  44. while (count) {
  45. c1 = *cs++;
  46. c2 = *ct++;
  47. if (c1 != c2)
  48. return c1 < c2 ? -1 : 1;
  49. if (!c1)
  50. break;
  51. count--;
  52. }
  53. return 0;
  54. }
  55. #endif
  56. /* Works only for digits and letters, but small and fast */
  57. #define TOLOWER(x) ((x) | 0x20)
  58. static unsigned int simple_guess_base(const char *cp)
  59. {
  60. if (cp[0] == '0') {
  61. if (TOLOWER(cp[1]) == 'x' && isxdigit(cp[2]))
  62. return 16;
  63. else
  64. return 8;
  65. } else {
  66. return 10;
  67. }
  68. }
  69. /**
  70. * simple_strtoull - convert a string to an unsigned long long
  71. * @cp: The start of the string
  72. * @endp: A pointer to the end of the parsed string will be placed here
  73. * @base: The number base to use
  74. */
  75. unsigned long long simple_strtoull(const char *cp, char **endp, unsigned int base)
  76. {
  77. unsigned long long result = 0;
  78. if (!base)
  79. base = simple_guess_base(cp);
  80. if (base == 16 && cp[0] == '0' && TOLOWER(cp[1]) == 'x')
  81. cp += 2;
  82. while (isxdigit(*cp)) {
  83. unsigned int value;
  84. value = isdigit(*cp) ? *cp - '0' : TOLOWER(*cp) - 'a' + 10;
  85. if (value >= base)
  86. break;
  87. result = result * base + value;
  88. cp++;
  89. }
  90. if (endp)
  91. *endp = (char *)cp;
  92. return result;
  93. }
  94. long simple_strtol(const char *cp, char **endp, unsigned int base)
  95. {
  96. if (*cp == '-')
  97. return -simple_strtoull(cp + 1, endp, base);
  98. return simple_strtoull(cp, endp, base);
  99. }