-
Notifications
You must be signed in to change notification settings - Fork 1
/
buffer.cpp
85 lines (64 loc) · 1.64 KB
/
buffer.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
#include "buffer.h"
buffer buffer_init(void)
{
buffer buffer;
buffer.data = NULL;
buffer.size = 0;
return buffer;
}
void buffer_destroy(buffer *buffer)
{
if (buffer->data != NULL) {
free(buffer->data);
buffer->data = NULL;
}
buffer->size = 0;
}
int buffer_is_empty(buffer *buffer)
{
return buffer->data == NULL;
}
void buffer_add(buffer *buffer, const char *data, size_t data_size)
{
if (buffer->data != NULL) {
buffer->data = (char *)realloc(buffer->data, (buffer->size + data_size) * sizeof(char));
} else {
buffer->data = (char *)calloc(data_size, sizeof(char));
}
memcpy(buffer->data + buffer->size, data, data_size);
buffer->size += data_size;
}
int buffer_find(buffer *buffer, const char *data, size_t data_size)
{
if (data_size > buffer->size)
return -1;
size_t last_pos = buffer->size - data_size + 1;
for (size_t i = 0; i < last_pos; ++i) {
size_t j;
for (j = 0; j < data_size; ++j) {
if (buffer->data[i + j] != data[j]) {
break;
}
}
if (j == data_size)
return i;
}
return -1;
}
int buffer_find_insensitive(buffer *buffer, const char *data, size_t data_size)
{
if (data_size > buffer->size)
return -1;
size_t last_pos = buffer->size - data_size + 1;
for (size_t i = 0; i < last_pos; ++i) {
size_t j;
for (j = 0; j < data_size; ++j) {
if (tolower(buffer->data[i + j]) != tolower(data[j])) {
break;
}
}
if (j == data_size)
return i;
}
return -1;
}