xstring.cc
Go to the documentation of this file.
1/*
2 * Copyright (C) 1996-2022 The Squid Software Foundation and contributors
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
9#include "squid.h"
10#include "compat/xalloc.h"
11#include "compat/xstring.h"
12
13#include <cerrno>
14
15char *
16xstrdup(const char *s)
17{
18 if (!s) {
19 if (failure_notify) {
20 (*failure_notify) ("xstrdup: tried to dup a nullptr!\n");
21 } else {
22 errno = EINVAL;
23 perror("xstrdup: tried to dup a nullptr!");
24 }
25 exit(1);
26 }
27
28 /* copy string, including terminating character */
29 size_t sz = strlen(s) + 1;
30 char *p = static_cast<char *>(xmalloc(sz));
31 memcpy(p, s, sz);
32
33 return p;
34}
35
36char *
37xstrncpy(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)
45 while (--n != 0 && *src != '\0') {
46 *dst = *src;
47 ++dst;
48 ++src;
49 }
50
51 *dst = '\0';
52 return r;
53}
54
55char *
56xstrndup(const char *s, size_t n)
57{
58 if (!s) {
59 errno = EINVAL;
60 if (failure_notify) {
61 (*failure_notify) ("xstrndup: tried to dup a nullptr!\n");
62 } else {
63 perror("xstrndup: tried to dup a nullptr!");
64 }
65 exit(1);
66 }
67
68 size_t sz = strlen(s) + 1;
69 // size_t is unsigned, as mandated by c99 and c++ standards.
70 if (sz > n)
71 sz = n;
72
73 char *p = xstrncpy(static_cast<char *>(xmalloc(sz)), s, sz);
74 return p;
75}
76
void(* failure_notify)(const char *)
Definition: compat.cc:12
#define xmalloc
void const char int sz
Definition: stub_cbdata.cc:16
char * xstrncpy(char *dst, const char *src, size_t n)
Definition: xstring.cc:37
char * xstrdup(const char *s)
Definition: xstring.cc:16
char * xstrndup(const char *s, size_t n)
Definition: xstring.cc:56

 

Introduction

Documentation

Support

Miscellaneous

Web Site Translations

Mirrors