From ae113f91fefff415898781272b892d670fcb46f4 Mon Sep 17 00:00:00 2001 From: nsfisis Date: Sun, 14 Jun 2026 17:18:44 +0900 Subject: feat(php-shim): implement random_int/random_bytes with fastrand PHP's random_int/random_bytes are cryptographically secure, but Composer does not rely on that property, so a non-cryptographic PRNG suffices. Co-Authored-By: Claude Opus 4.8 --- crates/shirabe-php-shim/src/random.rs | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 crates/shirabe-php-shim/src/random.rs (limited to 'crates/shirabe-php-shim/src/random.rs') diff --git a/crates/shirabe-php-shim/src/random.rs b/crates/shirabe-php-shim/src/random.rs new file mode 100644 index 0000000..05f62bd --- /dev/null +++ b/crates/shirabe-php-shim/src/random.rs @@ -0,0 +1,32 @@ +//! PHP's `random_int()` and `random_bytes()` are cryptographically secure; +//! these are not. Composer does not rely on that property, so a +//! non-cryptographic PRNG is sufficient here. + +pub fn random_int(range: impl std::ops::RangeBounds) -> T { + T::random_int(range) +} + +pub fn random_bytes(len: usize) -> Vec { + let mut buf = vec![0u8; len]; + fastrand::fill(&mut buf); + buf +} + +/// Integral types for which [`random_int`] can generate a value. +pub trait RandomInt: Sized { + fn random_int(range: impl std::ops::RangeBounds) -> Self; +} + +macro_rules! impl_random_int { + ($($t:ident),* $(,)?) => { + $( + impl RandomInt for $t { + fn random_int(range: impl std::ops::RangeBounds) -> Self { + fastrand::$t(range) + } + } + )* + }; +} + +impl_random_int!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize); -- cgit v1.3.1