forked from CESNET/ipfixcol
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.cpp
145 lines (120 loc) · 2.47 KB
/
util.cpp
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
extern "C" {
#include <stdlib.h>
#include <string.h>
#include <ipfixcol/verbose.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <assert.h>
}
#include "util.h"
growing_buffer::growing_buffer() : allocated(0), size(0), data(NULL)
{
}
growing_buffer::growing_buffer(const growing_buffer& other) throw(std::bad_alloc) : allocated(other.size), size(other.size), data(NULL)
{
if (size > 0) {
data = (char *) malloc(allocated);
if (data == NULL) {
throw (std::bad_alloc());
}
memcpy(data, other.data, size);
}
}
growing_buffer::~growing_buffer()
{
if (data) {
free(data);
}
}
char *growing_buffer::append(size_t size, const void *data) throw(std::bad_alloc)
{
char *cur;
cur = this->append_blank(size);
memcpy(cur, data, size);
return cur;
}
char *growing_buffer::append_blank(size_t size) throw(std::bad_alloc)
{
size_t cur;
cur = this->size;
if (size == 0) {
return &this->data[cur];
}
while (this->size + size > allocated) {
if (allocated == 0) {
allocated = (size > default_size) ? size : default_size;
this->data = NULL;
} else {
/* TODO: better allocation strategy */
if (allocated * 2 > this->size + size) {
allocated *= 2;
} else {
allocated += size;
}
}
this->data = (char *) realloc(this->data, this->allocated);
if (this->data == NULL) {
throw std::bad_alloc();
}
}
this->size += size;
return &this->data[cur];
}
void growing_buffer::empty()
{
size = 0;
}
void growing_buffer::allocate(size_t new_size) throw(std::bad_alloc) {
assert(new_size >= this->size);
if (allocated >= new_size) {
return;
}
allocated = new_size;
this->data = (char *) realloc(this->data, this->allocated);
if (this->data == NULL) {
throw std::bad_alloc();
}
}
char *growing_buffer::access(size_t offset)
{
return &data[offset];
}
size_t growing_buffer::get_size()
{
return size;
}
bool mkdir_parents(const char *pathname, mode_t mode)
{
char *path;
bool result = true;
size_t end, len;
path = strdup(pathname);
if (!path) {
return false;
}
len = strlen(pathname);
end = len;
while (1) {
if (mkdir(path, mode) == 0 || errno == EEXIST) {
// go to subdirectory
result = true;
if (end == len) {
break;
}
path[end] = '/';
end = strlen(path);
} else if (errno == ENOENT) {
// go to parent directory
while (path[end] != '/' && end > 0) end--;
if (end == 0) {
result = false;
}
path[end] = 0;
} else {
result = false;
}
}
free(path);
return result;
}