-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformat.cpp
More file actions
81 lines (70 loc) · 1.76 KB
/
Copy pathformat.cpp
File metadata and controls
81 lines (70 loc) · 1.76 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
#include <cassert>
#include <string>
#include <unistd.h>
#include <cstring>
#include <iostream>
const int len_size = 4;
const int MAX_BUF = 64*1048;
static int read_all(int fd,char* buf,int n){
while(n>0){
int rv = read(fd,buf,n);
if(rv<=0){
return -1;
}
assert(rv<=n);
buf += rv;
n-=rv;
}
return 0;
}
static int write_all(int fd,char* buf,int n){
while(n>0){
ssize_t rv = write(fd,buf,n);
if(rv<=0){
return -1;
}
assert(rv<=n);
buf += rv;
n -= rv;
}
return 0;
}
static int parse_len(int fd){
char len_buf[len_size] = {};
int ans = 0;
int n = read_all(fd,len_buf,4);
if(n){
perror("Can't read length\n");
exit(1);
}
for(int i = 0;i<len_size;i++){
char c = len_buf[i];
ans += (c << (i*8));
}
return ans;
}
static void write_len(int x,char* w){
for(int i = 0;i<len_size;i++){
char c = ((x<<((3-i)*8))>>((3-i)*8));
w[i] = c;
x>>=(8);
}
}
int write_to(int fd,std::string msg){
char wbuf[4+MAX_BUF] = {};
write_len(msg.size(),wbuf);
memcpy(wbuf+4,msg.data(),msg.size());
return write_all(fd, wbuf,4+msg.size());
}
int read_from(int fd,char* rbuf){
int len = parse_len(fd);
if(len<0){
return -1;
}
assert(len<MAX_BUF);
int n = read_all(fd, rbuf,len);
if(n<0){
return -1;
}
return 0;
}