github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/golang/snappy/cmd/snappytool/main.cpp (about)

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