Christian Franke | fa713d9 | 2013-07-05 15:35:37 +0000 | [diff] [blame] | 1 | /* |
| 2 | * Very simple prng to allow for randomized tests with reproducable |
| 3 | * results. |
| 4 | * |
| 5 | * Copyright (C) 2012 by Open Source Routing. |
| 6 | * Copyright (C) 2012 by Internet Systems Consortium, Inc. ("ISC") |
| 7 | * |
| 8 | * This file is part of Quagga |
| 9 | * |
| 10 | * Quagga is free software; you can redistribute it and/or modify it |
| 11 | * under the terms of the GNU General Public License as published by the |
| 12 | * Free Software Foundation; either version 2, or (at your option) any |
| 13 | * later version. |
| 14 | * |
| 15 | * Quagga is distributed in the hope that it will be useful, but |
| 16 | * WITHOUT ANY WARRANTY; without even the implied warranty of |
| 17 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 18 | * General Public License for more details. |
| 19 | * |
| 20 | * You should have received a copy of the GNU General Public License |
| 21 | * along with Quagga; see the file COPYING. If not, write to the Free |
| 22 | * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA |
| 23 | * 02111-1307, USA. |
| 24 | */ |
| 25 | |
| 26 | #include <assert.h> |
| 27 | #include <stdlib.h> |
| 28 | |
| 29 | #include "prng.h" |
| 30 | |
| 31 | struct prng |
| 32 | { |
| 33 | unsigned long long state1; |
| 34 | unsigned long long state2; |
| 35 | }; |
| 36 | |
| 37 | static char |
| 38 | prng_bit(struct prng *prng) |
| 39 | { |
| 40 | prng->state1 *= 2416; |
| 41 | prng->state1 += 374441; |
| 42 | prng->state1 %= 1771875; |
| 43 | |
| 44 | if (prng->state1 % 2) |
| 45 | { |
| 46 | prng->state2 *= 84589; |
| 47 | prng->state2 += 45989; |
| 48 | prng->state2 %= 217728; |
| 49 | } |
| 50 | |
| 51 | return prng->state2 % 2; |
| 52 | } |
| 53 | |
| 54 | struct prng* |
| 55 | prng_new(unsigned long long seed) |
| 56 | { |
| 57 | struct prng *rv = calloc(sizeof(*rv), 1); |
| 58 | assert(rv); |
| 59 | |
| 60 | rv->state1 = rv->state2 = seed; |
| 61 | |
| 62 | return rv; |
| 63 | } |
| 64 | |
| 65 | unsigned int |
| 66 | prng_rand(struct prng *prng) |
| 67 | { |
| 68 | unsigned int i, rv = 0; |
| 69 | |
| 70 | for (i = 0; i < 32; i++) |
| 71 | { |
| 72 | rv |= prng_bit(prng); |
| 73 | rv <<= 1; |
| 74 | } |
| 75 | return rv; |
| 76 | } |
| 77 | |
| 78 | void |
| 79 | prng_free(struct prng *prng) |
| 80 | { |
| 81 | free(prng); |
| 82 | } |