]> git.ipfire.org Git - thirdparty/squid.git/blame - compat/xstring.cc
SourceFormat Enforcement
[thirdparty/squid.git] / compat / xstring.cc
CommitLineData
37be9888 1/*
bde978a6 2 * Copyright (C) 1996-2015 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
15char *
16xstrdup(const char *s)
17{
18 size_t sz;
19 char *p;
20
21 if (s == NULL) {
22 if (failure_notify) {
23 (*failure_notify) ("xstrdup: tried to dup a NULL pointer!\n");
24 } else {
25 errno = EINVAL;
26 perror("xstrdup: tried to dup a NULL pointer!");
27 }
28 exit(1);
29 }
30
31 /* copy string, including terminating character */
32 sz = strlen(s) + 1;
33 p = (char *)xmalloc(sz);
34 memcpy(p, s, sz);
35
36 return p;
37}
38
39char *
40xstrncpy(char *dst, const char *src, size_t n)
41{
42 char *r = dst;
43
44 if (!n || !dst)
45 return dst;
46
47 if (src)
14942edd 48 while (--n != 0 && *src != '\0') {
f207fe64
FC
49 *dst = *src;
50 ++dst;
14942edd
FC
51 ++src;
52 }
25f98340
AJ
53
54 *dst = '\0';
55 return r;
56}
57
58char *
59xstrndup(const char *s, size_t n)
60{
61 size_t sz;
62 char *p;
63
64 if (s == NULL) {
65 errno = EINVAL;
66 if (failure_notify) {
67 (*failure_notify) ("xstrndup: tried to dup a NULL pointer!\n");
68 } else {
69 perror("xstrndup: tried to dup a NULL pointer!");
70 }
71 exit(1);
72 }
25f98340
AJ
73
74 sz = strlen(s) + 1;
2f9ec583 75 // size_t is unsigned, as mandated by c99 and c++ standards.
25f98340
AJ
76 if (sz > n)
77 sz = n;
78
79 p = xstrncpy((char *)xmalloc(sz), s, sz);
80 return p;
81}
f53969cc 82