| 1 |
/* ********************************************************************* |
| 2 |
* Description: The following source code is borrowed heavily from the |
| 3 |
* zlib project The zlib source is subject to the following copyright |
| 4 |
* and license: |
| 5 |
* |
| 6 |
* Copyright (C) 1995-2010, 2021 Jean-loup Gailly and Mark Adler |
| 7 |
* |
| 8 |
* This software is provided 'as-is', without any express or implied |
| 9 |
* warranty. In no event will the authors be held liable for any damages |
| 10 |
* arising from the use of this software. |
| 11 |
* |
| 12 |
* Permission is granted to anyone to use this software for any purpose, |
| 13 |
* including commercial applications, and to alter it and redistribute it |
| 14 |
* freely, subject to the following restrictions: |
| 15 |
* |
| 16 |
* 1. The origin of this software must not be misrepresented; you must not |
| 17 |
* claim that you wrote the original software. If you use this software |
| 18 |
* in a product, an acknowledgment in the product documentation would be |
| 19 |
* appreciated but is not required. |
| 20 |
* 2. Altered source versions must be plainly marked as such, and must not be |
| 21 |
* misrepresented as being the original software. |
| 22 |
* 3. This notice may not be removed or altered from any source distribution. |
| 23 |
* |
| 24 |
* Jean-loup Gailly Mark Adler |
| 25 |
* [email protected] [email protected] |
| 26 |
*/ |
| 27 |
|
| 28 |
#include "adler.h" |
| 29 |
|
| 30 |
#define DO1(buf, i) \ |
| 31 |
{ \ |
| 32 |
s1 += (buf)[i]; \ |
| 33 |
s2 += s1; \ |
| 34 |
} |
| 35 |
#define DO2(buf, i) \ |
| 36 |
DO1(buf, i); \ |
| 37 |
DO1(buf, (i) + 1); |
| 38 |
#define DO4(buf, i) \ |
| 39 |
DO2(buf, i); \ |
| 40 |
DO2(buf, (i) + 2); |
| 41 |
#define DO8(buf, i) \ |
| 42 |
DO4(buf, i); \ |
| 43 |
DO4(buf, (i) + 4); |
| 44 |
#define DO16(buf) \ |
| 45 |
DO8(buf, 0); \ |
| 46 |
DO8(buf, 8); |
| 47 |
|
| 48 |
size_t adler(size_t adler, const void *vbuf, size_t len) |
| 49 |
{ |
| 50 |
const size_t BASE = 65521; /* largest prime smaller than 65536 */ |
| 51 |
const size_t NMAX = 5552; /* NMAX is the largest n such |
| 52 |
that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ |
| 53 |
|
| 54 |
const unsigned char *buf = (const unsigned char *)vbuf; |
| 55 |
|
| 56 |
size_t s1 = adler & 0xffff; |
| 57 |
size_t s2 = (adler >> 16) & 0xffff; |
| 58 |
|
| 59 |
if (buf == NULL || len == 0) { |
| 60 |
return 1L; |
| 61 |
} |
| 62 |
|
| 63 |
while (len > 0) { |
| 64 |
int k = len < NMAX ? len : NMAX; |
| 65 |
len -= k; |
| 66 |
while (k >= 16) { |
| 67 |
DO16(buf); |
| 68 |
buf += 16; |
| 69 |
k -= 16; |
| 70 |
} |
| 71 |
if (k != 0) { |
| 72 |
do { |
| 73 |
s1 += *buf++; |
| 74 |
s2 += s1; |
| 75 |
} while (--k); |
| 76 |
} |
| 77 |
s1 %= BASE; |
| 78 |
s2 %= BASE; |
| 79 |
} |
| 80 |
return (s2 << 16) | s1; |
| 81 |
} |