libkazv
random-generator.hpp
Go to the documentation of this file.
1 /*
2  * This file is part of libkazv.
3  * SPDX-FileCopyrightText: 2021-2024 tusooa <tusooa@kazv.moe>
4  * SPDX-License-Identifier: AGPL-3.0-or-later
5  */
6 
7 #pragma once
8 #include <libkazv-config.hpp>
9 
10 #include <memory>
11 #include <random>
12 
13 namespace Kazv
14 {
16  {
17  public:
18  using DataT = unsigned int;
19 
31  template<class DeriveT>
32  RandomInterface(DeriveT obj)
33  : m_d(std::make_unique<Model<DeriveT>>(std::move(obj)))
34  {}
35 
42  return (*m_d)();
43  }
44 
57  template<class RangeT>
58  RangeT generateRange(std::size_t size) {
59  using ValueT = std::decay_t<decltype(* (std::declval<RangeT>().begin()))>;
60  RangeT range(size, ValueT());
61  return fillRange(std::move(range));
62  }
63 
72  template<class RangeT>
74  std::generate(range.begin(), range.end(), [this] { return (*this)(); });
75  return range;
76  }
77 
78  private:
79  struct Concept
80  {
81  virtual ~Concept() = default;
82  virtual DataT operator()() = 0;
83  };
84 
85  template<class DeriveT>
86  struct Model : public Concept
87  {
88  Model(DeriveT obj) : instance(std::move(obj)) {}
89  ~Model() override = default;
90  DataT operator()() override {
91  return instance();
92  }
93  DeriveT instance;
94  };
95 
96  std::unique_ptr<Concept> m_d;
97  };
98 
103  {
104  public:
105  RandomDeviceGenerator() : m_d(std::make_unique<std::random_device>()) {}
106 
107  auto operator()() { return (*m_d)(); }
108 
109  private:
110  std::unique_ptr<std::random_device> m_d;
111  };
112 }
A movable wrapper around std::random_device.
Definition: random-generator.hpp:103
auto operator()()
Definition: random-generator.hpp:107
RandomDeviceGenerator()
Definition: random-generator.hpp:105
Definition: random-generator.hpp:16
unsigned int DataT
Definition: random-generator.hpp:18
RangeT fillRange(RangeT range)
Fill the given range.
Definition: random-generator.hpp:73
RandomInterface(DeriveT obj)
Construct a RandomInterface using an implementation.
Definition: random-generator.hpp:32
RangeT generateRange(std::size_t size)
Generate a range containing size random elements.
Definition: random-generator.hpp:58
DataT operator()()
Generate a random number of type DataT.
Definition: random-generator.hpp:41
A RangeT is an ordered collection that can be iterated through.
Definition: range-t.hpp:21
auto end() const
The past-end iterator of this range.
auto begin() const
The beginning iterator of this range.
Definition: location.hpp:10
Definition: clientutil.hpp:217