adler32.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * Adler-32 checksum
  3. *
  4. * Copyright (c) 2003 by Joergen Ibsen / Jibz
  5. * All Rights Reserved
  6. *
  7. * http://www.ibsensoftware.com/
  8. *
  9. * This software is provided 'as-is', without any express
  10. * or implied warranty. In no event will the authors be
  11. * held liable for any damages arising from the use of
  12. * this software.
  13. *
  14. * Permission is granted to anyone to use this software
  15. * for any purpose, including commercial applications,
  16. * and to alter it and redistribute it freely, subject to
  17. * the following restrictions:
  18. *
  19. * 1. The origin of this software must not be
  20. * misrepresented; you must not claim that you
  21. * wrote the original software. If you use this
  22. * software in a product, an acknowledgment in
  23. * the product documentation would be appreciated
  24. * but is not required.
  25. *
  26. * 2. Altered source versions must be plainly marked
  27. * as such, and must not be misrepresented as
  28. * being the original software.
  29. *
  30. * 3. This notice may not be removed or altered from
  31. * any source distribution.
  32. */
  33. /*
  34. * Adler-32 algorithm taken from the zlib source, which is
  35. * Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler
  36. */
  37. #include "tinf.h"
  38. #define A32_BASE 65521
  39. #define A32_NMAX 5552
  40. uint32_t uzlib_adler32(const void *data, unsigned int length, uint32_t prev_sum /* 1 */)
  41. {
  42. const unsigned char *buf = (const unsigned char *)data;
  43. unsigned int s1 = prev_sum & 0xffff;
  44. unsigned int s2 = prev_sum >> 16;
  45. while (length > 0)
  46. {
  47. int k = length < A32_NMAX ? length : A32_NMAX;
  48. int i;
  49. for (i = k / 16; i; --i, buf += 16)
  50. {
  51. s1 += buf[0]; s2 += s1; s1 += buf[1]; s2 += s1;
  52. s1 += buf[2]; s2 += s1; s1 += buf[3]; s2 += s1;
  53. s1 += buf[4]; s2 += s1; s1 += buf[5]; s2 += s1;
  54. s1 += buf[6]; s2 += s1; s1 += buf[7]; s2 += s1;
  55. s1 += buf[8]; s2 += s1; s1 += buf[9]; s2 += s1;
  56. s1 += buf[10]; s2 += s1; s1 += buf[11]; s2 += s1;
  57. s1 += buf[12]; s2 += s1; s1 += buf[13]; s2 += s1;
  58. s1 += buf[14]; s2 += s1; s1 += buf[15]; s2 += s1;
  59. }
  60. for (i = k % 16; i; --i) { s1 += *buf++; s2 += s1; }
  61. s1 %= A32_BASE;
  62. s2 %= A32_BASE;
  63. length -= k;
  64. }
  65. return (s2 << 16) | s1;
  66. }