adler.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. enum
  13. {
  14. ADLERITERS = 5552, /* max iters before can overflow 32 bits */
  15. ADLERBASE = 65521 /* largest prime smaller than 65536 */
  16. };
  17. uint32_t
  18. adler32(uint32_t adler, void *vbuf, int n)
  19. {
  20. uint32_t s1, s2;
  21. uint8_t *buf, *ebuf;
  22. int m;
  23. buf = vbuf;
  24. s1 = adler & 0xffff;
  25. s2 = (adler >> 16) & 0xffff;
  26. for(; n >= 16; n -= m){
  27. m = n;
  28. if(m > ADLERITERS)
  29. m = ADLERITERS;
  30. m &= ~15;
  31. for(ebuf = buf + m; buf < ebuf; buf += 16){
  32. s1 += buf[0];
  33. s2 += s1;
  34. s1 += buf[1];
  35. s2 += s1;
  36. s1 += buf[2];
  37. s2 += s1;
  38. s1 += buf[3];
  39. s2 += s1;
  40. s1 += buf[4];
  41. s2 += s1;
  42. s1 += buf[5];
  43. s2 += s1;
  44. s1 += buf[6];
  45. s2 += s1;
  46. s1 += buf[7];
  47. s2 += s1;
  48. s1 += buf[8];
  49. s2 += s1;
  50. s1 += buf[9];
  51. s2 += s1;
  52. s1 += buf[10];
  53. s2 += s1;
  54. s1 += buf[11];
  55. s2 += s1;
  56. s1 += buf[12];
  57. s2 += s1;
  58. s1 += buf[13];
  59. s2 += s1;
  60. s1 += buf[14];
  61. s2 += s1;
  62. s1 += buf[15];
  63. s2 += s1;
  64. }
  65. s1 %= ADLERBASE;
  66. s2 %= ADLERBASE;
  67. }
  68. if(n){
  69. for(ebuf = buf + n; buf < ebuf; buf++){
  70. s1 += buf[0];
  71. s2 += s1;
  72. }
  73. s1 %= ADLERBASE;
  74. s2 %= ADLERBASE;
  75. }
  76. return (s2 << 16) + s1;
  77. }