string.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. /* -*- linux-c -*- ------------------------------------------------------- *
  2. *
  3. * Copyright (C) 1991, 1992 Linus Torvalds
  4. * Copyright 2007 rPath, Inc. - All Rights Reserved
  5. *
  6. * This file is part of the Linux kernel, and is made available under
  7. * the terms of the GNU General Public License version 2.
  8. *
  9. * ----------------------------------------------------------------------- */
  10. /*
  11. * Very basic string functions
  12. */
  13. #include "boot.h"
  14. int strcmp(const char *str1, const char *str2)
  15. {
  16. const unsigned char *s1 = (const unsigned char *)str1;
  17. const unsigned char *s2 = (const unsigned char *)str2;
  18. int delta = 0;
  19. while (*s1 || *s2) {
  20. delta = *s2 - *s1;
  21. if (delta)
  22. return delta;
  23. s1++;
  24. s2++;
  25. }
  26. return 0;
  27. }
  28. int strncmp(const char *cs, const char *ct, size_t count)
  29. {
  30. unsigned char c1, c2;
  31. while (count) {
  32. c1 = *cs++;
  33. c2 = *ct++;
  34. if (c1 != c2)
  35. return c1 < c2 ? -1 : 1;
  36. if (!c1)
  37. break;
  38. count--;
  39. }
  40. return 0;
  41. }
  42. size_t strnlen(const char *s, size_t maxlen)
  43. {
  44. const char *es = s;
  45. while (*es && maxlen) {
  46. es++;
  47. maxlen--;
  48. }
  49. return (es - s);
  50. }
  51. unsigned int atou(const char *s)
  52. {
  53. unsigned int i = 0;
  54. while (isdigit(*s))
  55. i = i * 10 + (*s++ - '0');
  56. return i;
  57. }
  58. /* Works only for digits and letters, but small and fast */
  59. #define TOLOWER(x) ((x) | 0x20)
  60. static unsigned int simple_guess_base(const char *cp)
  61. {
  62. if (cp[0] == '0') {
  63. if (TOLOWER(cp[1]) == 'x' && isxdigit(cp[2]))
  64. return 16;
  65. else
  66. return 8;
  67. } else {
  68. return 10;
  69. }
  70. }
  71. /**
  72. * simple_strtoull - convert a string to an unsigned long long
  73. * @cp: The start of the string
  74. * @endp: A pointer to the end of the parsed string will be placed here
  75. * @base: The number base to use
  76. */
  77. unsigned long long simple_strtoull(const char *cp, char **endp, unsigned int base)
  78. {
  79. unsigned long long result = 0;
  80. if (!base)
  81. base = simple_guess_base(cp);
  82. if (base == 16 && cp[0] == '0' && TOLOWER(cp[1]) == 'x')
  83. cp += 2;
  84. while (isxdigit(*cp)) {
  85. unsigned int value;
  86. value = isdigit(*cp) ? *cp - '0' : TOLOWER(*cp) - 'a' + 10;
  87. if (value >= base)
  88. break;
  89. result = result * base + value;
  90. cp++;
  91. }
  92. if (endp)
  93. *endp = (char *)cp;
  94. return result;
  95. }