string.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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'.
  38. * Otherwise it will return -EINVAL. Value pointed to by res is
  39. * updated upon finding a match.
  40. */
  41. int strtobool(const char *s, bool *res)
  42. {
  43. switch (s[0]) {
  44. case 'y':
  45. case 'Y':
  46. case '1':
  47. *res = true;
  48. break;
  49. case 'n':
  50. case 'N':
  51. case '0':
  52. *res = false;
  53. break;
  54. default:
  55. return -EINVAL;
  56. }
  57. return 0;
  58. }
  59. /**
  60. * strlcpy - Copy a C-string into a sized buffer
  61. * @dest: Where to copy the string to
  62. * @src: Where to copy the string from
  63. * @size: size of destination buffer
  64. *
  65. * Compatible with *BSD: the result is always a valid
  66. * NUL-terminated string that fits in the buffer (unless,
  67. * of course, the buffer size is zero). It does not pad
  68. * out the result like strncpy() does.
  69. *
  70. * If libc has strlcpy() then that version will override this
  71. * implementation:
  72. */
  73. size_t __weak strlcpy(char *dest, const char *src, size_t size)
  74. {
  75. size_t ret = strlen(src);
  76. if (size) {
  77. size_t len = (ret >= size) ? size - 1 : ret;
  78. memcpy(dest, src, len);
  79. dest[len] = '\0';
  80. }
  81. return ret;
  82. }