read_dist.h 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /* Copyright 2016 Google Inc. All Rights Reserved.
  2. Author: zip753@gmail.com (Ivan Nikulin)
  3. Distributed under MIT license.
  4. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
  5. */
  6. /* API for reading distances from *.dist file.
  7. The format of *.dist file is as follows: for each backward reference there is
  8. a position-distance pair, also a copy length may be specified. Copy length is
  9. prefixed with flag byte 0, position-distance pair is prefixed with flag
  10. byte 1. Each number is a 32-bit integer. Copy length always comes before
  11. position-distance pair. Standalone copy length is allowed, in this case it is
  12. ignored. */
  13. #ifndef BROTLI_RESEARCH_READ_DIST_H_
  14. #define BROTLI_RESEARCH_READ_DIST_H_
  15. #include <cstdio>
  16. #include <cstdlib> /* exit, EXIT_FAILURE */
  17. #if !defined(CHECK)
  18. #define CHECK(X) if (!(X)) exit(EXIT_FAILURE);
  19. #endif
  20. /* Reads backwards reference from .dist file. Sets all missing fields to -1.
  21. Returns false when EOF is met or input is corrupt. */
  22. bool ReadBackwardReference(FILE* fin, int* copy, int* pos, int* dist) {
  23. int c = getc(fin);
  24. if (c == EOF) return false;
  25. if (c == 0) {
  26. CHECK(fread(copy, sizeof(int), 1, fin) == 1);
  27. if ((c = getc(fin)) != 1) {
  28. ungetc(c, fin);
  29. *pos = *dist = -1;
  30. } else {
  31. CHECK(fread(pos, sizeof(int), 1, fin) == 1);
  32. CHECK(fread(dist, sizeof(int), 1, fin) == 1);
  33. }
  34. } else if (c != 1) {
  35. return false;
  36. } else {
  37. CHECK(fread(pos, sizeof(int), 1, fin) == 1);
  38. CHECK(fread(dist, sizeof(int), 1, fin) == 1);
  39. *copy = -1;
  40. }
  41. return true;
  42. }
  43. #endif /* BROTLI_RESEARCH_READ_DIST_H_ */