-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpstring.c
69 lines (51 loc) · 1.31 KB
/
pstring.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
#include <stdlib.h>
#include <string.h>
#include "pstring.h"
void pstring_init(pstring_t* str) {
if (str == NULL)
return;
str->len = 0;
str->str = NULL;
}
bool pstring_append(pstring_t* str, const char* buff, size_t len) {
if (str == NULL || buff == NULL)
return false;
size_t size = len + (str->str ? 0 : 1);
str->str = (char*)realloc(str->str, str->len + size);
if (str->str == NULL)
return false;
memcpy(str->str + str->len, buff, len);
str->len += len;
return true;
}
bool pstring_replace(pstring_t* str, const char* buff, size_t len) {
if (str == NULL || buff == NULL)
return false;
if (str->str != NULL)
free(str->str);
pstring_init(str);
return pstring_append(str, buff, len);
}
bool pstring_substring(pstring_t* str, size_t begin) {
if (str == NULL || str->str == NULL || str->len <= begin)
return false;
char* buff = (char*)malloc(str->len - begin);
if (buff == NULL)
return false;
memcpy(buff, str->str + begin, str->len - begin);
free(str->str);
str->str = buff;
str->len -= begin;
return true;
}
void pstring_finalize(pstring_t* str) {
if (str == NULL || str->str == NULL)
return;
str->str[str->len] = '\0';
}
void pstring_free(pstring_t* str) {
if (str != NULL && str->str != NULL) {
free(str->str);
pstring_init(str);
}
}