blob: b660ece500175ff84b016d55770ecbc90f19d67f [file] [log] [blame]
Austin Schuh36244a12019-09-21 17:52:38 -07001// Copyright 2017 The Abseil Authors.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of 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,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifndef ABSL_RANDOM_INTERNAL_EXPLICIT_SEED_SEQ_H_
16#define ABSL_RANDOM_INTERNAL_EXPLICIT_SEED_SEQ_H_
17
18#include <algorithm>
19#include <cstddef>
20#include <cstdint>
21#include <initializer_list>
22#include <iterator>
23#include <vector>
24
25namespace absl {
26namespace random_internal {
27
28// This class conforms to the C++ Standard "Seed Sequence" concept
29// [rand.req.seedseq].
30//
31// An "ExplicitSeedSeq" is meant to provide a conformant interface for
32// forwarding pre-computed seed material to the constructor of a class
33// conforming to the "Uniform Random Bit Generator" concept. This class makes no
34// attempt to mutate the state provided by its constructor, and returns it
35// directly via ExplicitSeedSeq::generate().
36//
37// If this class is asked to generate more seed material than was provided to
38// the constructor, then the remaining bytes will be filled with deterministic,
39// nonrandom data.
40class ExplicitSeedSeq {
41 public:
42 using result_type = uint32_t;
43
44 ExplicitSeedSeq() : state_() {}
45
46 // Copy and move both allowed.
47 ExplicitSeedSeq(const ExplicitSeedSeq& other) = default;
48 ExplicitSeedSeq& operator=(const ExplicitSeedSeq& other) = default;
49 ExplicitSeedSeq(ExplicitSeedSeq&& other) = default;
50 ExplicitSeedSeq& operator=(ExplicitSeedSeq&& other) = default;
51
52 template <typename Iterator>
53 ExplicitSeedSeq(Iterator begin, Iterator end) {
54 for (auto it = begin; it != end; it++) {
55 state_.push_back(*it & 0xffffffff);
56 }
57 }
58
59 template <typename T>
60 ExplicitSeedSeq(std::initializer_list<T> il)
61 : ExplicitSeedSeq(il.begin(), il.end()) {}
62
63 size_t size() const { return state_.size(); }
64
65 template <typename OutIterator>
66 void param(OutIterator out) const {
67 std::copy(std::begin(state_), std::end(state_), out);
68 }
69
70 template <typename OutIterator>
71 void generate(OutIterator begin, OutIterator end) {
72 for (size_t index = 0; begin != end; begin++) {
73 *begin = state_.empty() ? 0 : state_[index++];
74 if (index >= state_.size()) {
75 index = 0;
76 }
77 }
78 }
79
80 protected:
81 std::vector<uint32_t> state_;
82};
83
84} // namespace random_internal
85} // namespace absl
86
87#endif // ABSL_RANDOM_INTERNAL_EXPLICIT_SEED_SEQ_H_