Skip to content

include/tenzr/modules/random/prng_key.h

Namespaces

Name
tenzr
tenzr::random

Classes

Name
struct tenzr::random::PRNGKey
Functional pseudo-random key formed by two 32-bit words.
struct tenzr::random::SplitKeys
Two independently derived PRNG keys.

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.

#ifndef TENZR_MODULES_RANDOM_PRNG_KEY_H_
#define TENZR_MODULES_RANDOM_PRNG_KEY_H_

#include <cstdint>
#include <utility>
#include <vector>

#include "tenzr/array.h"
#include "tenzr/common/export.h"

namespace tenzr::random {

  struct TENZR_API PRNGKey {
    uint32_t k0{0};
    uint32_t k1{0};

    PRNGKey() = default;

    explicit PRNGKey(uint64_t seed_val) noexcept : k0(static_cast<uint32_t>(seed_val >> 32)), k1(static_cast<uint32_t>(seed_val & 0xFFFFFFFFULL)) {}

    PRNGKey(uint32_t k0_val, uint32_t k1_val) noexcept : k0(k0_val), k1(k1_val) {}

    explicit PRNGKey(const Array& arr);

    [[nodiscard]] Array ToArray() const;

    [[nodiscard]] uint64_t ToU64() const noexcept { return (static_cast<uint64_t>(k0) << 32) | static_cast<uint64_t>(k1); }

    bool operator==(const PRNGKey& other) const noexcept { return k0 == other.k0 && k1 == other.k1; }

    bool operator!=(const PRNGKey& other) const noexcept { return !(*this == other); }
  };

  [[nodiscard]] TENZR_API PRNGKey Key(uint64_t seed);

  [[nodiscard]] TENZR_API std::pair<uint32_t, uint32_t> Threefry2x32(uint32_t k0, uint32_t k1, uint32_t c0, uint32_t c1) noexcept;

  struct SplitKeys {
    PRNGKey first;
    PRNGKey second;
  };

  [[nodiscard]] TENZR_API SplitKeys Split(const PRNGKey& k);

  [[nodiscard]] TENZR_API std::vector<PRNGKey> Split(const PRNGKey& k, size_t num);

  [[nodiscard]] TENZR_API PRNGKey FoldIn(const PRNGKey& k, uint32_t data);

  [[nodiscard]] TENZR_API std::vector<uint32_t> ThreefryRandomBits(const PRNGKey& k, size_t count);

}  // namespace tenzr::random

#endif  // TENZR_MODULES_RANDOM_PRNG_KEY_H_