main.cpp 1.8 KB

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