compat_string.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. #include "lib/string/compat_string.h"
  6. #include "lib/err/torerr.h"
  7. /* Inline the strl functions if the platform doesn't have them. */
  8. #ifndef HAVE_STRLCPY
  9. #include "strlcpy.c"
  10. #endif
  11. #ifndef HAVE_STRLCAT
  12. #include "strlcat.c"
  13. #endif
  14. #include <stdlib.h>
  15. /** Helper for tor_strtok_r_impl: Advances cp past all characters in
  16. * <b>sep</b>, and returns its new value. */
  17. static char *
  18. strtok_helper(char *cp, const char *sep)
  19. {
  20. if (sep[1]) {
  21. while (*cp && strchr(sep, *cp))
  22. ++cp;
  23. } else {
  24. while (*cp && *cp == *sep)
  25. ++cp;
  26. }
  27. return cp;
  28. }
  29. /** Implementation of strtok_r for platforms whose coders haven't figured out
  30. * how to write one. Hey, retrograde libc developers! You can use this code
  31. * here for free! */
  32. char *
  33. tor_strtok_r_impl(char *str, const char *sep, char **lasts)
  34. {
  35. char *cp, *start;
  36. raw_assert(*sep);
  37. if (str) {
  38. str = strtok_helper(str, sep);
  39. if (!*str)
  40. return NULL;
  41. start = cp = *lasts = str;
  42. } else if (!*lasts || !**lasts) {
  43. return NULL;
  44. } else {
  45. start = cp = *lasts;
  46. }
  47. if (sep[1]) {
  48. while (*cp && !strchr(sep, *cp))
  49. ++cp;
  50. } else {
  51. cp = strchr(cp, *sep);
  52. }
  53. if (!cp || !*cp) {
  54. *lasts = NULL;
  55. } else {
  56. *cp++ = '\0';
  57. *lasts = strtok_helper(cp, sep);
  58. }
  59. return start;
  60. }