1 // Copyright 2023 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 
15 #pragma once
16 #include "pw_bluetooth_sapphire/internal/host/common/assert.h"
17 #include "pw_random/random.h"
18 
19 namespace bt {
20 
21 // Returns the global random number generator. This returns nullptr until it is
22 // configured by initialization code.
23 pw::random::RandomGenerator* random_generator();
24 
25 // Sets the global random number generator used by the host stack. To prevent
26 // overriding, the current generator must be nullptr or an assert will fail.
27 void set_random_generator(pw::random::RandomGenerator* generator);
28 
29 template <typename T>
Random()30 T Random() {
31   static_assert(std::is_trivial_v<T> && !std::is_pointer_v<T>,
32                 "Type cannot be filled with random bytes");
33   PW_DCHECK(random_generator());
34   T t;
35   random_generator()->Get({reinterpret_cast<std::byte*>(&t), sizeof(T)});
36   return t;
37 }
38 
39 }  // namespace bt
40