randutil.c 843 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /*
  2. * randutil.c
  3. *
  4. * Copyright (c) 2001 Dug Song <dugsong@monkey.org>
  5. *
  6. * $Id: randutil.c 2000 2008-04-27 06:17:35Z aturner $
  7. */
  8. #include "config.h"
  9. #include <dnet.h>
  10. #include <err.h>
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #include <time.h>
  15. #include "randutil.h"
  16. static const char base64[] =
  17. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  18. void
  19. rand_strset(rand_t *r, void *buf, size_t len)
  20. {
  21. uint32_t u;
  22. char *p;
  23. int i;
  24. p = (char *)buf;
  25. i = (len + 3) / 4;
  26. u = rand_uint32(r);
  27. /* XXX - more Duff's device tomfoolery. */
  28. switch (len % 4) {
  29. case 0: do {
  30. u = rand_uint32(r);
  31. *p++ = base64[(u >> 18) & 0x3f];
  32. case 3:
  33. *p++ = base64[(u >> 12) & 0x3f];
  34. case 2:
  35. *p++ = base64[(u >> 6) & 0x3f];
  36. case 1:
  37. *p++ = base64[(u >> 0) & 0x3f];
  38. } while (--i > 0);
  39. }
  40. p[-1] = '\0';
  41. }