rippled
rngfill.h
1 //------------------------------------------------------------------------------
2 /*
3  This file is part of Beast: https://github.com/vinniefalco/Beast
4  Copyright 2014, Vinnie Falco <vinnie.falco@gmail.com>
5 
6  Permission to use, copy, modify, and/or distribute this software for any
7  purpose with or without fee is hereby granted, provided that the above
8  copyright notice and this permission notice appear in all copies.
9 
10  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18 //==============================================================================
19 
20 #ifndef BEAST_RANDOM_RNGFILL_H_INCLUDED
21 #define BEAST_RANDOM_RNGFILL_H_INCLUDED
22 
23 #include <array>
24 #include <cstdint>
25 #include <cstring>
26 #include <type_traits>
27 
28 namespace beast {
29 
30 template <class Generator>
31 void
32 rngfill(void* buffer, std::size_t bytes, Generator& g)
33 {
34  using result_type = typename Generator::result_type;
35  while (bytes >= sizeof(result_type))
36  {
37  auto const v = g();
38  std::memcpy(buffer, &v, sizeof(v));
39  buffer = reinterpret_cast<std::uint8_t*>(buffer) + sizeof(v);
40  bytes -= sizeof(v);
41  }
42  if (bytes > 0)
43  {
44  auto const v = g();
45  std::memcpy(buffer, &v, bytes);
46  }
47 }
48 
49 template <
50  class Generator,
51  std::size_t N,
52  class = std::enable_if_t<N % sizeof(typename Generator::result_type) == 0>>
53 void
55 {
56  using result_type = typename Generator::result_type;
57  auto i = N / sizeof(result_type);
58  result_type* p = reinterpret_cast<result_type*>(a.data());
59  while (i--)
60  *p++ = g();
61 }
62 
63 } // namespace beast
64 
65 #endif
cstring
std::enable_if_t
array
cstdint
std::uint8_t
beast::rngfill
void rngfill(void *buffer, std::size_t bytes, Generator &g)
Definition: rngfill.h:32
std::size_t
std::memcpy
T memcpy(T... args)
std::array::data
T data(T... args)
type_traits
beast
Definition: base_uint.h:585