deflatezlib.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. #include <flate.h>
  12. #include "zlib.h"
  13. typedef struct ZRead ZRead;
  14. struct ZRead
  15. {
  16. uint32_t adler;
  17. void *rr;
  18. int (*r)(void*, void*, int);
  19. };
  20. static int
  21. zlread(void *vzr, void *buf, int n)
  22. {
  23. ZRead *zr;
  24. zr = vzr;
  25. n = (*zr->r)(zr->rr, buf, n);
  26. if(n <= 0)
  27. return n;
  28. zr->adler = adler32(zr->adler, buf, n);
  29. return n;
  30. }
  31. int
  32. deflatezlib(void *wr, int (*w)(void*, void*, int), void *rr, int (*r)(void*, void*, int), int level, int debug)
  33. {
  34. ZRead zr;
  35. uint8_t buf[4];
  36. int ok;
  37. buf[0] = ZlibDeflate | ZlibWin32k;
  38. /* bogus zlib encoding of compression level */
  39. buf[1] = ((level > 2) + (level > 5) + (level > 8)) << 6;
  40. /* header check field */
  41. buf[1] |= 31 - ((buf[0] << 8) | buf[1]) % 31;
  42. if((*w)(wr, buf, 2) != 2)
  43. return FlateOutputFail;
  44. zr.rr = rr;
  45. zr.r = r;
  46. zr.adler = 1;
  47. ok = deflate(wr, w, &zr, zlread, level, debug);
  48. if(ok != FlateOk)
  49. return ok;
  50. buf[0] = zr.adler >> 24;
  51. buf[1] = zr.adler >> 16;
  52. buf[2] = zr.adler >> 8;
  53. buf[3] = zr.adler;
  54. if((*w)(wr, buf, 4) != 4)
  55. return FlateOutputFail;
  56. return FlateOk;
  57. }