]>
Commit | Line | Data |
---|---|---|
37be9888 | 1 | /* |
5b74111a | 2 | * Copyright (C) 1996-2018 The Squid Software Foundation and contributors |
37be9888 AJ |
3 | * |
4 | * Squid software is distributed under GPLv2+ license and includes | |
5 | * contributions from numerous individuals and organizations. | |
6 | * Please see the COPYING and CONTRIBUTORS files for details. | |
7 | */ | |
8 | ||
f7f3304a | 9 | #include "squid.h" |
25f98340 AJ |
10 | #include "compat/xalloc.h" |
11 | #include "compat/xstring.h" | |
12 | ||
1a30fdf5 | 13 | #include <cerrno> |
25f98340 AJ |
14 | |
15 | char * | |
16 | xstrdup(const char *s) | |
17 | { | |
2266451a | 18 | if (!s) { |
25f98340 AJ |
19 | if (failure_notify) { |
20 | (*failure_notify) ("xstrdup: tried to dup a NULL pointer!\n"); | |
21 | } else { | |
22 | errno = EINVAL; | |
23 | perror("xstrdup: tried to dup a NULL pointer!"); | |
24 | } | |
25 | exit(1); | |
26 | } | |
27 | ||
28 | /* copy string, including terminating character */ | |
2266451a AJ |
29 | size_t sz = strlen(s) + 1; |
30 | char *p = static_cast<char *>(xmalloc(sz)); | |
25f98340 AJ |
31 | memcpy(p, s, sz); |
32 | ||
33 | return p; | |
34 | } | |
35 | ||
36 | char * | |
37 | xstrncpy(char *dst, const char *src, size_t n) | |
38 | { | |
39 | char *r = dst; | |
40 | ||
41 | if (!n || !dst) | |
42 | return dst; | |
43 | ||
44 | if (src) | |
14942edd | 45 | while (--n != 0 && *src != '\0') { |
f207fe64 FC |
46 | *dst = *src; |
47 | ++dst; | |
14942edd FC |
48 | ++src; |
49 | } | |
25f98340 AJ |
50 | |
51 | *dst = '\0'; | |
52 | return r; | |
53 | } | |
54 | ||
55 | char * | |
56 | xstrndup(const char *s, size_t n) | |
57 | { | |
2266451a | 58 | if (!s) { |
25f98340 AJ |
59 | errno = EINVAL; |
60 | if (failure_notify) { | |
61 | (*failure_notify) ("xstrndup: tried to dup a NULL pointer!\n"); | |
62 | } else { | |
63 | perror("xstrndup: tried to dup a NULL pointer!"); | |
64 | } | |
65 | exit(1); | |
66 | } | |
25f98340 | 67 | |
2266451a | 68 | size_t sz = strlen(s) + 1; |
2f9ec583 | 69 | // size_t is unsigned, as mandated by c99 and c++ standards. |
25f98340 AJ |
70 | if (sz > n) |
71 | sz = n; | |
72 | ||
2266451a | 73 | char *p = xstrncpy(static_cast<char *>(xmalloc(sz)), s, sz); |
25f98340 AJ |
74 | return p; |
75 | } | |
f53969cc | 76 |