RoundTrip.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * Copyright (c) 2016-present, 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. */
  9. #pragma once
  10. #include "Options.h"
  11. #include "Pzstd.h"
  12. #include "utils/ScopeGuard.h"
  13. #include <cstdio>
  14. #include <string>
  15. #include <cstdint>
  16. #include <memory>
  17. namespace pzstd {
  18. inline bool check(std::string source, std::string decompressed) {
  19. std::unique_ptr<std::uint8_t[]> sBuf(new std::uint8_t[1024]);
  20. std::unique_ptr<std::uint8_t[]> dBuf(new std::uint8_t[1024]);
  21. auto sFd = std::fopen(source.c_str(), "rb");
  22. auto dFd = std::fopen(decompressed.c_str(), "rb");
  23. auto guard = makeScopeGuard([&] {
  24. std::fclose(sFd);
  25. std::fclose(dFd);
  26. });
  27. size_t sRead, dRead;
  28. do {
  29. sRead = std::fread(sBuf.get(), 1, 1024, sFd);
  30. dRead = std::fread(dBuf.get(), 1, 1024, dFd);
  31. if (std::ferror(sFd) || std::ferror(dFd)) {
  32. return false;
  33. }
  34. if (sRead != dRead) {
  35. return false;
  36. }
  37. for (size_t i = 0; i < sRead; ++i) {
  38. if (sBuf.get()[i] != dBuf.get()[i]) {
  39. return false;
  40. }
  41. }
  42. } while (sRead == 1024);
  43. if (!std::feof(sFd) || !std::feof(dFd)) {
  44. return false;
  45. }
  46. return true;
  47. }
  48. inline bool roundTrip(Options& options) {
  49. if (options.inputFiles.size() != 1) {
  50. return false;
  51. }
  52. std::string source = options.inputFiles.front();
  53. std::string compressedFile = std::tmpnam(nullptr);
  54. std::string decompressedFile = std::tmpnam(nullptr);
  55. auto guard = makeScopeGuard([&] {
  56. std::remove(compressedFile.c_str());
  57. std::remove(decompressedFile.c_str());
  58. });
  59. {
  60. options.outputFile = compressedFile;
  61. options.decompress = false;
  62. if (pzstdMain(options) != 0) {
  63. return false;
  64. }
  65. }
  66. {
  67. options.decompress = true;
  68. options.inputFiles.front() = compressedFile;
  69. options.outputFile = decompressedFile;
  70. if (pzstdMain(options) != 0) {
  71. return false;
  72. }
  73. }
  74. return check(source, decompressedFile);
  75. }
  76. }