File: distrutils.c

package info (click to toggle)
di 6.2.2.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 896 kB
  • sloc: ansic: 9,364; sh: 5,211; perl: 1,749; awk: 463; makefile: 398
file content (147 lines) | stat: -rw-r--r-- 2,205 bytes parent folder | download
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
/*
 * Copyright 1994-2026 Brad Lanam, Walnut Creek, CA
 * Copyright 2023-2026 Brad Lanam, Pleasant Hill, CA
 */

#include "config.h"

#if _hdr_stdio
#  include <stdio.h>
#endif
# if _hdr_stdlib
#  include <stdlib.h>
# endif
# if _hdr_memory
#  include <memory.h>
# endif
# if _hdr_malloc
#  include <malloc.h>
# endif
# if _hdr_string
#  include <string.h>
# endif
# if _hdr_strings
#  include <strings.h>
# endif

#include "distrutils.h"

/*
 *
 * portable realloc
 * some very old variants don't accept a null pointer for initial allocation.
 *
 */

void *
di_realloc (void * ptr, Size_t size)
{
  if (ptr == (void *) NULL) {
    ptr = (void *) malloc (size);
  } else {
    ptr = (void *) realloc (ptr, size);
  }

  return ptr;
}

void
di_trimchar (char *str, int ch)
{
  int     len;

  len = (int) strlen (str);
  if (len > 0) {
    --len;
  }
  if (len >= 0) {
    if (str [len] == ch) {
      str [len] = '\0';
    }
  }
}

char *
di_strtok (char *str, const char *delim, char **tokstr)
{
  char    *ptr = NULL;

#if _lib_strtok_r
  ptr = strtok_r (str, delim, tokstr);
#else
  ptr = strtok_r (str, delim);
#endif

  return ptr;
}

#if ! _lib_stpecpy

/* the following code is in the public domain */
/* modified from the linux stpecpy manual page */

char *
stpecpy (char *dst, char *end, const char *src)
{
  char  *p;

  if (dst == end) {
    return end;
  }

  p = (char *) memccpy (dst, src, '\0', (Size_t) (end - dst));
  if (p != NULL) {
    return p - 1;
  }

  /* truncation detected */
  end [-1] = '\0';
  return end;
}

#endif /* ! _lib_stpecpy */

#if ! _lib_strdup

char *
strdup (const char *ptr)
{
  Size_t        len;
  char          *nptr;

  if (ptr == NULL) {
    return NULL;
  }

  len = strlen (ptr);
  nptr = (char *) malloc (len + 1);
  stpecpy (nptr, nptr + len + 1, ptr);
  return nptr;
}

#endif /* ! _lib_strdup */

#if ! _lib_strstr

char *
strstr (const char *buff, const char *srch)
{
  Size_t    len;
  char *    p;

  p = buff;
  if (srch == NULL) {
    return p;
  }

  len = strlen (srch);
  for (; (p = strchr (p, *srch)) != NULL; p++) {
    if (strncmp (p, srch, len) == 0) {
      return (p);
    }
  }

  return (char *) NULL;
}

#endif /* ! _lib_strstr */