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