diff options
| author | nsfisis <nsfisis@gmail.com> | 2026-06-14 17:18:44 +0900 |
|---|---|---|
| committer | nsfisis <nsfisis@gmail.com> | 2026-06-14 17:23:13 +0900 |
| commit | ae113f91fefff415898781272b892d670fcb46f4 (patch) | |
| tree | 5d433f1902c0834973b6e5816d10629ca4a5b675 /crates/shirabe-php-shim/src | |
| parent | e71e24b5b5cacb93aab3a62e809414fbe9c8a438 (diff) | |
| download | php-shirabe-ae113f91fefff415898781272b892d670fcb46f4.tar.gz php-shirabe-ae113f91fefff415898781272b892d670fcb46f4.tar.zst php-shirabe-ae113f91fefff415898781272b892d670fcb46f4.zip | |
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 <noreply@anthropic.com>
Diffstat (limited to 'crates/shirabe-php-shim/src')
| -rw-r--r-- | crates/shirabe-php-shim/src/lib.rs | 10 | ||||
| -rw-r--r-- | crates/shirabe-php-shim/src/random.rs | 32 |
2 files changed, 34 insertions, 8 deletions
diff --git a/crates/shirabe-php-shim/src/lib.rs b/crates/shirabe-php-shim/src/lib.rs index 2a6ecf6..c236727 100644 --- a/crates/shirabe-php-shim/src/lib.rs +++ b/crates/shirabe-php-shim/src/lib.rs @@ -1,6 +1,8 @@ mod preg; +mod random; pub use preg::*; +pub use random::*; use indexmap::IndexMap; @@ -1360,10 +1362,6 @@ pub fn filesize(_path: &str) -> Option<i64> { std::fs::metadata(_path).ok().map(|m| m.len() as i64) } -pub fn random_int(_min: i64, _max: i64) -> i64 { - todo!() -} - pub fn json_encode_ex<T: serde::Serialize + ?Sized>(_value: &T, _flags: i64) -> Option<String> { todo!() } @@ -1607,10 +1605,6 @@ pub fn bin2hex(_data: &[u8]) -> String { _data.iter().map(|b| format!("{:02x}", b)).collect() } -pub fn random_bytes(_length: usize) -> Vec<u8> { - todo!() -} - pub fn is_dir(_path: &str) -> bool { std::path::Path::new(_path).is_dir() } 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<T: RandomInt>(range: impl std::ops::RangeBounds<T>) -> T { + T::random_int(range) +} + +pub fn random_bytes(len: usize) -> Vec<u8> { + 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>) -> Self; +} + +macro_rules! impl_random_int { + ($($t:ident),* $(,)?) => { + $( + impl RandomInt for $t { + fn random_int(range: impl std::ops::RangeBounds<Self>) -> Self { + fastrand::$t(range) + } + } + )* + }; +} + +impl_random_int!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize); |
