1 /*
2 This is a C version of the cmd/snappytool Go program.
3 
4 To build the snappytool binary:
5 g++ main.cpp /usr/lib/libsnappy.a -o snappytool
6 or, if you have built the C++ snappy library from source:
7 g++ main.cpp /path/to/your/snappy/.libs/libsnappy.a -o snappytool
8 after running "make" from your snappy checkout directory.
9 */
10 
11 #include <errno.h>
12 #include <stdio.h>
13 #include <string.h>
14 #include <unistd.h>
15 
16 #include "snappy.h"
17 
18 #define N 1000000
19 
20 char dst[N];
21 char src[N];
22 
main(int argc,char ** argv)23 int main(int argc, char** argv) {
24   // Parse args.
25   if (argc != 2) {
26     fprintf(stderr, "exactly one of -d or -e must be given\n");
27     return 1;
28   }
29   bool decode = strcmp(argv[1], "-d") == 0;
30   bool encode = strcmp(argv[1], "-e") == 0;
31   if (decode == encode) {
32     fprintf(stderr, "exactly one of -d or -e must be given\n");
33     return 1;
34   }
35 
36   // Read all of stdin into src[:s].
37   size_t s = 0;
38   while (1) {
39     if (s == N) {
40       fprintf(stderr, "input too large\n");
41       return 1;
42     }
43     ssize_t n = read(0, src+s, N-s);
44     if (n == 0) {
45       break;
46     }
47     if (n < 0) {
48       fprintf(stderr, "read error: %s\n", strerror(errno));
49       // TODO: handle EAGAIN, EINTR?
50       return 1;
51     }
52     s += n;
53   }
54 
55   // Encode or decode src[:s] to dst[:d], and write to stdout.
56   size_t d = 0;
57   if (encode) {
58     if (N < snappy::MaxCompressedLength(s)) {
59       fprintf(stderr, "input too large after encoding\n");
60       return 1;
61     }
62     snappy::RawCompress(src, s, dst, &d);
63   } else {
64     if (!snappy::GetUncompressedLength(src, s, &d)) {
65       fprintf(stderr, "could not get uncompressed length\n");
66       return 1;
67     }
68     if (N < d) {
69       fprintf(stderr, "input too large after decoding\n");
70       return 1;
71     }
72     if (!snappy::RawUncompress(src, s, dst)) {
73       fprintf(stderr, "input was not valid Snappy-compressed data\n");
74       return 1;
75     }
76   }
77   write(1, dst, d);
78   return 0;
79 }
80