diff --git a/Cargo.toml b/Cargo.toml index 18b0084..a1d30cc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "bevy_rand" -version = "0.2.0" +version = "0.3.0" edition = "2021" authors = ["Gonçalo Rica Pais da Silva "] description = "A plugin to integrate rand for ECS optimised RNG for the Bevy game engine." @@ -15,11 +15,14 @@ rust-version = "1.70.0" [features] default = ["serialize", "thread_local_entropy"] thread_local_entropy = ["dep:rand_chacha"] -serialize = ["dep:serde", "rand_core/serde1", "rand_chacha?/serde1"] +serialize = ["dep:serde", "rand_core/serde1"] + +[workspace] +members = ["bevy_prng"] [dependencies] # bevy -bevy = { version = "0.11.1", default-features = false } +bevy = { version = "0.11", default-features = false } # others serde = { version = "1.0", features = ["derive"], optional = true } @@ -27,8 +30,8 @@ rand_core = { version = "0.6", features = ["std"] } rand_chacha = { version = "0.3", optional = true } [dev-dependencies] +bevy_prng = { path = "bevy_prng", version = "0.1", features = ["rand_chacha"] } rand = "0.8" -rand_chacha = "0.3" ron = { version = "0.8.0", features = ["integer128"] } [target.'cfg(target_arch = "wasm32")'.dev-dependencies] diff --git a/README.md b/README.md index f840a1d..49ecc20 100644 --- a/README.md +++ b/README.md @@ -9,10 +9,6 @@ Bevy Rand is a plugin to provide integration of `rand` ecosystem PRNGs in an ECS friendly way. It provides a set of wrapper component and resource types that allow for safe access to a PRNG for generating random numbers, giving features like reflection, serialization for free. And with these types, it becomes possible to have determinism with the usage of these integrated PRNGs in ways that work with multi-threading and also avoid pitfalls such as unstable query iteration order. -## Prerequisites - -For a PRNG crate to be usable with Bevy Rand, at its minimum, it must implement `RngCore` and `SeedableRng` traits from `rand_core`, as well as `PartialEq`, `Clone`, and `Debug` traits. For reflection/serialization support, it should also implement `Serialize`/`Deserialize` traits from `serde`, though this can be disabled if one is not making use of reflection/serialization. As long as these traits are implemented, the PRNG can just be plugged in without an issue. - ## Overview Games often use randomness as a core mechanic. For example, card games generate a random deck for each game and killing monsters in an RPG often rewards players with a random item. While randomness makes games more interesting and increases replayability, it also makes games harder to test and prevents advanced techniques such as [deterministic lockstep](https://gafferongames.com/post/deterministic_lockstep/). @@ -58,7 +54,13 @@ Bevy Rand approaches forking via `From` implementations of the various component ## Using Bevy Rand -Usage of Bevy Rand can range from very simple to quite complex use-cases, all depending on whether one cares about deterministic output or not. +Usage of Bevy Rand can range from very simple to quite complex use-cases, all depending on whether one cares about deterministic output or not. First, add `bevy_rand`,`bevy_prng`, and either `rand_core` or `rand` to your `Cargo.toml` to bring in both the components and the PRNGs you want to use, along with the various traits needed to use the RNGs. To select a given algorithm type with `bevy_prng`, enable the feature representing the newtypes from the `rand_*` crate you want to use. + +```toml +rand_core = "0.6" +bevy_rand = "0.3" +bevy_prng = { version = "0.1", features = ["rand_chacha"] } +``` ### Registering a PRNG for use with Bevy Rand @@ -68,11 +70,11 @@ Before a PRNG can be used via `GlobalEntropy` or `EntropyComponent`, it must be use bevy::prelude::*; use bevy_rand::prelude::*; use rand_core::RngCore; -use rand_chacha::ChaCha8Rng; +use bevy_prng::ChaCha8Rng; fn main() { App::new() - .add_plugin(EntropyPlugin::::default()) + .add_plugins(EntropyPlugin::::default()) .run(); } ``` @@ -85,7 +87,7 @@ At the simplest case, using `GlobalEntropy` directly for all random number gener use bevy::prelude::ResMut; use bevy_rand::prelude::*; use rand_core::RngCore; -use rand_chacha::ChaCha8Rng; +use bevy_prng::ChaCha8Rng; fn print_random_value(mut rng: ResMut>) { println!("Random value: {}", rng.next_u32()); @@ -99,7 +101,7 @@ For seeding `EntropyComponent`s from a global source, it is best to make use of ```rust use bevy::prelude::*; use bevy_rand::prelude::*; -use rand_chacha::ChaCha8Rng; +use bevy_prng::ChaCha8Rng; #[derive(Component)] struct Source; @@ -118,7 +120,7 @@ fn setup_source(mut commands: Commands, mut global: ResMut"] +description = "A crate providing newtyped RNGs for integration into Bevy." +repository = "https://github.com/Bluefinger/bevy_rand" +license = "MIT OR Apache-2.0" +keywords = ["game", "bevy", "rand", "rng"] +categories = ["game-engines", "algorithms"] +exclude = ["/.*"] +resolver = "2" +rust-version = "1.70.0" + +[features] +default = ["serialize"] +serialize = [ + "dep:serde", + "rand_core/serde1", + "rand_chacha?/serde1", + "rand_pcg?/serde1", + "rand_xoshiro?/serde1", + "wyrand?/serde1", +] + +[dependencies] +bevy = { version = "0.11", default-features = false } +rand_core = { version = "0.6", features = ["std"] } +serde = { version = "1.0", features = ["derive"], optional = true } +rand_chacha = { version = "0.3", optional = true } +wyrand = { version = "0.1", optional = true } +rand_pcg = { version = "0.3", optional = true } +rand_xoshiro = { version = "0.6", optional = true } diff --git a/bevy_prng/LICENSE-APACHE b/bevy_prng/LICENSE-APACHE new file mode 100644 index 0000000..4b5dc5a --- /dev/null +++ b/bevy_prng/LICENSE-APACHE @@ -0,0 +1,201 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, +and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by +the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all +other entities that control, are controlled by, or are under common +control with that entity. For the purposes of this definition, +"control" means (i) the power, direct or indirect, to cause the +direction or management of such entity, whether by contract or +otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity +exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, +including but not limited to software source code, documentation +source, and configuration files. + +"Object" form shall mean any form resulting from mechanical +transformation or translation of a Source form, including but +not limited to compiled object code, generated documentation, +and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or +Object form, made available under the License, as indicated by a +copyright notice that is included in or attached to the work +(an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object +form, that is based on (or derived from) the Work and for which the +editorial revisions, annotations, elaborations, or other modifications +represent, as a whole, an original work of authorship. For the purposes +of this License, Derivative Works shall not include works that remain +separable from, or merely link (or bind by name) to the interfaces of, +the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including +the original version of the Work and any modifications or additions +to that Work or Derivative Works thereof, that is intentionally +submitted to Licensor for inclusion in the Work by the copyright owner +or by an individual or Legal Entity authorized to submit on behalf of +the copyright owner. For the purposes of this definition, "submitted" +means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, +and issue tracking systems that are managed by, or on behalf of, the +Licensor for the purpose of discussing and improving the Work, but +excluding communication that is conspicuously marked or otherwise +designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity +on behalf of whom a Contribution has been received by Licensor and +subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable +copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the +Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable +(except as stated in this section) patent license to make, have made, +use, offer to sell, sell, import, and otherwise transfer the Work, +where such license applies only to those patent claims licensable +by such Contributor that are necessarily infringed by their +Contribution(s) alone or by combination of their Contribution(s) +with the Work to which such Contribution(s) was submitted. If You +institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work +or a Contribution incorporated within the Work constitutes direct +or contributory patent infringement, then any patent licenses +granted to You under this License for that Work shall terminate +as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the +Work or Derivative Works thereof in any medium, with or without +modifications, and in Source or Object form, provided that You +meet the following conditions: + +(a) You must give any other recipients of the Work or +Derivative Works a copy of this License; and + +(b) You must cause any modified files to carry prominent notices +stating that You changed the files; and + +(c) You must retain, in the Source form of any Derivative Works +that You distribute, all copyright, patent, trademark, and +attribution notices from the Source form of the Work, +excluding those notices that do not pertain to any part of +the Derivative Works; and + +(d) If the Work includes a "NOTICE" text file as part of its +distribution, then any Derivative Works that You distribute must +include a readable copy of the attribution notices contained +within such NOTICE file, excluding those notices that do not +pertain to any part of the Derivative Works, in at least one +of the following places: within a NOTICE text file distributed +as part of the Derivative Works; within the Source form or +documentation, if provided along with the Derivative Works; or, +within a display generated by the Derivative Works, if and +wherever such third-party notices normally appear. The contents +of the NOTICE file are for informational purposes only and +do not modify the License. You may add Your own attribution +notices within Derivative Works that You distribute, alongside +or as an addendum to the NOTICE text from the Work, provided +that such additional attribution notices cannot be construed +as modifying the License. + +You may add Your own copyright statement to Your modifications and +may provide additional or different license terms and conditions +for use, reproduction, or distribution of Your modifications, or +for any such Derivative Works as a whole, provided Your use, +reproduction, and distribution of the Work otherwise complies with +the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, +any Contribution intentionally submitted for inclusion in the Work +by You to the Licensor shall be under the terms and conditions of +this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify +the terms of any separate license agreement you may have executed +with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade +names, trademarks, service marks, or product names of the Licensor, +except as required for reasonable and customary use in describing the +origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or +agreed to in writing, Licensor provides the Work (and each +Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +implied, including, without limitation, any warranties or conditions +of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A +PARTICULAR PURPOSE. You are solely responsible for determining the +appropriateness of using or redistributing the Work and assume any +risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, +whether in tort (including negligence), contract, or otherwise, +unless required by applicable law (such as deliberate and grossly +negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, +incidental, or consequential damages of any character arising as a +result of this License or out of the use or inability to use the +Work (including but not limited to damages for loss of goodwill, +work stoppage, computer failure or malfunction, or any and all +other commercial damages or losses), even if such Contributor +has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing +the Work or Derivative Works thereof, You may choose to offer, +and charge a fee for, acceptance of support, warranty, indemnity, +or other liability obligations and/or rights consistent with this +License. However, in accepting such obligations, You may act only +on Your own behalf and on Your sole responsibility, not on behalf +of any other Contributor, and only if You agree to indemnify, +defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason +of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following +boilerplate notice, with the fields enclosed by brackets "[]" +replaced with your own identifying information. (Don't include +the brackets!) The text should be enclosed in the appropriate +comment syntax for the file format. We also recommend that a +file or class name and description of purpose be included on the +same "printed page" as the copyright notice for easier +identification within third-party archives. + +Copyright 2022 Bluefinger + +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 + +http://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. diff --git a/bevy_prng/LICENSE-MIT b/bevy_prng/LICENSE-MIT new file mode 100644 index 0000000..aab9b63 --- /dev/null +++ b/bevy_prng/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Bluefinger + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/bevy_prng/README.md b/bevy_prng/README.md new file mode 100644 index 0000000..28cb509 --- /dev/null +++ b/bevy_prng/README.md @@ -0,0 +1,58 @@ +# Bevy PRNG + +[![Crates.io](https://img.shields.io/crates/v/bevy_prng.svg)](https://crates.io/crates/bevy_prng) +[![CI](https://github.com/Bluefinger/bevy_rand/actions/workflows/ci.yml/badge.svg)](https://github.com/Bluefinger/bevy_rand/actions/workflows/ci.yml) +[![License](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue.svg)](https://github.com/Bluefinger/bevy_rand) +[![Documentation](https://docs.rs/bevy_prng/badge.svg)](https://docs.rs/bevy_prng) + +## What is Bevy PRNG? + +`bevy_prng` is a crate that provides newtyped versions of various `rand_*` PRNG algorithm crates to make them suitable for integration within `bevy` for reflection purposes. It enables these types to have stable `TypePath`s and otherwise implement various required traits. This crate can be used as standalone to provide access to various PRNG algorithms of one's choice, to then use to write components/resources for one's game in `bevy`, but primarily, it's purpose to support and be a counterpart to `bevy_rand` (which provides the generic wrapper component/resource that `bevy_prng` types can plug in to). + +## Using Bevy PRNG + +By default, `bevy_prng` won't export anything _unless_ the feature/algorithm you require is explicitly defined. In order to gain access to a newtyped PRNG struct, you'll have activate one of the following features: + +- **`rand_chacha`** - This enables the exporting of newtyped `ChaCha*Rng` structs, for those that want/need to use a CSPRNG level source. +- **`rand_pcg`** - This enables the exporting of newtyped `Pcg*` structs from `rand_pcg`. +- **`rand_xoshiro`** - This enables the exporting of newtyped `Xoshiro*` structs from `rand_xoshiro`. It also reexports `Seed512` so to allow setting up `Xoshiro512StarStar` and so forth without the need to pull in `rand_xoshiro` explicitly. +- **`wyrand`** - This enables the exporting of newtyped `WyRand` from `wyrand`, the same algorithm in use within `fastrand`/`turborand`. + +In addition to these feature flags to enable various supported algorithms, there's also **`serialize`** flag to provide `serde` support for `Serialize`/`Deserialize`, which is enabled by default. + +All types are provided at the top-level of the module: + +```rust ignore +use bevy_prng::*; +``` + +## Supported PRNG Algorithms/Crates + +All the below crates implement the necessary traits to be compatible with `bevy_prng`. Additional PRNG crates can be added via PR's to this crate/repo, provided the PRNGs implement `Debug`, `Clone`, `PartialEq` and have optional `Serialize`/`Deserialize` `serde` traits implemented and put behind appropriate feature flags. + +### Cryptographically Secure PRNGs + +- [rand_chacha](https://crates.io/crates/rand_chacha) + +### Non-Cryptographically Secure PRNGS + +- [wyrand](https://crates.io/crates/wyrand) +- [rand_xoshiro](https://crates.io/crates/rand_xoshiro) +- [rand_pcg](https://crates.io/crates/rand_pcg) + +## Supported Versions & MSRV + +`bevy_prng` uses the same MSRV as `bevy`. + +| `bevy` | `bevy_prng` | +| -------- | ----------- | +| v0.11 | v0.1 | + +## License + +Licensed under either of + +- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) +- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +at your option. diff --git a/bevy_prng/src/lib.rs b/bevy_prng/src/lib.rs new file mode 100644 index 0000000..bf64893 --- /dev/null +++ b/bevy_prng/src/lib.rs @@ -0,0 +1,305 @@ +#![doc = include_str!("../README.md")] +#![deny(missing_docs)] +#![cfg_attr(docsrs, feature(doc_cfg))] +#![cfg_attr(docsrs, allow(unused_attributes))] +#[cfg(any( + feature = "wyrand", + feature = "rand_chacha", + feature = "rand_pcg", + feature = "rand_xoshiro" +))] +use bevy::prelude::{Reflect, ReflectFromReflect}; +#[cfg(any( + feature = "wyrand", + feature = "rand_chacha", + feature = "rand_pcg", + feature = "rand_xoshiro" +))] +use rand_core::{RngCore, SeedableRng}; + +#[cfg(all( + any( + feature = "wyrand", + feature = "rand_chacha", + feature = "rand_pcg", + feature = "rand_xoshiro" + ), + feature = "serialize" +))] +use bevy::prelude::{ReflectDeserialize, ReflectSerialize}; + +#[cfg(all( + any( + feature = "wyrand", + feature = "rand_chacha", + feature = "rand_pcg", + feature = "rand_xoshiro" + ), + feature = "serialize" +))] +use serde::{Deserialize, Serialize}; + +#[cfg(any( + feature = "wyrand", + feature = "rand_chacha", + feature = "rand_pcg", + feature = "rand_xoshiro" +))] +macro_rules! newtype_prng { + ($newtype:tt, $rng:ty, $seed:ty, $doc:tt, $feature:tt) => { + #[doc = $doc] + #[derive(Debug, Clone, PartialEq, Reflect)] + #[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))] + #[cfg_attr( + all(feature = "serialize"), + reflect_value(Debug, PartialEq, FromReflect, Serialize, Deserialize) + )] + #[cfg_attr( + all(not(feature = "serialize")), + reflect_value(Debug, PartialEq, FromReflect) + )] + #[cfg_attr(docsrs, doc(cfg(feature = $feature)))] + #[repr(transparent)] + pub struct $newtype($rng); + + impl $newtype { + /// Create a new instance. + #[inline] + #[must_use] + pub fn new(rng: $rng) -> Self { + Self(rng) + } + } + + impl RngCore for $newtype { + #[inline(always)] + fn next_u32(&mut self) -> u32 { + self.0.next_u32() + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + self.0.next_u64() + } + + #[inline] + fn fill_bytes(&mut self, dest: &mut [u8]) { + self.0.fill_bytes(dest) + } + + #[inline] + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), ::rand_core::Error> { + self.0.try_fill_bytes(dest) + } + } + + impl SeedableRng for $newtype { + type Seed = $seed; + + #[inline] + fn from_seed(seed: Self::Seed) -> Self { + Self::new(<$rng>::from_seed(seed)) + } + } + + impl From<$rng> for $newtype { + #[inline] + fn from(value: $rng) -> Self { + Self::new(value) + } + } + }; +} + +#[cfg(feature = "wyrand")] +newtype_prng!( + WyRand, + ::wyrand::WyRand, + [u8; 8], + "A newtyped [`wyrand::WyRand`] RNG", + "wyrand" +); + +#[cfg(feature = "rand_chacha")] +newtype_prng!( + ChaCha8Rng, + ::rand_chacha::ChaCha8Rng, + [u8; 32], + "A newtyped [`rand_chacha::ChaCha8Rng`] RNG", + "rand_chacha" +); + +#[cfg(feature = "rand_chacha")] +newtype_prng!( + ChaCha12Rng, + ::rand_chacha::ChaCha12Rng, + [u8; 32], + "A newtyped [`rand_chacha::ChaCha12Rng`] RNG", + "rand_chacha" +); + +#[cfg(feature = "rand_chacha")] +newtype_prng!( + ChaCha20Rng, + ::rand_chacha::ChaCha20Rng, + [u8; 32], + "A newtyped [`rand_chacha::ChaCha20Rng`] RNG", + "rand_chacha" +); + +#[cfg(feature = "rand_pcg")] +newtype_prng!( + Pcg32, + ::rand_pcg::Pcg32, + [u8; 16], + "A newtyped [`rand_pcg::Pcg32`] RNG", + "rand_pcg" +); + +#[cfg(feature = "rand_pcg")] +newtype_prng!( + Pcg64, + ::rand_pcg::Pcg64, + [u8; 32], + "A newtyped [`rand_pcg::Pcg64`] RNG", + "rand_pcg" +); + +#[cfg(feature = "rand_pcg")] +newtype_prng!( + Pcg64Mcg, + ::rand_pcg::Pcg64Mcg, + [u8; 16], + "A newtyped [`rand_pcg::Pcg64Mcg`] RNG", + "rand_pcg" +); + +#[cfg(feature = "rand_xoshiro")] +#[cfg_attr(docsrs, doc(cfg(feature = "rand_xoshiro")))] +pub use rand_xoshiro::Seed512; + +#[cfg(feature = "rand_xoshiro")] +newtype_prng!( + Xoshiro512StarStar, + ::rand_xoshiro::Xoshiro512StarStar, + ::rand_xoshiro::Seed512, + "A newtyped [`rand_xoshiro::Xoshiro512StarStar`] RNG", + "rand_xoshiro" +); + +#[cfg(feature = "rand_xoshiro")] +newtype_prng!( + Xoshiro512PlusPlus, + ::rand_xoshiro::Xoshiro512PlusPlus, + ::rand_xoshiro::Seed512, + "A newtyped [`rand_xoshiro::Xoshiro512PlusPlus`] RNG", + "rand_xoshiro" +); + +#[cfg(feature = "rand_xoshiro")] +newtype_prng!( + Xoshiro512Plus, + ::rand_xoshiro::Xoshiro512Plus, + ::rand_xoshiro::Seed512, + "A newtyped [`rand_xoshiro::Xoshiro512Plus`] RNG", + "rand_xoshiro" +); + +#[cfg(feature = "rand_xoshiro")] +newtype_prng!( + Xoshiro256StarStar, + ::rand_xoshiro::Xoshiro256StarStar, + [u8; 32], + "A newtyped [`rand_xoshiro::Xoshiro256StarStar`] RNG", + "rand_xoshiro" +); + +#[cfg(feature = "rand_xoshiro")] +newtype_prng!( + Xoshiro256PlusPlus, + ::rand_xoshiro::Xoshiro256PlusPlus, + [u8; 32], + "A newtyped [`rand_xoshiro::Xoshiro256PlusPlus`] RNG", + "rand_xoshiro" +); + +#[cfg(feature = "rand_xoshiro")] +newtype_prng!( + Xoshiro256Plus, + ::rand_xoshiro::Xoshiro256Plus, + [u8; 32], + "A newtyped [`rand_xoshiro::Xoshiro256Plus`] RNG", + "rand_xoshiro" +); + +#[cfg(feature = "rand_xoshiro")] +newtype_prng!( + Xoroshiro128StarStar, + ::rand_xoshiro::Xoroshiro128StarStar, + [u8; 16], + "A newtyped [`rand_xoshiro::Xoshiro128StarStar`] RNG", + "rand_xoshiro" +); + +#[cfg(feature = "rand_xoshiro")] +newtype_prng!( + Xoroshiro128PlusPlus, + ::rand_xoshiro::Xoroshiro128PlusPlus, + [u8; 16], + "A newtyped [`rand_xoshiro::Xoshiro256PlusPlus`] RNG", + "rand_xoshiro" +); + +#[cfg(feature = "rand_xoshiro")] +newtype_prng!( + Xoroshiro128Plus, + ::rand_xoshiro::Xoroshiro128Plus, + [u8; 16], + "A newtyped [`rand_xoshiro::Xoshiro128Plus`] RNG", + "rand_xoshiro" +); + +#[cfg(feature = "rand_xoshiro")] +newtype_prng!( + Xoshiro128StarStar, + ::rand_xoshiro::Xoshiro128StarStar, + [u8; 16], + "A newtyped [`rand_xoshiro::Xoshiro128StarStar`] RNG", + "rand_xoshiro" +); + +#[cfg(feature = "rand_xoshiro")] +newtype_prng!( + Xoshiro128PlusPlus, + ::rand_xoshiro::Xoshiro128PlusPlus, + [u8; 16], + "A newtyped [`rand_xoshiro::Xoshiro256PlusPlus`] RNG", + "rand_xoshiro" +); + +#[cfg(feature = "rand_xoshiro")] +newtype_prng!( + Xoshiro128Plus, + ::rand_xoshiro::Xoshiro128Plus, + [u8; 16], + "A newtyped [`rand_xoshiro::Xoshiro128Plus`] RNG", + "rand_xoshiro" +); + +#[cfg(feature = "rand_xoshiro")] +newtype_prng!( + Xoroshiro64StarStar, + ::rand_xoshiro::Xoroshiro64StarStar, + [u8; 8], + "A newtyped [`rand_xoshiro::Xoroshiro64StarStar`] RNG", + "rand_xoshiro" +); + +#[cfg(feature = "rand_xoshiro")] +newtype_prng!( + Xoroshiro64Star, + ::rand_xoshiro::Xoroshiro64Star, + [u8; 8], + "A newtyped [`rand_xoshiro::Xoroshiro64Star`] RNG", + "rand_xoshiro" +); diff --git a/examples/turn_based_game.rs b/examples/turn_based_game.rs index 333975b..f07ebfe 100644 --- a/examples/turn_based_game.rs +++ b/examples/turn_based_game.rs @@ -1,9 +1,9 @@ #![allow(clippy::type_complexity)] use bevy::prelude::*; +use bevy_prng::ChaCha8Rng; use bevy_rand::prelude::*; use rand::prelude::{IteratorRandom, Rng}; -use rand_chacha::ChaCha8Rng; #[derive(Component)] struct Player; diff --git a/src/component.rs b/src/component.rs index 3c7dbd8..19d35a7 100644 --- a/src/component.rs +++ b/src/component.rs @@ -1,10 +1,7 @@ use std::fmt::Debug; use crate::{resource::GlobalEntropy, traits::SeedableEntropySource}; -use bevy::{ - prelude::{Component, Mut, Reflect, ReflectComponent, ReflectFromReflect, ResMut}, - reflect::{utility::GenericTypePathCell, TypePath}, -}; +use bevy::prelude::{Component, Mut, Reflect, ReflectComponent, ReflectFromReflect, ResMut}; use rand_core::{RngCore, SeedableRng}; #[cfg(feature = "thread_local_entropy")] @@ -31,7 +28,7 @@ use serde::{Deserialize, Serialize}; /// ``` /// use bevy::prelude::*; /// use bevy_rand::prelude::*; -/// use rand_chacha::ChaCha8Rng; +/// use bevy_prng::ChaCha8Rng; /// /// #[derive(Component)] /// struct Source; @@ -49,7 +46,7 @@ use serde::{Deserialize, Serialize}; /// ``` /// use bevy::prelude::*; /// use bevy_rand::prelude::*; -/// use rand_chacha::ChaCha8Rng; +/// use bevy_prng::ChaCha8Rng; /// /// #[derive(Component)] /// struct Source; @@ -67,7 +64,7 @@ use serde::{Deserialize, Serialize}; /// ``` /// use bevy::prelude::*; /// use bevy_rand::prelude::*; -/// use rand_chacha::ChaCha8Rng; +/// use bevy_prng::ChaCha8Rng; /// /// #[derive(Component)] /// struct Npc; @@ -90,7 +87,6 @@ use serde::{Deserialize, Serialize}; /// } /// ``` #[derive(Debug, Clone, PartialEq, Eq, Component, Reflect)] -#[reflect_value(type_path = false)] #[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))] #[cfg_attr( feature = "serialize", @@ -98,11 +94,11 @@ use serde::{Deserialize, Serialize}; )] #[cfg_attr( all(feature = "serialize"), - reflect_value(Debug, PartialEq, Component, FromReflect, Serialize, Deserialize) + reflect(Debug, PartialEq, Component, FromReflect, Serialize, Deserialize) )] #[cfg_attr( all(not(feature = "serialize")), - reflect_value(Debug, PartialEq, Component, FromReflect) + reflect(Debug, PartialEq, Component, FromReflect) )] pub struct EntropyComponent(R); @@ -113,9 +109,7 @@ impl EntropyComponent { pub fn new(rng: R) -> Self { Self(rng) } -} -impl EntropyComponent { /// Reseeds the internal `RngCore` instance with a new seed. #[inline] pub fn reseed(&mut self, seed: R::Seed) { @@ -123,35 +117,6 @@ impl EntropyComponent { } } -impl TypePath for EntropyComponent { - fn type_path() -> &'static str { - static CELL: GenericTypePathCell = GenericTypePathCell::new(); - CELL.get_or_insert::(|| { - format!( - "bevy_rand::component::EntropyComponent<{}>", - std::any::type_name::() - ) - }) - } - - fn short_type_path() -> &'static str { - static CELL: GenericTypePathCell = GenericTypePathCell::new(); - CELL.get_or_insert::(|| bevy::utils::get_short_name(Self::type_path())) - } - - fn type_ident() -> Option<&'static str> { - Some("EntropyComponent") - } - - fn crate_name() -> Option<&'static str> { - Some("bevy_rand") - } - - fn module_path() -> Option<&'static str> { - Some("bevy_rand::component") - } -} - impl Default for EntropyComponent { fn default() -> Self { Self::from_entropy() @@ -183,6 +148,7 @@ impl RngCore for EntropyComponent { impl SeedableRng for EntropyComponent { type Seed = R::Seed; + #[inline] fn from_seed(seed: Self::Seed) -> Self { Self::new(R::from_seed(seed)) } @@ -203,9 +169,9 @@ impl SeedableRng for EntropyComponent { // Source entropy from thread local user-space RNG instead of // system entropy source to reduce overhead when creating many // rng instances for many entities at once. - ThreadLocalEntropy.fill_bytes(seed.as_mut()); + ThreadLocalEntropy::new().fill_bytes(seed.as_mut()); - Self::new(R::from_seed(seed)) + Self::from_seed(seed) } } @@ -239,7 +205,8 @@ impl From<&mut ResMut<'_, GlobalEntropy>> #[cfg(test)] mod tests { - use rand_chacha::ChaCha8Rng; + use bevy::reflect::TypePath; + use bevy_prng::ChaCha8Rng; use super::*; @@ -258,7 +225,7 @@ mod tests { #[test] fn type_paths() { assert_eq!( - "bevy_rand::component::EntropyComponent", + "bevy_rand::component::EntropyComponent", EntropyComponent::::type_path() ); @@ -270,18 +237,18 @@ mod tests { #[cfg(feature = "serialize")] #[test] - fn rng_reflection() { + fn rng_untyped_serialization() { use bevy::reflect::{ serde::{ReflectSerializer, UntypedReflectDeserializer}, TypeRegistryInternal, }; - use ron::ser::to_string; + use ron::to_string; use serde::de::DeserializeSeed; let mut registry = TypeRegistryInternal::default(); registry.register::>(); - let mut val = EntropyComponent::::from_seed([7; 32]); + let mut val: EntropyComponent = EntropyComponent::from_seed([7; 32]); // Modify the state of the RNG instance val.next_u32(); @@ -292,7 +259,7 @@ mod tests { assert_eq!( &serialized, - "{\"bevy_rand::component::EntropyComponent\":((seed:(7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7),stream:0,word_pos:1))}" + "{\"bevy_rand::component::EntropyComponent\":(((seed:(7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7),stream:0,word_pos:1)))}" ); let mut deserializer = ron::Deserializer::from_str(&serialized).unwrap(); @@ -315,4 +282,54 @@ mod tests { "The deserialized EntropyComponent should have the same output as original" ); } + + #[cfg(feature = "serialize")] + #[test] + fn rng_typed_serialization() { + use bevy::reflect::{ + serde::{TypedReflectDeserializer, TypedReflectSerializer}, + GetTypeRegistration, TypeRegistryInternal, + }; + use ron::ser::to_string; + use serde::de::DeserializeSeed; + + let mut registry = TypeRegistryInternal::default(); + registry.register::>(); + + let registered_type = EntropyComponent::::get_type_registration(); + + let mut val = EntropyComponent::::from_seed([7; 32]); + + // Modify the state of the RNG instance + val.next_u32(); + + let ser = TypedReflectSerializer::new(&val, ®istry); + + let serialized = to_string(&ser).unwrap(); + + assert_eq!( + &serialized, + "(((seed:(7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7),stream:0,word_pos:1)))" + ); + + let mut deserializer = ron::Deserializer::from_str(&serialized).unwrap(); + + let de = TypedReflectDeserializer::new(®istered_type, ®istry); + + let value = de.deserialize(&mut deserializer).unwrap(); + + let mut dynamic = value.take::>().unwrap(); + + // The two instances should be the same + assert_eq!( + val, dynamic, + "The deserialized EntropyComponent should equal the original" + ); + // They should output the same numbers, as no state is lost between serialization and deserialization. + assert_eq!( + val.next_u32(), + dynamic.next_u32(), + "The deserialized EntropyComponent should have the same output as original" + ); + } } diff --git a/src/lib.rs b/src/lib.rs index 233acb1..9ee9663 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,13 +4,13 @@ #![deny(missing_docs)] #![doc = include_str!("../README.md")] -/// Components for integrating `RngCore` PRNGs into bevy. +/// Components for integrating [`RngCore`] PRNGs into bevy. Must be newtyped to support [`Reflect`]. pub mod component; -/// Plugin for integrating `RngCore` PRNGs into bevy. +/// Plugin for integrating [`RngCore`] PRNGs into bevy. Must be newtyped to support [`Reflect`]. pub mod plugin; /// Prelude for providing all necessary types for easy use. pub mod prelude; -/// Resource for integrating `RngCore` PRNGs into bevy. +/// Resource for integrating [`RngCore`] PRNGs into bevy. Must be newtyped to support [`Reflect`]. pub mod resource; #[cfg(feature = "thread_local_entropy")] mod thread_local_entropy; diff --git a/src/plugin.rs b/src/plugin.rs index 3f5299d..fa4d580 100644 --- a/src/plugin.rs +++ b/src/plugin.rs @@ -10,13 +10,15 @@ use rand_core::SeedableRng; /// use bevy::prelude::*; /// use bevy_rand::prelude::*; /// use rand_core::RngCore; -/// use rand_chacha::{ChaCha8Rng, ChaCha12Rng}; +/// use bevy_prng::{ChaCha8Rng, ChaCha12Rng}; /// /// fn main() { /// App::new() -/// .add_plugin(EntropyPlugin::::default()) -/// .add_plugin(EntropyPlugin::::default()) -/// .add_system(print_random_value) +/// .add_plugins(( +/// EntropyPlugin::::default(), +/// EntropyPlugin::::default() +/// )) +/// .add_systems(Update, print_random_value) /// .run(); /// } /// diff --git a/src/resource.rs b/src/resource.rs index 4de85cc..250e37b 100644 --- a/src/resource.rs +++ b/src/resource.rs @@ -1,10 +1,7 @@ use std::fmt::Debug; use crate::traits::SeedableEntropySource; -use bevy::{ - prelude::{Reflect, ReflectFromReflect, ReflectResource, Resource}, - reflect::{utility::GenericTypePathCell, TypePath}, -}; +use bevy::prelude::{Reflect, ReflectFromReflect, ReflectResource, Resource}; use rand_core::{RngCore, SeedableRng}; #[cfg(feature = "thread_local_entropy")] @@ -26,14 +23,13 @@ use serde::{Deserialize, Serialize}; /// use bevy::prelude::*; /// use bevy_rand::prelude::*; /// use rand_core::RngCore; -/// use rand_chacha::ChaCha8Rng; +/// use bevy_prng::ChaCha8Rng; /// /// fn print_random_value(mut rng: ResMut>) { /// println!("Random value: {}", rng.next_u32()); /// } /// ``` #[derive(Debug, Clone, PartialEq, Eq, Resource, Reflect)] -#[reflect_value(type_path = false)] #[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))] #[cfg_attr( feature = "serialize", @@ -41,11 +37,11 @@ use serde::{Deserialize, Serialize}; )] #[cfg_attr( feature = "serialize", - reflect_value(Debug, PartialEq, Resource, FromReflect, Serialize, Deserialize) + reflect(Debug, PartialEq, Resource, FromReflect, Serialize, Deserialize) )] #[cfg_attr( not(feature = "serialize"), - reflect_value(Debug, PartialEq, Resource, FromReflect) + reflect(Debug, PartialEq, Resource, FromReflect) )] pub struct GlobalEntropy(R); @@ -66,35 +62,6 @@ impl GlobalEntropy { } } -impl TypePath for GlobalEntropy { - fn type_path() -> &'static str { - static CELL: GenericTypePathCell = GenericTypePathCell::new(); - CELL.get_or_insert::(|| { - format!( - "bevy_rand::resource::GlobalEntropy<{}>", - std::any::type_name::() - ) - }) - } - - fn short_type_path() -> &'static str { - static CELL: GenericTypePathCell = GenericTypePathCell::new(); - CELL.get_or_insert::(|| bevy::utils::get_short_name(Self::type_path())) - } - - fn type_ident() -> Option<&'static str> { - Some("GlobalEntropy") - } - - fn crate_name() -> Option<&'static str> { - Some("bevy_rand") - } - - fn module_path() -> Option<&'static str> { - Some("bevy_rand::resource") - } -} - impl Default for GlobalEntropy { fn default() -> Self { Self::from_entropy() @@ -126,6 +93,7 @@ impl RngCore for GlobalEntropy { impl SeedableRng for GlobalEntropy { type Seed = R::Seed; + #[inline] fn from_seed(seed: Self::Seed) -> Self { Self::new(R::from_seed(seed)) } @@ -146,9 +114,9 @@ impl SeedableRng for GlobalEntropy { // Source entropy from thread local user-space RNG instead of // system entropy source to reduce overhead when creating many // rng instances for many resources at once. - ThreadLocalEntropy.fill_bytes(seed.as_mut()); + ThreadLocalEntropy::new().fill_bytes(seed.as_mut()); - Self::new(R::from_seed(seed)) + Self::from_seed(seed) } } @@ -166,14 +134,15 @@ impl From<&mut R> for GlobalEntropy { #[cfg(test)] mod tests { - use rand_chacha::ChaCha8Rng; + use bevy::reflect::TypePath; + use bevy_prng::ChaCha8Rng; use super::*; #[test] fn type_paths() { assert_eq!( - "bevy_rand::resource::GlobalEntropy", + "bevy_rand::resource::GlobalEntropy", GlobalEntropy::::type_path() ); @@ -185,7 +154,7 @@ mod tests { #[cfg(feature = "serialize")] #[test] - fn rng_reflection() { + fn rng_untyped_serialization() { use bevy::reflect::{ serde::{ReflectSerializer, UntypedReflectDeserializer}, TypeRegistryInternal, @@ -207,7 +176,7 @@ mod tests { assert_eq!( &serialized, - "{\"bevy_rand::resource::GlobalEntropy\":((seed:(7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7),stream:0,word_pos:1))}" + "{\"bevy_rand::resource::GlobalEntropy\":(((seed:(7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7),stream:0,word_pos:1)))}" ); let mut deserializer = ron::Deserializer::from_str(&serialized).unwrap(); @@ -230,4 +199,54 @@ mod tests { "The deserialized GlobalEntropy should have the same output as original" ); } + + #[cfg(feature = "serialize")] + #[test] + fn rng_typed_serialization() { + use bevy::reflect::{ + serde::{TypedReflectDeserializer, TypedReflectSerializer}, + GetTypeRegistration, TypeRegistryInternal, + }; + use ron::to_string; + use serde::de::DeserializeSeed; + + let mut registry = TypeRegistryInternal::default(); + registry.register::>(); + + let registered_type = GlobalEntropy::::get_type_registration(); + + let mut val = GlobalEntropy::::from_seed([7; 32]); + + // Modify the state of the RNG instance + val.next_u32(); + + let ser = TypedReflectSerializer::new(&val, ®istry); + + let serialized = to_string(&ser).unwrap(); + + assert_eq!( + &serialized, + "(((seed:(7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7),stream:0,word_pos:1)))" + ); + + let mut deserializer = ron::Deserializer::from_str(&serialized).unwrap(); + + let de = TypedReflectDeserializer::new(®istered_type, ®istry); + + let value = de.deserialize(&mut deserializer).unwrap(); + + let mut dynamic = value.take::>().unwrap(); + + // The two instances should be the same + assert_eq!( + val, dynamic, + "The deserialized GlobalEntropy should equal the original" + ); + // They should output the same numbers, as no state is lost between serialization and deserialization. + assert_eq!( + val.next_u32(), + dynamic.next_u32(), + "The deserialized GlobalEntropy should have the same output as original" + ); + } } diff --git a/src/thread_local_entropy.rs b/src/thread_local_entropy.rs index 4348c4d..72885b0 100644 --- a/src/thread_local_entropy.rs +++ b/src/thread_local_entropy.rs @@ -1,7 +1,7 @@ use std::{cell::UnsafeCell, rc::Rc}; use rand_chacha::ChaCha8Rng; -use rand_core::{RngCore, SeedableRng}; +use rand_core::{CryptoRng, RngCore, SeedableRng}; thread_local! { // We require `Rc` to avoid premature freeing when `ThreadLocalEntropy` is used within thread-local destructors. @@ -12,57 +12,165 @@ thread_local! { /// sourcing entropy to OS/Hardware sources. The use of `ChaCha8` with 8 rounds as opposed to 12 or 20 rounds /// is due to tuning for additional speed/throughput. While this does minimise the quality of the entropy, /// the output should still be sufficiently secure as per the recommendations set in the -/// [Too Much Crypto](https://eprint.iacr.org/2019/1492.pdf) paper. -pub(crate) struct ThreadLocalEntropy; +/// [Too Much Crypto](https://eprint.iacr.org/2019/1492.pdf) paper. [`ThreadLocalEntropy`] is not thread-safe and +/// cannot be sent or synchronised between threads, it should be initialised within each thread context it is +/// needed in. +#[derive(Clone)] +pub(crate) struct ThreadLocalEntropy(Rc>); impl ThreadLocalEntropy { - /// Inspired by `rand`'s approach to `ThreadRng` as well as `turborand`'s instantiation methods. The [`Rc`] - /// prevents the Rng instance from being cleaned up, giving it a `'static` lifetime. However, it does not - /// allow mutable access without a cell, so using [`UnsafeCell`] to bypass overheads associated with - /// `RefCell`. There's no direct access to the pointer or mutable reference, so we control how long it - /// lives and can ensure no multiple mutable references exist. - /// - /// # Safety - /// - /// Caller must ensure only one `mut` reference exists at a time. + /// Create a new [`ThreadLocalEntropy`] instance. Only one instance can exist per thread at a time, so to + /// prevent the creation of multiple `&mut` references to #[inline] - unsafe fn get_rng(&'_ mut self) -> &'_ mut ChaCha8Rng { - // Obtain pointer to thread local instance of PRNG which with Rc, should be !Send & !Sync as well - // as 'static. - let rng = SOURCE.with(|source| source.get()); + #[must_use] + pub(crate) fn new() -> Self { + Self(SOURCE.with(|source| Rc::clone(source))) + } +} - &mut *rng +impl core::fmt::Debug for ThreadLocalEntropy { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_tuple("ThreadLocalEntropy").finish() } } impl RngCore for ThreadLocalEntropy { - #[inline] + #[inline(always)] fn next_u32(&mut self) -> u32 { - // SAFETY: We must ensure to drop the `&mut rng` ref before creating another - // mutable reference - unsafe { self.get_rng().next_u32() } + // SAFETY: We will drop this `&mut` reference before we can + // create another one, and only one reference can exist to the + // underlying thread local cell at any given time. + let rng = unsafe { &mut *self.0.get() }; + + rng.next_u32() } - #[inline] + #[inline(always)] fn next_u64(&mut self) -> u64 { - // SAFETY: We must ensure to drop the `&mut rng` ref before creating another - // mutable reference - unsafe { self.get_rng().next_u64() } + // SAFETY: We will drop this `&mut` reference before we can + // create another one, and only one reference can exist to the + // underlying thread local cell at any given time. + let rng = unsafe { &mut *self.0.get() }; + + rng.next_u64() } #[inline] fn fill_bytes(&mut self, dest: &mut [u8]) { - // SAFETY: We must ensure to drop the `&mut rng` ref before creating another - // mutable reference - unsafe { - self.get_rng().fill_bytes(dest); - } + // SAFETY: We will drop this `&mut` reference before we can + // create another one, and only one reference can exist to the + // underlying thread local cell at any given time. + let rng = unsafe { &mut *self.0.get() }; + + rng.fill_bytes(dest); } #[inline] fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> { - // SAFETY: We must ensure to drop the `&mut rng` ref before creating another - // mutable reference - unsafe { self.get_rng().try_fill_bytes(dest) } + // SAFETY: We will drop this `&mut` reference before we can + // create another one, and only one reference can exist to the + // underlying thread local cell at any given time. + let rng = unsafe { &mut *self.0.get() }; + + rng.try_fill_bytes(dest) + } +} + +impl CryptoRng for ThreadLocalEntropy {} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn smoke_test() { + let mut rng1 = ThreadLocalEntropy::new(); + let mut rng2 = ThreadLocalEntropy::new(); + + // Neither instance should interfere with each other + rng1.next_u32(); + rng2.next_u64(); + + let mut bytes1 = vec![0u8; 128]; + let mut bytes2 = vec![0u8; 128]; + + let mut cloned = rng1.clone(); + + rng1.fill_bytes(&mut bytes1); + cloned.fill_bytes(&mut bytes2); + + // Cloned ThreadLocalEntropy instances won't output the same entropy + assert_ne!(&bytes1, &bytes2); + } + + #[test] + fn unique_source_per_thread() { + use std::sync::mpsc::channel; + + let mut bytes1: Vec = vec![0u8; 128]; + let mut bytes2: Vec = vec![0u8; 128]; + + let b1 = bytes1.as_mut(); + let b2 = bytes2.as_mut(); + + let (sender, receiver) = channel(); + let sender2 = sender.clone(); + + std::thread::scope(|s| { + s.spawn(move || { + // Obtain a thread local entropy source from this thread context. + // It should be initialised with a random state. + let mut rng = ThreadLocalEntropy::new(); + + // Use the source to produce some stored entropy. + rng.fill_bytes(b1); + + // SAFETY: The pointer is valid and points to a ChaCha8Rng instance, + // and it is not being accessed elsewhere nor being mutated. It is + // safe to deference & cast the pointer so we can clone the RNG. + let source = unsafe { &*rng.0.get() }; + + sender.send(source.clone()).unwrap(); + }); + s.spawn(move || { + // Obtain a thread local entropy source from this thread context. + // It should be initialised with a random state. + let mut rng = ThreadLocalEntropy::new(); + + // Use the source to produce some stored entropy. + rng.fill_bytes(b2); + + // SAFETY: The pointer is valid and points to a ChaCha8Rng instance, + // and it is not being accessed elsewhere nor being mutated. It is + // safe to deference & cast the pointer so we can clone the RNG. + let source = unsafe { &*rng.0.get() }; + + sender2.send(source.clone()).unwrap(); + }); + }); + + // Wait for the threads to execute and resolve. + let a = receiver.recv().unwrap(); + let b = receiver.recv().unwrap(); + + // The references to the thread local RNG sources will not be + // the same, as they each were initialised with different random + // states to each other from OS sources, even though each went + // through the exact same deterministic steps to fill some bytes. + // If the tasks ran on the same thread, then the RNG sources should + // be in different resulting states as the same source was advanced + // further. + assert_ne!(&a, &b); + + // Double check the entropy output in each buffer is not the same either. + assert_ne!(&bytes1, &bytes2); + } + + #[test] + fn non_leaking_debug() { + assert_eq!( + "ThreadLocalEntropy", + format!("{:?}", ThreadLocalEntropy::new()) + ); } } diff --git a/src/traits.rs b/src/traits.rs index 9215cdd..c50bb49 100644 --- a/src/traits.rs +++ b/src/traits.rs @@ -1,5 +1,6 @@ use std::fmt::Debug; +use bevy::reflect::{FromReflect, GetTypeRegistration, Reflect, TypePath}; use rand_core::{RngCore, SeedableRng}; #[cfg(feature = "serialize")] @@ -17,6 +18,10 @@ pub trait SeedableEntropySource: + PartialEq + Sync + Send + + Reflect + + TypePath + + FromReflect + + GetTypeRegistration + Serialize + for<'a> Deserialize<'a> + private::SealedSeedable @@ -32,6 +37,10 @@ impl SeedableEntropySource for T where + PartialEq + Sync + Send + + Reflect + + TypePath + + FromReflect + + GetTypeRegistration + Serialize + for<'a> Deserialize<'a> { @@ -42,13 +51,34 @@ impl SeedableEntropySource for T where /// [`crate::resource::GlobalEntropy`]. This is a sealed trait. #[cfg(not(feature = "serialize"))] pub trait SeedableEntropySource: - RngCore + SeedableRng + Clone + Debug + PartialEq + Sync + Send + private::SealedSeedable + RngCore + + SeedableRng + + Clone + + Debug + + PartialEq + + Reflect + + TypePath + + FromReflect + + GetTypeRegistration + + Sync + + Send + + private::SealedSeedable { } #[cfg(not(feature = "serialize"))] impl SeedableEntropySource for T where - T: RngCore + SeedableRng + Clone + Debug + PartialEq + Sync + Send + T: RngCore + + SeedableRng + + Clone + + Debug + + PartialEq + + Reflect + + TypePath + + FromReflect + + GetTypeRegistration + + Sync + + Send { } diff --git a/tests/determinism.rs b/tests/determinism.rs index 99299e1..7769029 100644 --- a/tests/determinism.rs +++ b/tests/determinism.rs @@ -1,9 +1,9 @@ #![allow(clippy::type_complexity)] use bevy::prelude::*; +use bevy_prng::ChaCha8Rng; use bevy_rand::prelude::*; use rand::prelude::Rng; -use rand_chacha::ChaCha8Rng; #[cfg(target_arch = "wasm32")] use wasm_bindgen_test::*;