main.cpp 1.6 KB

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