-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinput.c
More file actions
104 lines (81 loc) · 2.28 KB
/
input.c
File metadata and controls
104 lines (81 loc) · 2.28 KB
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
#include <memory.h>
#include <assert.h>
#include <stdbool.h>
#include <malloc.h>
#include <zconf.h>
#include "input.h"
result_t readUntilChars(int fd, string_t *pString, const char *chars) {
size_t charsLength = strlen(chars);
assert(charsLength > 0);
result_t ret;
// Basic state machine
bool *matchedChar = malloc(charsLength * sizeof(bool));
if (matchedChar == NULL) return OOM_ERROR;
for (size_t i = 0; i < charsLength; i++) matchedChar[i] = false;
*pString = createString();
if (*pString == NULL) {
ret = OOM_ERROR;
goto freeMatched;
}
while (true) {
char c;
ssize_t readRet = read(fd, &c, 1);
if (readRet == 0) {
ret = EOF_ERROR;
goto freeString;
}
if (readRet < 0) {
ret = IO_ERROR;
goto freeString;
}
if (matchedChar[charsLength - 2] && chars[charsLength - 1] == c) {
removeLastChars(*pString, charsLength - 1);
ret = OK;
goto freeMatched;
}
if (append(*pString, c) < 0) {
ret = OOM_ERROR;
goto freeString;
}
for (size_t i = charsLength - 1; i > 0; i--) {
matchedChar[i] = (matchedChar[i - 1] && c == chars[i]);
}
matchedChar[0] = c == chars[0];
}
freeString:
destroyString(*pString);
freeMatched:
free(matchedChar);
return ret;
}
result_t readUntil(int fd, string_t *pString, char c) {
*pString = createString();
size_t i = 0;
while (true) {
// Out of memory error.
if (*pString == NULL) return OOM_ERROR;
//Read next character.
char next;
ssize_t bytesRead = read(fd, &next, 1);
// Check if EOF
if (bytesRead == 0) {
destroyString(*pString);
return EOF_ERROR;
}
// Error reading file.
if (bytesRead < 0) {
destroyString(*pString);
return IO_ERROR;
}
// Stop reading if next character is the one looked for
if (next == c) {
return OK;
}
// Append the character
if (append(*pString, next) < 0) {
destroyString(*pString);
return OOM_ERROR;
}
i++;
}
}