Skip to content

src/modules/random/generator.cc

Namespaces

Name
tenzr
tenzr::random

Source code

// Copyright 2026 The Tenzr Project Authors
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "tenzr/modules/random/generator.h"

#include <cstdint>
#include <mutex>
#include <random>

namespace tenzr::random {

  Generator::Generator() { SeedRandom(); }

  Generator::Generator(uint64_t seed) { ManualSeed(seed); }

  void Generator::ManualSeed(uint64_t seed) {
    std::lock_guard<std::mutex> lock(mutex_);
    initial_seed_ = seed;
    engine_.seed(seed);
  }

  void Generator::SeedRandom() {
    std::random_device rd;
    uint64_t s = (static_cast<uint64_t>(rd()) << 32) | static_cast<uint64_t>(rd());
    ManualSeed(s);
  }

  uint64_t Generator::NextUint64() {
    std::lock_guard<std::mutex> lock(mutex_);
    return engine_();
  }

  double Generator::NextDouble() {
    std::lock_guard<std::mutex> lock(mutex_);
    std::uniform_real_distribution<double> dist(0.0, 1.0);
    return dist(engine_);
  }

  float Generator::NextFloat() {
    std::lock_guard<std::mutex> lock(mutex_);
    std::uniform_real_distribution<float> dist(0.0f, 1.0f);
    return dist(engine_);
  }

  Generator& DefaultGenerator() {
    static Generator gen;
    return gen;
  }

}  // namespace tenzr::random