]> git.ipfire.org Git - thirdparty/squid.git/blob - compat/xstring.cc
Updated 3.2 release notes
[thirdparty/squid.git] / compat / xstring.cc
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
9 char *
10 xstrdup(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
33 char *
34 xstrncpy(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
49 char *
50 xstrndup(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 }
64 if (n < 0) {
65 errno = EINVAL;
66 if (failure_notify) {
67 (*failure_notify) ("xstrndup: tried to dup a negative length string!\n");
68 } else {
69 perror("xstrndup: tried to dup a negative length string!");
70 }
71 exit(1);
72 }
73
74 sz = strlen(s) + 1;
75 if (sz > n)
76 sz = n;
77
78 p = xstrncpy((char *)xmalloc(sz), s, sz);
79 return p;
80 }