zran.h 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /* zran.h -- example of deflated stream indexing and random access
  2. * Copyright (C) 2005, 2012, 2018, 2023 Mark Adler
  3. * For conditions of distribution and use, see copyright notice in zlib.h
  4. * Version 1.3 18 Feb 2023 Mark Adler */
  5. #include <stdio.h>
  6. #include "zlib.h"
  7. // Access point.
  8. typedef struct point {
  9. off_t out; // offset in uncompressed data
  10. off_t in; // offset in compressed file of first full byte
  11. int bits; // 0, or number of bits (1-7) from byte at in-1
  12. unsigned char window[32768]; // preceding 32K of uncompressed data
  13. } point_t;
  14. // Access point list.
  15. struct deflate_index {
  16. int have; // number of access points in list
  17. int mode; // -15 for raw, 15 for zlib, or 31 for gzip
  18. off_t length; // total length of uncompressed data
  19. point_t *list; // allocated list of access points
  20. };
  21. // Make one pass through a zlib, gzip, or raw deflate compressed stream and
  22. // build an index, with access points about every span bytes of uncompressed
  23. // output. gzip files with multiple members are fully indexed. span should be
  24. // chosen to balance the speed of random access against the memory requirements
  25. // of the list, which is about 32K bytes per access point. The return value is
  26. // the number of access points on success (>= 1), Z_MEM_ERROR for out of
  27. // memory, Z_BUF_ERROR for a premature end of input, Z_DATA_ERROR for a format
  28. // or verification error in the input file, or Z_ERRNO for a file read error.
  29. // On success, *built points to the resulting index.
  30. int deflate_index_build(FILE *in, off_t span, struct deflate_index **built);
  31. // Use the index to read len bytes from offset into buf. Return the number of
  32. // bytes read or a negative error code. If data is requested past the end of
  33. // the uncompressed data, then deflate_index_extract() will return a value less
  34. // than len, indicating how much was actually read into buf. If given a valid
  35. // index, this function should not return an error unless the file was modified
  36. // somehow since the index was generated, given that deflate_index_build() had
  37. // validated all of the input. If nevertheless there is a failure, Z_BUF_ERROR
  38. // is returned if the compressed data ends prematurely, Z_DATA_ERROR if the
  39. // deflate compressed data is not valid, Z_MEM_ERROR if out of memory,
  40. // Z_STREAM_ERROR if the index is not valid, or Z_ERRNO if there is an error
  41. // reading or seeking on the input file.
  42. ptrdiff_t deflate_index_extract(FILE *in, struct deflate_index *index,
  43. off_t offset, unsigned char *buf, size_t len);
  44. // Deallocate an index built by deflate_index_build().
  45. void deflate_index_free(struct deflate_index *index);