blob: 00d03194d7246fc5e999a148fd3d47ab6ede9fae [file] [log] [blame]
paul718e3742002-12-13 20:15:29 +00001/*
2 * zebra string function
3 *
ajs851adbd2005-04-02 18:48:39 +00004 * XXX This version of snprintf does not check bounds!
paul718e3742002-12-13 20:15:29 +00005 */
6
ajs851adbd2005-04-02 18:48:39 +00007/*
8 The implementations of strlcpy and strlcat are copied from rsync (GPL):
9 Copyright (C) Andrew Tridgell 1998
10 Copyright (C) 2002 by Martin Pool
11
12 Note that these are not terribly efficient, since they make more than one
13 pass over the argument strings. At some point, they should be optimized.
14*/
15
16
paul718e3742002-12-13 20:15:29 +000017#include <zebra.h>
18
paul718e3742002-12-13 20:15:29 +000019#ifndef HAVE_SNPRINTF
20/*
21 * snprint() is a real basic wrapper around the standard sprintf()
22 * without any bounds checking
23 */
24int
25snprintf(char *str, size_t size, const char *format, ...)
26{
27 va_list args;
28
29 va_start (args, format);
30
31 return vsprintf (str, format, args);
32}
33#endif
34
35#ifndef HAVE_STRLCPY
ajs851adbd2005-04-02 18:48:39 +000036/**
37 * Like strncpy but does not 0 fill the buffer and always null
38 * terminates.
39 *
40 * @param bufsize is the size of the destination buffer.
41 *
42 * @return index of the terminating byte.
43 **/
paul718e3742002-12-13 20:15:29 +000044size_t
ajs851adbd2005-04-02 18:48:39 +000045strlcpy(char *d, const char *s, size_t bufsize)
paul718e3742002-12-13 20:15:29 +000046{
ajs851adbd2005-04-02 18:48:39 +000047 size_t len = strlen(s);
48 size_t ret = len;
49 if (bufsize > 0) {
50 if (len >= bufsize)
51 len = bufsize-1;
52 memcpy(d, s, len);
53 d[len] = 0;
54 }
55 return ret;
paul718e3742002-12-13 20:15:29 +000056}
57#endif
58
59#ifndef HAVE_STRLCAT
ajs851adbd2005-04-02 18:48:39 +000060/**
61 * Like strncat() but does not 0 fill the buffer and always null
62 * terminates.
63 *
64 * @param bufsize length of the buffer, which should be one more than
65 * the maximum resulting string length.
66 **/
paul718e3742002-12-13 20:15:29 +000067size_t
ajs851adbd2005-04-02 18:48:39 +000068strlcat(char *d, const char *s, size_t bufsize)
paul718e3742002-12-13 20:15:29 +000069{
ajs851adbd2005-04-02 18:48:39 +000070 size_t len1 = strlen(d);
71 size_t len2 = strlen(s);
72 size_t ret = len1 + len2;
paul718e3742002-12-13 20:15:29 +000073
ajs851adbd2005-04-02 18:48:39 +000074 if (len1 < bufsize - 1) {
75 if (len2 >= bufsize - len1)
76 len2 = bufsize - len1 - 1;
77 memcpy(d+len1, s, len2);
78 d[len1+len2] = 0;
79 }
80 return ret;
paul718e3742002-12-13 20:15:29 +000081}
82#endif
ajs3cb98de2005-04-02 16:01:05 +000083
84#ifndef HAVE_STRNLEN
85size_t
86strnlen(const char *s, size_t maxlen)
87{
88 const char *p;
89 return (p = (const char *)memchr(s, '\0', maxlen)) ? (size_t)(p-s) : maxlen;
90}
91#endif