3 * Copyright (C) 1999 David Mazieres (dm@uun.org)
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License as
7 * published by the Free Software Foundation; either version 2, or (at
8 * your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
22 /* Faster generic_fls */
23 /* (c) 2002, D.Phillips and Sistina Software */
25 #include "rabinpoly.h"
26 #define MSB64 0x8000000000000000ULL
28 static inline unsigned fls8(unsigned n)
31 n & 0xc0? (n >> 7) + 7: (n >> 5) + 5:
32 n & 0x0c? (n >> 3) + 3: n - ((n + 1) >> 2);
35 static inline unsigned fls16(unsigned n)
37 return n & 0xff00? fls8(n >> 8) + 8: fls8(n);
40 static inline unsigned fls32(unsigned n)
42 return n & 0xffff0000? fls16(n >> 16) + 16: fls16(n);
45 static inline unsigned fls64(unsigned long long n) /* should be u64 */
47 return n & 0xffffffff00000000ULL? fls32(n >> 32) + 32: fls32(n);
51 static u_int64_t polymod (u_int64_t nh, u_int64_t nl, u_int64_t d);
52 static void polymult (u_int64_t *php, u_int64_t *plp,
53 u_int64_t x, u_int64_t y);
54 static u_int64_t polymmult (u_int64_t x, u_int64_t y, u_int64_t d);
56 static u_int64_t poly = 0xb15e234bd3792f63ull; // Actual polynomial
57 static u_int64_t T[256]; // Lookup table for mod
60 u_int64_t append8 (u_int64_t p, u_char m)
61 { return ((p << 8) | m) ^ T[p >> shift];
65 polymod (u_int64_t nh, u_int64_t nl, u_int64_t d)
74 for (i = 62; i >= 0; i--)
80 for (i = 63; i >= k; i--)
87 polymult (u_int64_t *php, u_int64_t *plp, u_int64_t x, u_int64_t y)
89 u_int64_t ph = 0, pl = 0;
92 for (i = 1; i < 64; i++)
93 if (x & (1ULL << i)) {
104 polymmult (u_int64_t x, u_int64_t y, u_int64_t d)
107 polymult (&h, &l, x, y);
108 return polymod (h, l, d);
111 static int size = RABIN_WINDOW_SIZE;
112 static u_int64_t fingerprint = 0;
113 static int bufpos = -1;
114 static u_int64_t U[256];
115 static u_char buf[RABIN_WINDOW_SIZE];
118 { u_int64_t sizeshift = 1;
122 assert (poly >= 0x100);
123 xshift = fls64 (poly) - 1;
125 T1 = polymod (0, 1ULL << xshift, poly);
126 for (j = 0; j < 256; j++)
127 T[j] = polymmult (j, T1, poly) | ((u_int64_t) j << xshift);
129 for (i = 1; i < size; i++)
130 sizeshift = append8 (sizeshift, 0);
131 for (i = 0; i < 256; i++)
132 U[i] = polymmult (i, sizeshift, poly);
133 bzero (buf, sizeof (buf));
140 bzero (buf, sizeof (buf));
144 rabin_slide8 (u_char m)
146 if (++bufpos >= size) bufpos = 0;
150 fingerprint = append8 (fingerprint ^ U[om], m);