deflatezlib.c 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <flate.h>
  4. #include "zlib.h"
  5. typedef struct ZRead ZRead;
  6. struct ZRead
  7. {
  8. ulong adler;
  9. void *rr;
  10. int (*r)(void*, void*, int);
  11. };
  12. static int
  13. zlread(void *vzr, void *buf, int n)
  14. {
  15. ZRead *zr;
  16. zr = vzr;
  17. n = (*zr->r)(zr->rr, buf, n);
  18. if(n <= 0)
  19. return n;
  20. zr->adler = adler32(zr->adler, buf, n);
  21. return n;
  22. }
  23. int
  24. deflatezlib(void *wr, int (*w)(void*, void*, int), void *rr, int (*r)(void*, void*, int), int level, int debug)
  25. {
  26. ZRead zr;
  27. uchar buf[4];
  28. int ok;
  29. buf[0] = ZlibDeflate | ZlibWin32k;
  30. /* bogus zlib encoding of compression level */
  31. buf[1] = ((level > 2) + (level > 5) + (level > 8)) << 6;
  32. /* header check field */
  33. buf[1] |= 31 - ((buf[0] << 8) | buf[1]) % 31;
  34. if((*w)(wr, buf, 2) != 2)
  35. return FlateOutputFail;
  36. zr.rr = rr;
  37. zr.r = r;
  38. zr.adler = 1;
  39. ok = deflate(wr, w, &zr, zlread, level, debug);
  40. if(ok != FlateOk)
  41. return ok;
  42. buf[0] = zr.adler >> 24;
  43. buf[1] = zr.adler >> 16;
  44. buf[2] = zr.adler >> 8;
  45. buf[3] = zr.adler;
  46. if((*w)(wr, buf, 4) != 4)
  47. return FlateOutputFail;
  48. return FlateOk;
  49. }