salted_seed_seq.h 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. // 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. #ifndef ABSL_RANDOM_INTERNAL_SALTED_SEED_SEQ_H_
  15. #define ABSL_RANDOM_INTERNAL_SALTED_SEED_SEQ_H_
  16. #include <cstdint>
  17. #include <cstdlib>
  18. #include <initializer_list>
  19. #include <iterator>
  20. #include <memory>
  21. #include <type_traits>
  22. #include <utility>
  23. #include "absl/container/inlined_vector.h"
  24. #include "absl/meta/type_traits.h"
  25. #include "absl/random/internal/seed_material.h"
  26. #include "absl/types/optional.h"
  27. #include "absl/types/span.h"
  28. namespace absl {
  29. ABSL_NAMESPACE_BEGIN
  30. namespace random_internal {
  31. // This class conforms to the C++ Standard "Seed Sequence" concept
  32. // [rand.req.seedseq].
  33. //
  34. // A `SaltedSeedSeq` is meant to wrap an existing seed sequence and modify
  35. // generated sequence by mixing with extra entropy. This entropy may be
  36. // build-dependent or process-dependent. The implementation may change to be
  37. // have either or both kinds of entropy. If salt is not available sequence is
  38. // not modified.
  39. template <typename SSeq>
  40. class SaltedSeedSeq {
  41. public:
  42. using inner_sequence_type = SSeq;
  43. using result_type = typename SSeq::result_type;
  44. SaltedSeedSeq() : seq_(absl::make_unique<SSeq>()) {}
  45. template <typename Iterator>
  46. SaltedSeedSeq(Iterator begin, Iterator end)
  47. : seq_(absl::make_unique<SSeq>(begin, end)) {}
  48. template <typename T>
  49. SaltedSeedSeq(std::initializer_list<T> il)
  50. : SaltedSeedSeq(il.begin(), il.end()) {}
  51. SaltedSeedSeq(const SaltedSeedSeq&) = delete;
  52. SaltedSeedSeq& operator=(const SaltedSeedSeq&) = delete;
  53. SaltedSeedSeq(SaltedSeedSeq&&) = default;
  54. SaltedSeedSeq& operator=(SaltedSeedSeq&&) = default;
  55. template <typename RandomAccessIterator>
  56. void generate(RandomAccessIterator begin, RandomAccessIterator end) {
  57. // The common case is that generate is called with ContiguousIterators
  58. // to uint arrays. Such contiguous memory regions may be optimized,
  59. // which we detect here.
  60. using tag = absl::conditional_t<
  61. (std::is_pointer<RandomAccessIterator>::value &&
  62. std::is_same<absl::decay_t<decltype(*begin)>, uint32_t>::value),
  63. ContiguousAndUint32Tag, DefaultTag>;
  64. if (begin != end) {
  65. generate_impl(begin, end, tag{});
  66. }
  67. }
  68. template <typename OutIterator>
  69. void param(OutIterator out) const {
  70. seq_->param(out);
  71. }
  72. size_t size() const { return seq_->size(); }
  73. private:
  74. struct ContiguousAndUint32Tag {};
  75. struct DefaultTag {};
  76. // Generate which requires the iterators are contiguous pointers to uint32_t.
  77. void generate_impl(uint32_t* begin, uint32_t* end, ContiguousAndUint32Tag) {
  78. generate_contiguous(absl::MakeSpan(begin, end));
  79. }
  80. // The uncommon case for generate is that it is called with iterators over
  81. // some other buffer type which is assignable from a 32-bit value. In this
  82. // case we allocate a temporary 32-bit buffer and then copy-assign back
  83. // to the initial inputs.
  84. template <typename RandomAccessIterator>
  85. void generate_impl(RandomAccessIterator begin, RandomAccessIterator end,
  86. DefaultTag) {
  87. return generate_and_copy(std::distance(begin, end), begin);
  88. }
  89. // Fills the initial seed buffer the underlying SSeq::generate() call,
  90. // mixing in the salt material.
  91. void generate_contiguous(absl::Span<uint32_t> buffer) {
  92. seq_->generate(buffer.begin(), buffer.end());
  93. const uint32_t salt = absl::random_internal::GetSaltMaterial().value_or(0);
  94. MixIntoSeedMaterial(absl::MakeConstSpan(&salt, 1), buffer);
  95. }
  96. // Allocates a seed buffer of `n` elements, generates the seed, then
  97. // copies the result into the `out` iterator.
  98. template <typename Iterator>
  99. void generate_and_copy(size_t n, Iterator out) {
  100. // Allocate a temporary buffer, generate, and then copy.
  101. absl::InlinedVector<uint32_t, 8> data(n, 0);
  102. generate_contiguous(absl::MakeSpan(data.data(), data.size()));
  103. std::copy(data.begin(), data.end(), out);
  104. }
  105. // Because [rand.req.seedseq] is not required to be copy-constructible,
  106. // copy-assignable nor movable, we wrap it with unique pointer to be able
  107. // to move SaltedSeedSeq.
  108. std::unique_ptr<SSeq> seq_;
  109. };
  110. // is_salted_seed_seq indicates whether the type is a SaltedSeedSeq.
  111. template <typename T, typename = void>
  112. struct is_salted_seed_seq : public std::false_type {};
  113. template <typename T>
  114. struct is_salted_seed_seq<
  115. T, typename std::enable_if<std::is_same<
  116. T, SaltedSeedSeq<typename T::inner_sequence_type>>::value>::type>
  117. : public std::true_type {};
  118. // MakeSaltedSeedSeq returns a salted variant of the seed sequence.
  119. // When provided with an existing SaltedSeedSeq, returns the input parameter,
  120. // otherwise constructs a new SaltedSeedSeq which embodies the original
  121. // non-salted seed parameters.
  122. template <
  123. typename SSeq, //
  124. typename EnableIf = absl::enable_if_t<is_salted_seed_seq<SSeq>::value>>
  125. SSeq MakeSaltedSeedSeq(SSeq&& seq) {
  126. return SSeq(std::forward<SSeq>(seq));
  127. }
  128. template <
  129. typename SSeq, //
  130. typename EnableIf = absl::enable_if_t<!is_salted_seed_seq<SSeq>::value>>
  131. SaltedSeedSeq<typename std::decay<SSeq>::type> MakeSaltedSeedSeq(SSeq&& seq) {
  132. using sseq_type = typename std::decay<SSeq>::type;
  133. using result_type = typename sseq_type::result_type;
  134. absl::InlinedVector<result_type, 8> data;
  135. seq.param(std::back_inserter(data));
  136. return SaltedSeedSeq<sseq_type>(data.begin(), data.end());
  137. }
  138. } // namespace random_internal
  139. ABSL_NAMESPACE_END
  140. } // namespace absl
  141. #endif // ABSL_RANDOM_INTERNAL_SALTED_SEED_SEQ_H_