684e5de242f4f954e2153830a31699e073f9d5a1
[debian/amanda] / common-src / simpleprng.c
1 /*
2  * Copyright (c) 2005-2008 Zmanda Inc.  All Rights Reserved.
3  *
4  * This program is free software; you can redistribute it and/or modify it
5  * under the terms of the GNU General Public License version 2 as published
6  * by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
10  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
11  * for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16  *
17  * Contact information: Zmanda Inc, 465 S Mathlida Ave, Suite 300
18  * Sunnyvale, CA 94086, USA, or: http://www.zmanda.com
19  */
20
21 #include "simpleprng.h"
22
23 /* A *very* basic linear congruential generator; values are as cited in
24  * http://en.wikipedia.org/wiki/Linear_congruential_generator for Numerical Recipes */
25
26 #define A 1664525
27 #define C 1013904223
28
29 void
30 simpleprng_seed(
31     simpleprng_state_t *state,
32     guint32 seed)
33 {
34     g_assert(seed != 0);
35     *state = seed;
36 }
37
38 guint32 simpleprng_rand(
39     simpleprng_state_t *state)
40 {
41     return (*state = (A * (*state)) + C);
42 }
43
44 void simpleprng_fill_buffer(
45     simpleprng_state_t *state,
46     gpointer buf,
47     size_t len)
48 {
49     guint8 *p = buf;
50     while (len--) {
51         *(p++) = simpleprng_rand_byte(state);
52     }
53 }
54
55 gboolean simpleprng_verify_buffer(
56     simpleprng_state_t *state,
57     gpointer buf,
58     size_t len)
59 {
60     guint8 *p = buf;
61     while (len--) {
62         guint8 expected = simpleprng_rand_byte(state);
63         guint8 got = *p;
64         if (expected != got) {
65             g_fprintf(stderr,
66                     "random value mismatch in buffer %p, offset %zd: got 0x%02x, expected 0x%02x\n", 
67                     buf, (size_t)(p-(guint8*)buf), (int)got, (int)expected);
68             return FALSE;
69         }
70         p++;
71     }
72
73     return TRUE;
74 }