-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathread4_multi.c
88 lines (62 loc) · 1.42 KB
/
read4_multi.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
#include "lib/helpers.h"
/**
* The read4 API is defined in the parent class Reader4.
* int read4(char *buf4);
*/
int read4(char *buf4);
#define READ4_FULL_LEN 4
typedef struct {
char tmp[READ4_FULL_LEN + 1];
int index;
int len;
} Solution;
/** initialize your data structure here. */
Solution* solutionCreate() {
return calloc(1, sizeof(Solution));
}
int CopyFromTmp(Solution* obj, char* buf, int *len)
{
int i = 0;
int cn = Min(obj->len, *len);
for (i = 0; i < cn; ++i)
{
buf[i] = obj->tmp[obj->index];
++obj->index;
}
obj->len -= cn;
*len -= cn;
return cn;
}
/**
* @param buf Destination buffer
* @param n Number of characters to read
* @return The number of actual characters read
*/
int _read(Solution* obj, char* buf, int len) {
int org_len = len, cn = 0;
if (len <= 0)
return 0;
while (len > 0)
{
if (obj->len > 0)
{
cn = CopyFromTmp(obj, buf, &len);
if (len == 0)
break;
buf += cn;
}
if (len < READ4_FULL_LEN)
{
obj->len = read4(obj->tmp);
obj->index = 0;
CopyFromTmp(obj, buf, &len);
break;
}
cn = read4(buf);
buf += cn;
len -= cn;
if (cn < READ4_FULL_LEN)
break;
}
return org_len - len;
}