You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
1.8 KiB

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