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