index.html 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. <!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="generator" content="rustdoc"><meta name="description" content="API documentation for the Rust `rngs` mod in crate `rand`."><meta name="keywords" content="rust, rustlang, rust-lang, rngs"><title>rand::rngs - Rust</title><link rel="stylesheet" type="text/css" href="../../normalize.css"><link rel="stylesheet" type="text/css" href="../../rustdoc.css" id="mainThemeStyle"><link rel="stylesheet" type="text/css" href="../../dark.css"><link rel="stylesheet" type="text/css" href="../../light.css" id="themeStyle"><script src="../../storage.js"></script><link rel="shortcut icon" href="https://www.rust-lang.org/favicon.ico"></head><body class="rustdoc mod"><!--[if lte IE 8]><div class="warning">This old browser is unsupported and will most likely display funky things.</div><![endif]--><nav class="sidebar"><div class="sidebar-menu">&#9776;</div><a href='../../rand/index.html'><img src='https://www.rust-lang.org/logos/rust-logo-128x128-blk.png' alt='logo' width='100'></a><p class='location'>Module rngs</p><div class="sidebar-elems"><div class="block items"><ul><li><a href="#modules">Modules</a></li><li><a href="#structs">Structs</a></li><li><a href="#enums">Enums</a></li></ul></div><p class='location'><a href='../index.html'>rand</a></p><script>window.sidebarCurrent = {name: 'rngs', ty: 'mod', relpath: '../'};</script><script defer src="../sidebar-items.js"></script></div></nav><div class="theme-picker"><button id="theme-picker" aria-label="Pick another theme!"><img src="../../brush.svg" width="18" alt="Pick another theme!"></button><div id="theme-choices"></div></div><script src="../../theme.js"></script><nav class="sub"><form class="search-form js-only"><div class="search-container"><input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"><a id="settings-menu" href="../../settings.html"><img src="../../wheel.svg" width="18" alt="Change settings"></a></div></form></nav><section id="main" class="content"><h1 class='fqn'><span class='in-band'>Module <a href='../index.html'>rand</a>::<wbr><a class="mod" href=''>rngs</a></span><span class='out-of-band'><span id='render-detail'><a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">[<span class='inner'>&#x2212;</span>]</a></span><a class='srclink' href='../../src/rand/rngs/mod.rs.html#11-218' title='goto source code'>[src]</a></span></h1><div class='docblock'><p>Random number generators and adapters for common usage:</p>
  2. <ul>
  3. <li><a href="struct.ThreadRng.html"><code>ThreadRng</code></a>, a fast, secure, auto-seeded thread-local generator</li>
  4. <li><a href="struct.StdRng.html"><code>StdRng</code></a> and <a href="struct.SmallRng.html"><code>SmallRng</code></a>, algorithms to cover typical usage</li>
  5. <li><a href="struct.EntropyRng.html"><code>EntropyRng</code></a>, <a href="struct.OsRng.html"><code>OsRng</code></a> and <a href="struct.JitterRng.html"><code>JitterRng</code></a> as entropy sources</li>
  6. <li><a href="mock/struct.StepRng.html"><code>mock::StepRng</code></a> as a simple counter for tests</li>
  7. <li><a href="adapter/struct.ReadRng.html"><code>adapter::ReadRng</code></a> to read from a file/stream</li>
  8. </ul>
  9. <h1 id="background--random-number-generators-rngs" class="section-header"><a href="#background--random-number-generators-rngs">Background — Random number generators (RNGs)</a></h1>
  10. <p>Computers are inherently deterministic, so to get <em>random</em> numbers one
  11. either has to use a hardware generator or collect bits of <em>entropy</em> from
  12. various sources (e.g. event timestamps, or jitter). This is a relatively
  13. slow and complicated operation.</p>
  14. <p>Generally the operating system will collect some entropy, remove bias, and
  15. use that to seed its own PRNG; <a href="struct.OsRng.html"><code>OsRng</code></a> provides an interface to this.
  16. <a href="struct.JitterRng.html"><code>JitterRng</code></a> is an entropy collector included with Rand that measures
  17. jitter in the CPU execution time, and jitter in memory access time.
  18. <a href="struct.EntropyRng.html"><code>EntropyRng</code></a> is a wrapper that uses the best entropy source that is
  19. available.</p>
  20. <h2 id="pseudo-random-number-generators" class="section-header"><a href="#pseudo-random-number-generators">Pseudo-random number generators</a></h2>
  21. <p>What is commonly used instead of &quot;true&quot; random number renerators, are
  22. <em>pseudo-random number generators</em> (PRNGs), deterministic algorithms that
  23. produce an infinite stream of pseudo-random numbers from a small random
  24. seed. PRNGs are faster, and have better provable properties. The numbers
  25. produced can be statistically of very high quality and can be impossible to
  26. predict. (They can also have obvious correlations and be trivial to predict;
  27. quality varies.)</p>
  28. <p>There are two different types of PRNGs: those developed for simulations
  29. and statistics, and those developed for use in cryptography; the latter are
  30. called Cryptographically Secure PRNGs (CSPRNG or CPRNG). Both types can
  31. have good statistical quality but the latter also have to be impossible to
  32. predict, even after seeing many previous output values. Rand provides a good
  33. default algorithm from each class:</p>
  34. <ul>
  35. <li><a href="struct.SmallRng.html"><code>SmallRng</code></a> is a PRNG chosen for low memory usage, high performance and
  36. good statistical quality.
  37. The current algorithm (plain Xorshift) unfortunately performs
  38. poorly in statistical quality test suites (TestU01 and PractRand) and will
  39. be replaced in the next major release.</li>
  40. <li><a href="struct.StdRng.html"><code>StdRng</code></a> is a CSPRNG chosen for good performance and trust of security
  41. (based on reviews, maturity and usage). The current algorithm is HC-128,
  42. which is one of the recommendations by ECRYPT's eSTREAM project.</li>
  43. </ul>
  44. <p>The above PRNGs do not cover all use-cases; more algorithms can be found in
  45. the <a href="../prng/index.html"><code>prng</code> module</a>, as well as in several other crates. For example, you
  46. may wish a CSPRNG with significantly lower memory usage than <a href="struct.StdRng.html"><code>StdRng</code></a>
  47. while being less concerned about performance, in which case <a href="../prng/chacha/struct.ChaChaRng.html"><code>ChaChaRng</code></a>
  48. is a good choice.</p>
  49. <p>One complexity is that the internal state of a PRNG must change with every
  50. generated number. For APIs this generally means a mutable reference to the
  51. state of the PRNG has to be passed around.</p>
  52. <p>A solution is <a href="struct.ThreadRng.html"><code>ThreadRng</code></a>. This is a thread-local implementation of
  53. <a href="struct.StdRng.html"><code>StdRng</code></a> with automatic seeding on first use. It is the best choice if you
  54. &quot;just&quot; want a convenient, secure, fast random number source. Use via the
  55. <a href="../fn.thread_rng.html"><code>thread_rng</code></a> function, which gets a reference to the current thread's
  56. local instance.</p>
  57. <h2 id="seeding" class="section-header"><a href="#seeding">Seeding</a></h2>
  58. <p>As mentioned above, PRNGs require a random seed in order to produce random
  59. output. This is especially important for CSPRNGs, which are still
  60. deterministic algorithms, thus can only be secure if their seed value is
  61. also secure. To seed a PRNG, use one of:</p>
  62. <ul>
  63. <li><a href="../trait.FromEntropy.html#tymethod.from_entropy"><code>FromEntropy::from_entropy</code></a>; this is the most convenient way to seed
  64. with fresh, secure random data.</li>
  65. <li><a href="../trait.SeedableRng.html#tymethod.from_rng"><code>SeedableRng::from_rng</code></a>; this allows seeding from another PRNG or
  66. from an entropy source such as <a href="struct.EntropyRng.html"><code>EntropyRng</code></a>.</li>
  67. <li><a href="../trait.SeedableRng.html#tymethod.from_seed"><code>SeedableRng::from_seed</code></a>; this is mostly useful if you wish to be able
  68. to reproduce the output sequence by using a fixed seed. (Don't use
  69. <a href="struct.StdRng.html"><code>StdRng</code></a> or <a href="struct.SmallRng.html"><code>SmallRng</code></a> in this case since different algorithms may be
  70. used by future versions of Rand; use an algorithm from the
  71. <a href="../prng/index.html"><code>prng</code> module</a>.)</li>
  72. </ul>
  73. <h2 id="conclusion" class="section-header"><a href="#conclusion">Conclusion</a></h2>
  74. <ul>
  75. <li><a href="../fn.thread_rng.html"><code>thread_rng</code></a> is what you often want to use.</li>
  76. <li>If you want more control, flexibility, or better performance, use
  77. <a href="struct.StdRng.html"><code>StdRng</code></a>, <a href="struct.SmallRng.html"><code>SmallRng</code></a> or an algorithm from the <a href="../prng/index.html"><code>prng</code> module</a>.</li>
  78. <li>Use <a href="../trait.FromEntropy.html#tymethod.from_entropy"><code>FromEntropy::from_entropy</code></a> to seed new PRNGs.</li>
  79. <li>If you need reproducibility, use <a href="../trait.SeedableRng.html#tymethod.from_seed"><code>SeedableRng::from_seed</code></a> combined with
  80. a named PRNG.</li>
  81. </ul>
  82. <p>More information and notes on cryptographic security can be found
  83. in the <a href="../prng/index.html"><code>prng</code> module</a>.</p>
  84. <h2 id="examples" class="section-header"><a href="#examples">Examples</a></h2>
  85. <p>Examples of seeding PRNGs:</p>
  86. <pre class="rust rust-example-rendered">
  87. <span class="kw">use</span> <span class="ident">rand</span>::<span class="ident">prelude</span>::<span class="kw-2">*</span>;
  88. <span class="comment">// StdRng seeded securely by the OS or local entropy collector:</span>
  89. <span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">rng</span> <span class="op">=</span> <span class="ident">StdRng</span>::<span class="ident">from_entropy</span>();
  90. <span class="comment">// SmallRng seeded from thread_rng:</span>
  91. <span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">rng</span> <span class="op">=</span> <span class="ident">SmallRng</span>::<span class="ident">from_rng</span>(<span class="ident">thread_rng</span>())<span class="question-mark">?</span>;
  92. <span class="comment">// SmallRng seeded by a constant, for deterministic results:</span>
  93. <span class="kw">let</span> <span class="ident">seed</span> <span class="op">=</span> [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>, <span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>, <span class="number">9</span>,<span class="number">10</span>,<span class="number">11</span>,<span class="number">12</span>, <span class="number">13</span>,<span class="number">14</span>,<span class="number">15</span>,<span class="number">16</span>]; <span class="comment">// byte array</span>
  94. <span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">rng</span> <span class="op">=</span> <span class="ident">SmallRng</span>::<span class="ident">from_seed</span>(<span class="ident">seed</span>);</pre>
  95. <h1 id="implementing-custom-rngs" class="section-header"><a href="#implementing-custom-rngs">Implementing custom RNGs</a></h1>
  96. <p>If you want to implement custom RNG, see the <a href="https://crates.io/crates/rand_core"><code>rand_core</code></a> crate. The RNG
  97. will have to implement the <a href="../trait.RngCore.html"><code>RngCore</code></a> trait, where the <a href="../trait.Rng.html"><code>Rng</code></a> trait is
  98. build on top of.</p>
  99. <p>If the RNG needs seeding, also implement the <a href="../trait.SeedableRng.html"><code>SeedableRng</code></a> trait.</p>
  100. <p><a href="../trait.CryptoRng.html"><code>CryptoRng</code></a> is a marker trait cryptographically secure PRNGs can
  101. implement.</p>
  102. </div><h2 id='modules' class='section-header'><a href="#modules">Modules</a></h2>
  103. <table>
  104. <tr class=' module-item'>
  105. <td><a class="mod" href="adapter/index.html"
  106. title='mod rand::rngs::adapter'>adapter</a></td>
  107. <td class='docblock-short'>
  108. <p>Wrappers / adapters forming RNGs</p>
  109. </td>
  110. </tr>
  111. <tr class=' module-item'>
  112. <td><a class="mod" href="mock/index.html"
  113. title='mod rand::rngs::mock'>mock</a></td>
  114. <td class='docblock-short'>
  115. <p>Mock random number generator</p>
  116. </td>
  117. </tr></table><h2 id='structs' class='section-header'><a href="#structs">Structs</a></h2>
  118. <table>
  119. <tr class=' module-item'>
  120. <td><a class="struct" href="struct.EntropyRng.html"
  121. title='struct rand::rngs::EntropyRng'>EntropyRng</a></td>
  122. <td class='docblock-short'>
  123. <p>An interface returning random data from external source(s), provided
  124. specifically for securely seeding algorithmic generators (PRNGs).</p>
  125. </td>
  126. </tr>
  127. <tr class=' module-item'>
  128. <td><a class="struct" href="struct.JitterRng.html"
  129. title='struct rand::rngs::JitterRng'>JitterRng</a></td>
  130. <td class='docblock-short'>
  131. <p>A true random number generator based on jitter in the CPU execution time,
  132. and jitter in memory access time.</p>
  133. </td>
  134. </tr>
  135. <tr class=' module-item'>
  136. <td><a class="struct" href="struct.OsRng.html"
  137. title='struct rand::rngs::OsRng'>OsRng</a></td>
  138. <td class='docblock-short'>
  139. <p>A random number generator that retrieves randomness straight from the
  140. operating system.</p>
  141. </td>
  142. </tr>
  143. <tr class=' module-item'>
  144. <td><a class="struct" href="struct.SmallRng.html"
  145. title='struct rand::rngs::SmallRng'>SmallRng</a></td>
  146. <td class='docblock-short'>
  147. <p>An RNG recommended when small state, cheap initialization and good
  148. performance are required. The PRNG algorithm in <code>SmallRng</code> is chosen to be
  149. efficient on the current platform, <strong>without consideration for cryptography
  150. or security</strong>. The size of its state is much smaller than for <a href="struct.StdRng.html"><code>StdRng</code></a>.</p>
  151. </td>
  152. </tr>
  153. <tr class=' module-item'>
  154. <td><a class="struct" href="struct.StdRng.html"
  155. title='struct rand::rngs::StdRng'>StdRng</a></td>
  156. <td class='docblock-short'>
  157. <p>The standard RNG. The PRNG algorithm in <code>StdRng</code> is chosen to be efficient
  158. on the current platform, to be statistically strong and unpredictable
  159. (meaning a cryptographically secure PRNG).</p>
  160. </td>
  161. </tr>
  162. <tr class=' module-item'>
  163. <td><a class="struct" href="struct.ThreadRng.html"
  164. title='struct rand::rngs::ThreadRng'>ThreadRng</a></td>
  165. <td class='docblock-short'>
  166. <p>The type returned by <a href="../fn.thread_rng.html"><code>thread_rng</code></a>, essentially just a reference to the
  167. PRNG in thread-local memory.</p>
  168. </td>
  169. </tr></table><h2 id='enums' class='section-header'><a href="#enums">Enums</a></h2>
  170. <table>
  171. <tr class=' module-item'>
  172. <td><a class="enum" href="enum.TimerError.html"
  173. title='enum rand::rngs::TimerError'>TimerError</a></td>
  174. <td class='docblock-short'>
  175. <p>An error that can occur when <a href="struct.JitterRng.html#method.test_timer"><code>JitterRng::test_timer</code></a> fails.</p>
  176. </td>
  177. </tr></table></section><section id="search" class="content hidden"></section><section class="footer"></section><aside id="help" class="hidden"><div><h1 class="hidden">Help</h1><div class="shortcuts"><h2>Keyboard Shortcuts</h2><dl><dt><kbd>?</kbd></dt><dd>Show this help dialog</dd><dt><kbd>S</kbd></dt><dd>Focus the search field</dd><dt><kbd>↑</kbd></dt><dd>Move up in search results</dd><dt><kbd>↓</kbd></dt><dd>Move down in search results</dd><dt><kbd>↹</kbd></dt><dd>Switch tab</dd><dt><kbd>&#9166;</kbd></dt><dd>Go to active search result</dd><dt><kbd>+</kbd></dt><dd>Expand all sections</dd><dt><kbd>-</kbd></dt><dd>Collapse all sections</dd></dl></div><div class="infos"><h2>Search Tricks</h2><p>Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type.</p><p>Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>.</p><p>Search functions by type signature (e.g. <code>vec -> usize</code> or <code>* -> vec</code>)</p><p>Search multiple things at once by splitting your query with comma (e.g. <code>str,u8</code> or <code>String,struct:Vec,test</code>)</p></div></div></aside><script>window.rootPath = "../../";window.currentCrate = "rand";</script><script src="../../aliases.js"></script><script src="../../main.js"></script><script defer src="../../search-index.js"></script></body></html>