str.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. /*
  2. * zebra string function
  3. *
  4. * XXX This version of snprintf does not check bounds!
  5. */
  6. /*
  7. The implementations of strlcpy and strlcat are copied from rsync (GPL):
  8. Copyright (C) Andrew Tridgell 1998
  9. Copyright (C) 2002 by Martin Pool
  10. Note that these are not terribly efficient, since they make more than one
  11. pass over the argument strings. At some point, they should be optimized.
  12. The implementation of strndup is copied from glibc-2.3.5:
  13. Copyright (C) 1996, 1997, 1998, 2001, 2002 Free Software Foundation, Inc.
  14. */
  15. #include <zebra.h>
  16. #ifndef HAVE_SNPRINTF
  17. /*
  18. * snprint() is a real basic wrapper around the standard sprintf()
  19. * without any bounds checking
  20. */
  21. int
  22. snprintf(char *str, size_t size, const char *format, ...)
  23. {
  24. va_list args;
  25. va_start (args, format);
  26. return vsprintf (str, format, args);
  27. }
  28. #endif
  29. #ifndef HAVE_STRLCPY
  30. /**
  31. * Like strncpy but does not 0 fill the buffer and always null
  32. * terminates.
  33. *
  34. * @param bufsize is the size of the destination buffer.
  35. *
  36. * @return index of the terminating byte.
  37. **/
  38. size_t
  39. strlcpy(char *d, const char *s, size_t bufsize)
  40. {
  41. size_t len = strlen(s);
  42. size_t ret = len;
  43. if (bufsize > 0) {
  44. if (len >= bufsize)
  45. len = bufsize-1;
  46. memcpy(d, s, len);
  47. d[len] = 0;
  48. }
  49. return ret;
  50. }
  51. #endif
  52. #ifndef HAVE_STRLCAT
  53. /**
  54. * Like strncat() but does not 0 fill the buffer and always null
  55. * terminates.
  56. *
  57. * @param bufsize length of the buffer, which should be one more than
  58. * the maximum resulting string length.
  59. **/
  60. size_t
  61. strlcat(char *d, const char *s, size_t bufsize)
  62. {
  63. size_t len1 = strlen(d);
  64. size_t len2 = strlen(s);
  65. size_t ret = len1 + len2;
  66. if (len1 < bufsize - 1) {
  67. if (len2 >= bufsize - len1)
  68. len2 = bufsize - len1 - 1;
  69. memcpy(d+len1, s, len2);
  70. d[len1+len2] = 0;
  71. }
  72. return ret;
  73. }
  74. #endif
  75. #ifndef HAVE_STRNLEN
  76. size_t
  77. strnlen(const char *s, size_t maxlen)
  78. {
  79. const char *p;
  80. return (p = (const char *)memchr(s, '\0', maxlen)) ? (size_t)(p-s) : maxlen;
  81. }
  82. #endif
  83. #ifndef HAVE_STRNDUP
  84. char *
  85. strndup (const char *s, size_t maxlen)
  86. {
  87. size_t len = strnlen (s, maxlen);
  88. char *new = (char *) malloc (len + 1);
  89. if (new == NULL)
  90. return NULL;
  91. new[len] = '\0';
  92. return (char *) memcpy (new, s, len);
  93. }
  94. #endif