-
Notifications
You must be signed in to change notification settings - Fork 1
/
iostream.c
95 lines (84 loc) · 2 KB
/
iostream.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
#include <unistd.h>
#include <stdio.h>
#include <error.h>
#include <errno.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include "iostream.h"
#include "util.h"
int create_stream(IOstream* stream, int bufsize)
{
stream->capacity = bufsize;
stream->bytes = 0;
stream->ptr = (char*)malloc(stream->capacity);
if (!stream->ptr) {
return E_ERROR;
}
stream->cur = stream->ptr;
return E_OK;
}
int close_stream(IOstream* stream)
{
if (stream->ptr) {
free(stream->ptr);
}
stream->ptr = stream->cur = NULL;
stream->capacity = stream->bytes = 0;
return E_OK;
}
int try_read_more(IOstream* s)
{
if (s->cur != s->ptr) {
if (s->bytes != 0) {
memmove(s->ptr, s->cur, s->bytes);
}
s->cur = s->ptr;
}
if (s->bytes >= s->capacity) {
char* new_ptr = (char*)realloc(s->ptr, s->capacity * 2);
if (!new_ptr) {
error(EXIT_FAILURE, errno, "not enough memory, realloc buf");
}
s->cur = s->ptr = new_ptr;
s->capacity *= 2;
}
int avail = s->capacity - s->bytes;
int nread = read(s->fd, s->cur + s->bytes, avail);
if (nread > 0) {
s->bytes += nread;
}
if (nread == 0) return E_ERROR;
if (nread < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
return E_OK;
}
log("read error, %s\n", strerror(errno));
return E_ERROR;
}
return E_OK;
}
int get_line(IOstream* s, char** line, int* len)
{
char* bp = (char*)memchr(s->cur, '\n', s->bytes);
if (bp == NULL) {
return E_NEED_MORE;
}
*line = s->cur;
*len = ++bp - s->cur;
s->cur = bp;
s->bytes -= *len;
return E_OK;
}
int get_all_lines(IOstream* s, char** line, int* len)
{
char* bp = (char*)memrchr((void*)(s->cur), '\n', s->bytes);
if (bp == NULL) {
return E_NEED_MORE;
}
*line = s->cur;
*len = ++bp - s->cur;
s->cur = bp;
s->bytes -= *len;
return E_OK;
}