-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathio.c
144 lines (100 loc) · 2.62 KB
/
io.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
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
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/select.h>
#include "io.h"
#include "tle.h"
extern inline bool bmm_io_read_to_bool(enum bmm_io_read);
enum bmm_io_wait bmm_io_wait(int const fd, struct timeval *const timeout) {
fd_set fds;
FD_ZERO(&fds);
FD_SET(fd, &fds);
int const result = select(1, &fds, NULL, NULL, timeout);
switch (result) {
case -1:
return BMM_IO_WAIT_ERROR;
case 0:
return BMM_IO_WAIT_TIMEOUT;
default:
return BMM_IO_WAIT_READY;
}
}
size_t bmm_io_redir(FILE *const out, FILE *const in, size_t const size) {
size_t progress = 0;
unsigned char buf[BUFSIZ];
while (progress < size) {
size_t const ndiff = size - progress;
size_t const nmemb = ndiff < sizeof buf ? ndiff : sizeof buf;
size_t const nread = fread(buf, 1, nmemb, in);
if (nread == 0)
break;
size_t const nwritten = fwrite(buf, 1, nmemb, out);
if (nwritten < nread)
break;
progress += nread;
}
return progress;
}
size_t bmm_io_fastfw(FILE *const stream, size_t const size) {
size_t progress = 0;
unsigned char buf[BUFSIZ];
while (progress < size) {
size_t const ndiff = size - progress;
size_t const nmemb = ndiff < sizeof buf ? ndiff : sizeof buf;
size_t const nread = fread(buf, 1, nmemb, stream);
if (nread == 0)
break;
progress += nread;
}
return progress;
}
enum bmm_io_wait bmm_io_waitin(struct timeval *);
extern inline bool bmm_io_redirio(size_t);
extern inline enum bmm_io_read bmm_io_fastfwin(size_t);
extern inline enum bmm_io_read bmm_io_readin(void *, size_t);
extern inline bool bmm_io_writeout(void const *, size_t);
void *bmm_io_fconts(size_t *const ptr, FILE *const stream) {
if (fseek(stream, 0, SEEK_END) != 0) {
BMM_TLE_STDS();
return NULL;
}
long int const pos = ftell(stream);
if (fseek(stream, 0, SEEK_SET) != 0) {
BMM_TLE_STDS();
return NULL;
}
size_t const size = (size_t) pos;
void *const buf = malloc(size);
if (buf == NULL) {
BMM_TLE_STDS();
return NULL;
}
if (fread(buf, size, 1, stream) != 1) {
BMM_TLE_STDS();
free(buf);
return NULL;
}
*ptr = size;
return buf;
}
void *bmm_io_conts(size_t *const ptr, char const *const path) {
FILE *const stream = fopen(path, "r");
if (stream == NULL) {
BMM_TLE_STDS();
return NULL;
}
void *const buf = bmm_io_fconts(ptr, stream);
if (buf == NULL) {
BMM_TLE_STDS();
if (fclose(stream) != 0)
BMM_TLE_STDS();
return NULL;
}
if (fclose(stream) != 0) {
BMM_TLE_STDS();
free(buf);
return NULL;
}
return buf;
}