librsync  2.0.1
rollsum.c
1 /*= -*- c-basic-offset: 4; indent-tabs-mode: nil; -*-
2  *
3  * rollsum -- the librsync rolling checksum
4  *
5  * Copyright (C) 2003 by Donovan Baarda <abo@minkirri.apana.org.au>
6  * based on work, Copyright (C) 2000, 2001 by Martin Pool <mbp@sourcefrog.net>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU Lesser General Public License as published by
10  * the Free Software Foundation; either version 2.1 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  */
22 #include "rollsum.h"
23 
24 #define DO1(buf,i) {s1 += buf[i]; s2 += s1;}
25 #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
26 #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
27 #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
28 #define DO16(buf) DO8(buf,0); DO8(buf,8);
29 
30 void RollsumUpdate(Rollsum *sum, const unsigned char *buf, size_t len)
31 {
32  /* ANSI C says no overflow for unsigned. zlib's adler32 goes to extra
33  effort to avoid overflow for its mod prime, which we don't have. */
34  size_t n = len;
35  uint_fast16_t s1 = sum->s1;
36  uint_fast16_t s2 = sum->s2;
37 
38  while (n >= 16) {
39  DO16(buf);
40  buf += 16;
41  n -= 16;
42  }
43  while (n != 0) {
44  s1 += *buf++;
45  s2 += s1;
46  n--;
47  }
48  /* Increment s1 and s2 by the amounts added by the char offset. */
49  s1 += len * ROLLSUM_CHAR_OFFSET;
50  s2 += ((len * (len + 1)) / 2) * ROLLSUM_CHAR_OFFSET;
51  sum->count += len; /* Increment sum count. */
52  sum->s1 = s1;
53  sum->s2 = s2;
54 }