compat_string.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. #include <string.h>
  16. /** Helper for tor_strtok_r_impl: Advances cp past all characters in
  17. * <b>sep</b>, and returns its new value. */
  18. static char *
  19. strtok_helper(char *cp, const char *sep)
  20. {
  21. if (sep[1]) {
  22. while (*cp && strchr(sep, *cp))
  23. ++cp;
  24. } else {
  25. while (*cp && *cp == *sep)
  26. ++cp;
  27. }
  28. return cp;
  29. }
  30. /** Implementation of strtok_r for platforms whose coders haven't figured out
  31. * how to write one. Hey, retrograde libc developers! You can use this code
  32. * here for free! */
  33. char *
  34. tor_strtok_r_impl(char *str, const char *sep, char **lasts)
  35. {
  36. char *cp, *start;
  37. raw_assert(*sep);
  38. if (str) {
  39. str = strtok_helper(str, sep);
  40. if (!*str)
  41. return NULL;
  42. start = cp = *lasts = str;
  43. } else if (!*lasts || !**lasts) {
  44. return NULL;
  45. } else {
  46. start = cp = *lasts;
  47. }
  48. if (sep[1]) {
  49. while (*cp && !strchr(sep, *cp))
  50. ++cp;
  51. } else {
  52. cp = strchr(cp, *sep);
  53. }
  54. if (!cp || !*cp) {
  55. *lasts = NULL;
  56. } else {
  57. *cp++ = '\0';
  58. *lasts = strtok_helper(cp, sep);
  59. }
  60. return start;
  61. }