-
Notifications
You must be signed in to change notification settings - Fork 1
/
strmem.c
163 lines (138 loc) · 2.55 KB
/
strmem.c
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
/**
* \file strmem.c
* \brief Methods to str functions.
*
* include LICENSE
*/
#define _GNU_SOURCE /* for strcasestr */
#include <string.h>
#include <strmem.h>
#ifdef TRACE_MEM
#include <tracemem.h>
#endif
/** \brief Wrapper for strdup().
*
* Returns a copy of the passed in string. The returned copy must be
* free'd.
*
* There is no need to check the returned value, since this function will
* terminate the program if the memory allocation fails.
*
* It is safe to pass a NULL pointer. No memory is allocated if a NULL is
* passed.
*/
char *app_strndup(const char *s, int size)
{
if (s) {
char *ptr = app_new(char, size + 1);
if (ptr) {
memcpy(ptr, s, size);
ptr[size] = '\0';
return ptr;
}
msg_fatal(_("strndup failed"));
}
return NULL;
}
char *app_strdup(const char *s)
{
if (s) {
return app_strndup(s, strlen(s));
}
return NULL;
}
/** \brief return a power of 2 value greater than size.
*
*/
unsigned int app_power_of_2(unsigned int size)
{
unsigned int newsize = 1;
while (newsize < size) {
newsize <<= 1;
}
return newsize;
}
void app_dup_str(char **varp, char *str)
{
app_free(*varp);
if (str) {
*varp = app_strdup(str);
} else {
*varp = NULL;
}
}
/*
* just to avoid segmentation fault
*/
int app_strlen(const char *s)
{
if (s) {
return strlen(s);
}
return 0;
}
char *app_strcpy(char *s1, const char *s2)
{
if (s1 && s2) {
return strcpy(s1, s2);
}
return NULL;
}
char *app_strncpy(char *s1, const char *s2, int n)
{
if (s1 && s2) {
return strncpy(s1, s2, n);
}
return NULL;
}
int app_strcmp(const char *s1, const char *s2)
{
if (s1 && s2) {
return strcmp(s1, s2);
}
return 1; /* not egal */
}
int app_strncmp(const char *s1, const char *s2, int n)
{
if (s1 && s2) {
return strncmp(s1, s2, n);
}
return 1; /* not egal */
}
int app_strcasecmp(const char *s1, const char *s2)
{
if (s1 && s2) {
return strcasecmp(s1, s2);
}
return 1; /* not egal */
}
int app_strncasecmp(const char *s1, const char *s2, int n)
{
if (s1 && s2) {
return strncasecmp(s1, s2, n);
}
return 1; /* not egal */
}
char *app_strcasestr(const char *s1, const char *s2)
{
if (s1 && s2) {
return strcasestr(s1, s2);
}
return NULL;
}
char *app_strstr(const char *s1, const char *s2)
{
if (s1 && s2) {
return strstr(s1, s2);
}
return NULL;
}
/*
* special for trace memory
*/
#ifdef TRACE_MEM
void str_free_func(void *ptr)
{
app_free(ptr);
}
#endif