2
0

simple_decompression.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright (c) Yann Collet, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. * You may select, at your option, one of the above-listed licenses.
  9. */
  10. #include <stdio.h> // printf
  11. #include <stdlib.h> // free
  12. #include <zstd.h> // presumes zstd library is installed
  13. #include "common.h" // Helper functions, CHECK(), and CHECK_ZSTD()
  14. static void decompress(const char* fname)
  15. {
  16. size_t cSize;
  17. void* const cBuff = mallocAndLoadFile_orDie(fname, &cSize);
  18. /* Read the content size from the frame header. For simplicity we require
  19. * that it is always present. By default, zstd will write the content size
  20. * in the header when it is known. If you can't guarantee that the frame
  21. * content size is always written into the header, either use streaming
  22. * decompression, or ZSTD_decompressBound().
  23. */
  24. unsigned long long const rSize = ZSTD_getFrameContentSize(cBuff, cSize);
  25. CHECK(rSize != ZSTD_CONTENTSIZE_ERROR, "%s: not compressed by zstd!", fname);
  26. CHECK(rSize != ZSTD_CONTENTSIZE_UNKNOWN, "%s: original size unknown!", fname);
  27. void* const rBuff = malloc_orDie((size_t)rSize);
  28. /* Decompress.
  29. * If you are doing many decompressions, you may want to reuse the context
  30. * and use ZSTD_decompressDCtx(). If you want to set advanced parameters,
  31. * use ZSTD_DCtx_setParameter().
  32. */
  33. size_t const dSize = ZSTD_decompress(rBuff, rSize, cBuff, cSize);
  34. CHECK_ZSTD(dSize);
  35. /* When zstd knows the content size, it will error if it doesn't match. */
  36. CHECK(dSize == rSize, "Impossible because zstd will check this condition!");
  37. /* success */
  38. printf("%25s : %6u -> %7u \n", fname, (unsigned)cSize, (unsigned)rSize);
  39. free(rBuff);
  40. free(cBuff);
  41. }
  42. int main(int argc, const char** argv)
  43. {
  44. const char* const exeName = argv[0];
  45. if (argc!=2) {
  46. printf("wrong arguments\n");
  47. printf("usage:\n");
  48. printf("%s FILE\n", exeName);
  49. return 1;
  50. }
  51. decompress(argv[1]);
  52. printf("%s correctly decoded (in memory). \n", argv[1]);
  53. return 0;
  54. }