prng.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. #include <assert.h>
  26. #include <stdlib.h>
  27. #include "prng.h"
  28. struct prng
  29. {
  30. unsigned long long state1;
  31. unsigned long long state2;
  32. };
  33. static char
  34. prng_bit(struct prng *prng)
  35. {
  36. prng->state1 *= 2416;
  37. prng->state1 += 374441;
  38. prng->state1 %= 1771875;
  39. if (prng->state1 % 2)
  40. {
  41. prng->state2 *= 84589;
  42. prng->state2 += 45989;
  43. prng->state2 %= 217728;
  44. }
  45. return prng->state2 % 2;
  46. }
  47. struct prng*
  48. prng_new(unsigned long long seed)
  49. {
  50. struct prng *rv = calloc(sizeof(*rv), 1);
  51. assert(rv);
  52. rv->state1 = rv->state2 = seed;
  53. return rv;
  54. }
  55. unsigned int
  56. prng_rand(struct prng *prng)
  57. {
  58. unsigned int i, rv = 0;
  59. for (i = 0; i < 32; i++)
  60. {
  61. rv |= prng_bit(prng);
  62. rv <<= 1;
  63. }
  64. return rv;
  65. }
  66. void
  67. prng_free(struct prng *prng)
  68. {
  69. free(prng);
  70. }