File: xstring.cc

package info (click to toggle)
squid3 3.4.8-6
  • links: PTS
  • area: main
  • in suites: jessie-kfreebsd
  • size: 31,084 kB
  • sloc: cpp: 165,325; ansic: 21,998; sh: 12,166; makefile: 5,964; perl: 2,153; sql: 322; awk: 118
file content (75 lines) | stat: -rw-r--r-- 1,395 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include "squid.h"
#include "compat/xalloc.h"
#include "compat/xstring.h"

#if HAVE_ERRNO_H
#include <errno.h>
#endif

char *
xstrdup(const char *s)
{
    size_t sz;
    char *p;

    if (s == NULL) {
        if (failure_notify) {
            (*failure_notify) ("xstrdup: tried to dup a NULL pointer!\n");
        } else {
            errno = EINVAL;
            perror("xstrdup: tried to dup a NULL pointer!");
        }
        exit(1);
    }

    /* copy string, including terminating character */
    sz = strlen(s) + 1;
    p = (char *)xmalloc(sz);
    memcpy(p, s, sz);

    return p;
}

char *
xstrncpy(char *dst, const char *src, size_t n)
{
    char *r = dst;

    if (!n || !dst)
        return dst;

    if (src)
        while (--n != 0 && *src != '\0') {
            *dst = *src;
            ++dst;
            ++src;
        }

    *dst = '\0';
    return r;
}

char *
xstrndup(const char *s, size_t n)
{
    size_t sz;
    char *p;

    if (s == NULL) {
        errno = EINVAL;
        if (failure_notify) {
            (*failure_notify) ("xstrndup: tried to dup a NULL pointer!\n");
        } else {
            perror("xstrndup: tried to dup a NULL pointer!");
        }
        exit(1);
    }

    sz = strlen(s) + 1;
    // size_t is unsigned, as mandated by c99 and c++ standards.
    if (sz > n)
        sz = n;

    p = xstrncpy((char *)xmalloc(sz), s, sz);
    return p;
}