]> git.ipfire.org Git - thirdparty/squid.git/blame - compat/xstring.cc
Remove unnecessary stub_tools dependency on String
[thirdparty/squid.git] / compat / xstring.cc
CommitLineData
25f98340
AJ
1#include "config.h"
2#include "compat/xalloc.h"
3#include "compat/xstring.h"
4
5#if HAVE_ERRNO_H
6#include <errno.h>
7#endif
8
9char *
10xstrdup(const char *s)
11{
12 size_t sz;
13 char *p;
14
15 if (s == NULL) {
16 if (failure_notify) {
17 (*failure_notify) ("xstrdup: tried to dup a NULL pointer!\n");
18 } else {
19 errno = EINVAL;
20 perror("xstrdup: tried to dup a NULL pointer!");
21 }
22 exit(1);
23 }
24
25 /* copy string, including terminating character */
26 sz = strlen(s) + 1;
27 p = (char *)xmalloc(sz);
28 memcpy(p, s, sz);
29
30 return p;
31}
32
33char *
34xstrncpy(char *dst, const char *src, size_t n)
35{
36 char *r = dst;
37
38 if (!n || !dst)
39 return dst;
40
41 if (src)
42 while (--n != 0 && *src != '\0')
43 *dst++ = *src++;
44
45 *dst = '\0';
46 return r;
47}
48
49char *
50xstrndup(const char *s, size_t n)
51{
52 size_t sz;
53 char *p;
54
55 if (s == NULL) {
56 errno = EINVAL;
57 if (failure_notify) {
58 (*failure_notify) ("xstrndup: tried to dup a NULL pointer!\n");
59 } else {
60 perror("xstrndup: tried to dup a NULL pointer!");
61 }
62 exit(1);
63 }
25f98340
AJ
64
65 sz = strlen(s) + 1;
2f9ec583 66 // size_t is unsigned, as mandated by c99 and c++ standards.
25f98340
AJ
67 if (sz > n)
68 sz = n;
69
70 p = xstrncpy((char *)xmalloc(sz), s, sz);
71 return p;
72}