Back to index

tetex-bin  3.0
adler32.c
Go to the documentation of this file.
00001 /* adler32.c -- compute the Adler-32 checksum of a data stream
00002  * Copyright (C) 1995-2003 Mark Adler
00003  * For conditions of distribution and use, see copyright notice in zlib.h
00004  */
00005 
00006 /* @(#) $Id$ */
00007 
00008 #define ZLIB_INTERNAL
00009 #include "zlib.h"
00010 
00011 #define BASE 65521UL    /* largest prime smaller than 65536 */
00012 #define NMAX 5552
00013 /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
00014 
00015 #define DO1(buf,i)  {s1 += buf[i]; s2 += s1;}
00016 #define DO2(buf,i)  DO1(buf,i); DO1(buf,i+1);
00017 #define DO4(buf,i)  DO2(buf,i); DO2(buf,i+2);
00018 #define DO8(buf,i)  DO4(buf,i); DO4(buf,i+4);
00019 #define DO16(buf)   DO8(buf,0); DO8(buf,8);
00020 
00021 #ifdef NO_DIVIDE
00022 #  define MOD(a) \
00023     do { \
00024         if (a >= (BASE << 16)) a -= (BASE << 16); \
00025         if (a >= (BASE << 15)) a -= (BASE << 15); \
00026         if (a >= (BASE << 14)) a -= (BASE << 14); \
00027         if (a >= (BASE << 13)) a -= (BASE << 13); \
00028         if (a >= (BASE << 12)) a -= (BASE << 12); \
00029         if (a >= (BASE << 11)) a -= (BASE << 11); \
00030         if (a >= (BASE << 10)) a -= (BASE << 10); \
00031         if (a >= (BASE << 9)) a -= (BASE << 9); \
00032         if (a >= (BASE << 8)) a -= (BASE << 8); \
00033         if (a >= (BASE << 7)) a -= (BASE << 7); \
00034         if (a >= (BASE << 6)) a -= (BASE << 6); \
00035         if (a >= (BASE << 5)) a -= (BASE << 5); \
00036         if (a >= (BASE << 4)) a -= (BASE << 4); \
00037         if (a >= (BASE << 3)) a -= (BASE << 3); \
00038         if (a >= (BASE << 2)) a -= (BASE << 2); \
00039         if (a >= (BASE << 1)) a -= (BASE << 1); \
00040         if (a >= BASE) a -= BASE; \
00041     } while (0)
00042 #else
00043 #  define MOD(a) a %= BASE
00044 #endif
00045 
00046 /* ========================================================================= */
00047 uLong ZEXPORT adler32(adler, buf, len)
00048     uLong adler;
00049     const Bytef *buf;
00050     uInt len;
00051 {
00052     unsigned long s1 = adler & 0xffff;
00053     unsigned long s2 = (adler >> 16) & 0xffff;
00054     int k;
00055 
00056     if (buf == Z_NULL) return 1L;
00057 
00058     while (len > 0) {
00059         k = len < NMAX ? (int)len : NMAX;
00060         len -= k;
00061         while (k >= 16) {
00062             DO16(buf);
00063             buf += 16;
00064             k -= 16;
00065         }
00066         if (k != 0) do {
00067             s1 += *buf++;
00068             s2 += s1;
00069         } while (--k);
00070         MOD(s1);
00071         MOD(s2);
00072     }
00073     return (s2 << 16) | s1;
00074 }