-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstream_match.c
101 lines (84 loc) · 2.48 KB
/
stream_match.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
#include "stream_match.h"
Matcher *matcher_init(const char *match_target)
{
Matcher *matcher = (Matcher *)malloc(sizeof(Matcher));
if (matcher == NULL)
{
perror("malloc failed");
exit(EXIT_FAILURE);
}
matcher->target_length = strlen(match_target);
matcher->match_target = (char *)malloc((matcher->target_length + 1) * sizeof(char));
if (matcher->match_target == NULL)
{
perror("malloc failed");
free(matcher);
exit(EXIT_FAILURE);
}
strcpy(matcher->match_target, match_target);
matcher->buffer = NULL;
return matcher;
}
void matcher_resize_buffer(Matcher *matcher, size_t n)
{
size_t old_len = strlen(matcher->buffer);
if (old_len <= n)
{
// 不需要缩小
return;
}
char *new_buffer = (char *)malloc((n + 1) * sizeof(char));
if (new_buffer == NULL)
{
perror("malloc failed");
exit(EXIT_FAILURE);
}
// 将原始数据的后n个字节复制到新缓冲区
memcpy(new_buffer, matcher->buffer + (old_len - n), n);
new_buffer[n] = '\0'; // 添加字符串结尾的空字符
// 释放原始缓冲区,并更新matcher->buffer指向新缓冲区
free(matcher->buffer);
matcher->buffer = new_buffer;
}
MatchResult matcher_receive(Matcher *matcher, const char *new_content)
{
if (matcher->buffer == NULL)
{
matcher->buffer = (char *)malloc((strlen(new_content) + 1) * sizeof(char));
if (matcher->buffer == NULL)
{
perror("malloc failed");
exit(EXIT_FAILURE);
}
strcpy(matcher->buffer, new_content);
}
else
{
size_t old_len = strlen(matcher->buffer);
size_t new_len = strlen(new_content);
matcher->buffer = realloc(matcher->buffer, old_len + new_len + 1);
if (matcher->buffer == NULL)
{
perror("realloc failed");
exit(EXIT_FAILURE);
}
strcat(matcher->buffer, new_content);
}
if (strstr(matcher->buffer, matcher->match_target) != NULL)
{
return MATCH;
}
else
{
// not match. we shrink the buffer to the size of target.
matcher_resize_buffer(matcher, matcher->target_length - 1);
return NOT_MATCH;
}
}
void matcher_destroy(Matcher *matcher)
{
// 这里不释放match_target,因为match target谁知道是哪来的!反正不归我管。
// free(matcher->match_target);
free(matcher->buffer);
free(matcher);
}