forked from msgpack/msgpack-c
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crosslang.cc
133 lines (111 loc) · 2.41 KB
/
crosslang.cc
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
//
// MessagePack cross-language test tool
//
// $ cd ../cpp && ./configure && make && make install
// or
// $ port install msgpack # MacPorts
//
// $ g++ -Wall crosslang.cc -lmsgpack
//
#include <msgpack.hpp>
#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
static int run(int infd, int outfd)
try {
msgpack::unpacker pac;
while(true) {
pac.reserve_buffer(32*1024);
ssize_t count =
read(infd, pac.buffer(), pac.buffer_capacity());
if(count <= 0) {
if(count == 0) {
return 0;
}
if(errno == EAGAIN || errno == EINTR) {
continue;
}
return 1;
}
pac.buffer_consumed(count);
msgpack::unpacked result;
while(pac.next(&result)) {
msgpack::sbuffer sbuf;
msgpack::pack(sbuf, result.get());
const char* p = sbuf.data();
const char* const pend = p + sbuf.size();
while(p < pend) {
ssize_t bytes = write(outfd, p, pend-p);
if(bytes <= 0) {
if(count == 0) {
return 0;
}
if(errno == EAGAIN || errno == EINTR) {
continue;
}
return 1;
}
p += bytes;
}
}
}
return 0;
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
return 1;
}
static void usage(const char* prog)
{
printf(
"Usage: %s [in-file] [out-file]\n"
"\n"
"This tool is for testing of MessagePack implementation.\n"
"This does following behavior:\n"
"\n"
" 1. Reads objects serialized by MessagePack from <in-file> (default: stdin)\n"
" 2. Re-serializes the objects using C++ implementation of MessagePack (Note that C++ implementation is considered valid)\n"
" 3. Writes the re-serialized objects into <out-file> (default: stdout)\n"
"\n"
, prog);
exit(1);
}
int main(int argc, char* argv[])
{
int infd = 0;
int outfd = 1;
if(argc < 1 || argc > 3) {
usage(argv[0]);
}
for(int i=1; i < argc; ++i) {
if(strlen(argv[i]) > 1 && argv[i][0] == '-') {
usage(argv[0]);
}
}
if(argc >= 2) {
const char* fname = argv[1];
if(strcmp(fname, "-") != 0) {
infd = open(fname, O_RDONLY);
if(infd < 0) {
perror("can't open input file");
exit(1);
}
}
}
if(argc >= 3) {
const char* fname = argv[2];
if(strcmp(fname, "-") != 0) {
outfd = open(fname, O_WRONLY | O_CREAT| O_TRUNC, 0666);
if(outfd < 0) {
perror("can't open output file");
exit(1);
}
}
}
int code = run(infd, outfd);
close(infd);
close(outfd);
return code;
}