1 //Written in the D programming language
2 /*
3  * Wrapper for std.random.rndGen and some useful routines.
4  *
5  * Copyright (C) 2013 Jaypha
6  *
7  * Distributed under the Boost Software License, Version 1.0.
8  * (See http://www.boost.org/LICENSE_1_0.txt)
9  *
10  * Authors: Jason den Dulk
11  */
12 
13 module jaypha.rnd;
14 
15 import std.array;
16 import std.ascii;
17 import std.random;
18 
19 //-----------------------------------------------------------------------------
20 // A wrapper for rndGen to prevent copying, provided by monarch_dodra.
21 
22 struct Rnd
23 {
24   enum empty = false;
25   void popFront()
26   {
27     rndGen.popFront();
28   }
29   @property auto front()
30   {
31     return rndGen.front;
32   }
33 }
34 
35 @property Rnd rnd() { return Rnd(); }
36 
37 //-----------------------------------------------------------------------------
38 // A randomly generated string of hex characters. Useful for filenames.
39 
40 string rndHex(size_t size)
41 {
42   return rndString(size, hexDigits);
43 }
44 
45 //-----------------------------------------------------------------------------
46 // A random string of ASCII printable characters. Useful for passwords.
47 
48 string rndString(size_t size)
49 {
50   auto bytes = appender!string();
51   bytes.reserve(size);
52   foreach (j; 0..size)
53     bytes.put(cast(char) uniform(33, 126));
54   return bytes.data;
55 }
56 
57 //-----------------------------------------------------------------------------
58 // A random string of characters selected from the given set.
59 
60 string rndString(size_t size, const char[] allowableChars)
61 {
62   auto bytes = appender!string();
63   bytes.reserve(size);
64   foreach (j; 0..size)
65     bytes.put(allowableChars[uniform(0,allowableChars.length)]);
66   return bytes.data;
67 }
68 
69 //-----------------------------------------------------------------------------
70 // A random string of lower case ASCII letters.
71 
72 string rndId(size_t size)
73 {
74   return rndString(size,lowercase);
75 }
76 
77 unittest
78 {
79   import jaypha.string;
80 
81   string set = "ushjvko28&";
82   string rs = rndString(100,set);
83   foreach (x;rs)
84     assert(altIndexOf(set,x) != set.length);
85 
86   rs = rndHex(100);
87   foreach (x;rs)
88     assert(altIndexOf(hexDigits,x) != hexDigits.length);
89 
90   rs = rndId(100);
91   foreach (x;rs)
92     assert(altIndexOf(lowercase,x) != lowercase.length);
93 }