forked from basak/ddar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrabin.c
86 lines (71 loc) · 1.94 KB
/
rabin.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
Copyright 2010-2011 True Blue Logic Ltd
This program is free software: you can redistribute it and/or modify
it under the terms of version 3 of the GNU General Public License as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "rabin.h"
struct rabin_ctx {
uint32_t *a_exp;
int k;
};
struct rabin_ctx *rabin_init(uint32_t a, int k) {
int i;
uint32_t *a_exp;
uint32_t acc;
struct rabin_ctx *ctx;
ctx = (struct rabin_ctx *)malloc(sizeof(struct rabin_ctx));
if (!ctx)
return 0;
a_exp = (uint32_t *)malloc(sizeof(uint32_t) * k);
if (!a_exp) {
free(ctx);
return 0;
}
acc = 1;
a_exp[0] = 1;
for (i=1; i<k; i++) {
acc *= a;
a_exp[i] = acc;
}
ctx->k = k;
ctx->a_exp = a_exp;
return ctx;
}
void rabin_free(struct rabin_ctx *ctx) {
free(ctx->a_exp);
free(ctx);
}
uint32_t rabin_hash(const struct rabin_ctx *ctx, const unsigned char *p) {
int i;
uint32_t acc=0;
for (i=ctx->k-1; i>=0; i--, p++) {
acc += ctx->a_exp[i] * *p;
}
return acc;
}
uint32_t rabin_hash_split(const struct rabin_ctx *ctx, const unsigned char *p,
int size, const unsigned char *p2) {
int i;
uint32_t acc=0;
for (i=ctx->k-1; i>=0; i--, p++) {
acc += ctx->a_exp[i] * *p;
if (!--size)
p = p2;
}
return acc;
}
uint32_t rabin_hash_next(const struct rabin_ctx *ctx, uint32_t hash, unsigned
char old, unsigned char new) {
hash -= ctx->a_exp[ctx->k-1] * old;
hash *= ctx->a_exp[1];
hash += new;
return hash;
}
/* vim: set ts=8 sts=4 sw=4 cindent : */