server/src/util/bsdstring.c

84 lines
1.7 KiB
C
Raw Normal View History

2010-08-08 10:06:34 +02:00
#include <platform.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#ifndef HAVE_INLINE
#include "bsdstring.h"
#endif
2011-03-07 08:02:35 +01:00
INLINE_FUNCTION int wrptr(char **ptr, size_t * size, int bytes)
2010-08-08 10:06:34 +02:00
{
2011-03-07 08:02:35 +01:00
assert(bytes >= 0 || !"you're not using snprintf right, maybe?");
2010-08-08 10:06:34 +02:00
2011-03-07 08:02:35 +01:00
if (bytes == 0) {
2010-08-08 10:06:34 +02:00
return 0;
}
2011-03-07 08:02:35 +01:00
if (bytes < 0) {
2010-08-08 10:06:34 +02:00
*size = 0;
return EINVAL;
}
2011-03-07 08:02:35 +01:00
if (bytes <= *(int *)size) {
2010-08-08 10:06:34 +02:00
*ptr += bytes;
*size -= bytes;
return 0;
}
*ptr += *size;
*size = 0;
return ENAMETOOLONG;
}
#if !defined(HAVE_STRLCPY)
2011-03-07 08:02:35 +01:00
INLINE_FUNCTION size_t strlcpy(char *dst, const char *src, size_t siz)
{ /* copied from OpenBSD source code */
2010-08-08 10:06:34 +02:00
register char *d = dst;
register const char *s = src;
register size_t n = siz;
/* Copy as many bytes as will fit */
if (n != 0 && --n != 0) {
do {
if ((*d++ = *s++) == 0)
break;
} while (--n != 0);
}
/* Not enough room in dst, add NUL and traverse rest of src */
if (n == 0) {
if (siz != 0)
2011-03-07 08:02:35 +01:00
*d = '\0'; /* NUL-terminate dst */
while (*s++) ;
2010-08-08 10:06:34 +02:00
}
2011-03-07 08:02:35 +01:00
return (s - src - 1); /* count does not include NUL */
2010-08-08 10:06:34 +02:00
}
2011-03-07 08:02:35 +01:00
INLINE_FUNCTION size_t strlcat(char *dst, const char *src, size_t siz)
2010-08-08 10:06:34 +02:00
{
register char *d = dst;
register const char *s = src;
register size_t n = siz;
size_t dlen;
/* Find the end of dst and adjust bytes left but don't go past end */
while (*d != '\0' && n-- != 0)
d++;
dlen = d - dst;
n = siz - dlen;
if (n == 0)
2011-03-07 08:02:35 +01:00
return (dlen + strlen(s));
2010-08-08 10:06:34 +02:00
while (*s != '\0') {
if (n != 1) {
*d++ = *s;
n--;
}
s++;
}
*d = '\0';
2011-03-07 08:02:35 +01:00
return (dlen + (s - src)); /* count does not include NUL */
2010-08-08 10:06:34 +02:00
}
#endif