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* const buffer, std::size_t const bytes, Generator& g)
35{
36 using result_type = typename Generator::result_type;
37 constexpr std::size_t result_size = sizeof(result_type);
38
39 std::uint8_t* const buffer_start = static_cast<std::uint8_t*>(buffer);
40 std::size_t const complete_iterations = bytes / result_size;
41 std::size_t const bytes_remaining = bytes % result_size;
42
43 for (std::size_t count = 0; count < complete_iterations; ++count)
44 {
45 result_type const v = g();
46 std::size_t const offset = count * result_size;
47 std::memcpy(buffer_start + offset, &v, result_size);
48 }
49
50 if (bytes_remaining > 0)
51 {
52 result_type const v = g();
53 std::size_t const offset = complete_iterations * result_size;
54 std::memcpy(buffer_start + offset, &v, bytes_remaining);
55 }
56}
57
58template <
59 class Generator,
61 class = std::enable_if_t<N % sizeof(typename Generator::result_type) == 0>>
62void
64{
65 using result_type = typename Generator::result_type;
66 auto i = N / sizeof(result_type);
67 result_type* p = reinterpret_cast<result_type*>(a.data());
68 while (i--)
69 *p++ = g();
70}
71
72} // namespace beast
73
74#endif
T data(T... args)
T memcpy(T... args)
void rngfill(void *const buffer, std::size_t const bytes, Generator &g)
Definition rngfill.h:34