randutil.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * randutil.c
  3. *
  4. * Copyright (c) 2001 Dug Song <dugsong@monkey.org>
  5. *
  6. * $Id$
  7. */
  8. #include "config.h"
  9. #ifdef HAVE_LIBDNET
  10. /* need to undef these which are pulled in via defines.h, prior to importing dnet.h */
  11. #undef icmp_id
  12. #undef icmp_seq
  13. #undef icmp_data
  14. #undef icmp_mask
  15. #ifdef HAVE_DNET_H
  16. #include <dnet.h>
  17. #endif
  18. #ifdef HAVE_DUMBNET_H
  19. #include <dumbnet.h>
  20. #endif
  21. #endif
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include <string.h>
  25. #include <time.h>
  26. #include "randutil.h"
  27. static const char base64[] =
  28. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  29. void
  30. rand_strset(rand_t *r, void *buf, size_t len)
  31. {
  32. uint32_t u;
  33. char *p;
  34. int i;
  35. p = (char *)buf;
  36. i = (len + 3) / 4;
  37. u = rand_uint32(r);
  38. /* XXX - more Duff's device tomfoolery. */
  39. switch (len % 4) {
  40. case 0: do {
  41. u = rand_uint32(r);
  42. *p++ = base64[(u >> 18) & 0x3f];
  43. case 3:
  44. *p++ = base64[(u >> 12) & 0x3f];
  45. case 2:
  46. *p++ = base64[(u >> 6) & 0x3f];
  47. case 1:
  48. *p++ = base64[(u >> 0) & 0x3f];
  49. } while (--i > 0);
  50. }
  51. p[-1] = '\0';
  52. }