Skip to content

Commit

Permalink
Make RNG seedable
Browse files Browse the repository at this point in the history
  • Loading branch information
willcrichton committed Jul 11, 2024
1 parent 7378140 commit efd4ed3
Show file tree
Hide file tree
Showing 5 changed files with 70 additions and 4 deletions.
50 changes: 50 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ resolver = "2"
[workspace.dependencies]
tokio = { version = "1.38.0", features = ["full"] }
axum = "0.7.5"
serde = { version = "1.0.204", features = ["derive"] }
serde = { version = "1.0.204", features = ["derive"] }
rand = { version = "0.8.5", features = ["small_rng"] }
3 changes: 2 additions & 1 deletion crates/chatbot/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ version = "0.1.0"
edition = "2021"

[dependencies]
tokio = { workspace = true }
tokio = { workspace = true }
rand = { workspace = true }
14 changes: 12 additions & 2 deletions crates/chatbot/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
use std::time::Duration;
use rand::{rngs::SmallRng, Rng, SeedableRng};
use std::{cell::RefCell, time::Duration};
use tokio::time::sleep;

thread_local! {
static RNG: RefCell<SmallRng> = RefCell::new(SmallRng::from_entropy());
}

/// Seeds the thread-local RNG used by [`gen_random_number`].
pub fn seed_rng(seed: u64) {
RNG.with(|rng| *rng.borrow_mut() = SmallRng::seed_from_u64(seed));
}

/// Generates a random `usize`.
///
/// Warning: may take a few seconds!
pub async fn gen_random_number() -> usize {
sleep(Duration::from_secs(2)).await;
4
RNG.with(|rng| rng.borrow_mut().gen())
}

/// Generates a list of possible responses given the current chat.
Expand Down
4 changes: 4 additions & 0 deletions crates/server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,7 @@ anyhow = "1.0.86"
axum = { workspace = true }
serde = { workspace = true }
tokio = { workspace = true }
chatbot = { path = "../chatbot" }

[dev-dependencies]
rand = { workspace = true }

0 comments on commit efd4ed3

Please sign in to comment.