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 <cassert>
25 #include <cstdint>
26 #include <cstring>
27 #include <type_traits>
28 
29 namespace beast {
30 
31 template <class Generator>
32 void
33 rngfill(void* buffer, std::size_t bytes, Generator& g)
34 {
35  using result_type = typename Generator::result_type;
36 
37  while (bytes >= sizeof(result_type))
38  {
39  auto const v = g();
40  std::memcpy(buffer, &v, sizeof(v));
41  buffer = reinterpret_cast<std::uint8_t*>(buffer) + sizeof(v);
42  bytes -= sizeof(v);
43  }
44 
45  assert(bytes < sizeof(result_type));
46 
47 #ifdef __GNUC__
48  // gcc 11.1 (falsely) warns about an array-bounds overflow in release mode.
49 #pragma GCC diagnostic push
50 #pragma GCC diagnostic ignored "-Warray-bounds"
51 #endif
52 
53  if (bytes > 0)
54  {
55  auto const v = g();
56  std::memcpy(buffer, &v, bytes);
57  }
58 
59 #ifdef __GNUC__
60 #pragma GCC diagnostic pop
61 #endif
62 }
63 
64 template <
65  class Generator,
66  std::size_t N,
67  class = std::enable_if_t<N % sizeof(typename Generator::result_type) == 0>>
68 void
70 {
71  using result_type = typename Generator::result_type;
72  auto i = N / sizeof(result_type);
73  result_type* p = reinterpret_cast<result_type*>(a.data());
74  while (i--)
75  *p++ = g();
76 }
77 
78 } // namespace beast
79 
80 #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:33
cassert
std::size_t
std::memcpy
T memcpy(T... args)
std::array::data
T data(T... args)
type_traits
beast
Definition: base_uint.h:641