string.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. /*
  2. * linux/tools/lib/string.c
  3. *
  4. * Copied from linux/lib/string.c, where it is:
  5. *
  6. * Copyright (C) 1991, 1992 Linus Torvalds
  7. *
  8. * More specifically, the first copied function was strtobool, which
  9. * was introduced by:
  10. *
  11. * d0f1fed29e6e ("Add a strtobool function matching semantics of existing in kernel equivalents")
  12. * Author: Jonathan Cameron <jic23@cam.ac.uk>
  13. */
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #include <errno.h>
  17. #include <linux/string.h>
  18. #include <linux/compiler.h>
  19. /**
  20. * memdup - duplicate region of memory
  21. *
  22. * @src: memory region to duplicate
  23. * @len: memory region length
  24. */
  25. void *memdup(const void *src, size_t len)
  26. {
  27. void *p = malloc(len);
  28. if (p)
  29. memcpy(p, src, len);
  30. return p;
  31. }
  32. /**
  33. * strtobool - convert common user inputs into boolean values
  34. * @s: input string
  35. * @res: result
  36. *
  37. * This routine returns 0 iff the first character is one of 'Yy1Nn0', or
  38. * [oO][NnFf] for "on" and "off". Otherwise it will return -EINVAL. Value
  39. * pointed to by res is updated upon finding a match.
  40. */
  41. int strtobool(const char *s, bool *res)
  42. {
  43. if (!s)
  44. return -EINVAL;
  45. switch (s[0]) {
  46. case 'y':
  47. case 'Y':
  48. case '1':
  49. *res = true;
  50. return 0;
  51. case 'n':
  52. case 'N':
  53. case '0':
  54. *res = false;
  55. return 0;
  56. case 'o':
  57. case 'O':
  58. switch (s[1]) {
  59. case 'n':
  60. case 'N':
  61. *res = true;
  62. return 0;
  63. case 'f':
  64. case 'F':
  65. *res = false;
  66. return 0;
  67. default:
  68. break;
  69. }
  70. default:
  71. break;
  72. }
  73. return -EINVAL;
  74. }
  75. /**
  76. * strlcpy - Copy a C-string into a sized buffer
  77. * @dest: Where to copy the string to
  78. * @src: Where to copy the string from
  79. * @size: size of destination buffer
  80. *
  81. * Compatible with *BSD: the result is always a valid
  82. * NUL-terminated string that fits in the buffer (unless,
  83. * of course, the buffer size is zero). It does not pad
  84. * out the result like strncpy() does.
  85. *
  86. * If libc has strlcpy() then that version will override this
  87. * implementation:
  88. */
  89. size_t __weak strlcpy(char *dest, const char *src, size_t size)
  90. {
  91. size_t ret = strlen(src);
  92. if (size) {
  93. size_t len = (ret >= size) ? size - 1 : ret;
  94. memcpy(dest, src, len);
  95. dest[len] = '\0';
  96. }
  97. return ret;
  98. }