Skip to content

Commit 2de2d86

Browse files
committed
feat(sys): reimplement ngx_random
1 parent 30acb01 commit 2de2d86

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

nginx-sys/src/lib.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,23 @@ pub fn ngx_set_socket_errno(err: ngx_err_t) {
146146
errno::set_errno(errno::Errno(err as _))
147147
}
148148

149+
/// Returns a non cryptograhpically-secure pseudo-random integer.
150+
#[inline]
151+
pub fn ngx_random() -> core::ffi::c_long {
152+
#[cfg(windows)]
153+
unsafe {
154+
// Emulate random() as Microsoft CRT does not provide it.
155+
// rand() should be thread-safe in the multi-threaded CRT we link to, but will not be seeded
156+
// outside of the main thread.
157+
let x: u32 = ((rand() as u32) << 16) ^ ((rand() as u32) << 8) ^ (rand() as u32);
158+
(0x7fffffff & x) as _
159+
}
160+
#[cfg(not(windows))]
161+
unsafe {
162+
random()
163+
}
164+
}
165+
149166
/// Add a key-value pair to an nginx table entry (`ngx_table_elt_t`) in the given nginx memory pool.
150167
///
151168
/// # Arguments

0 commit comments

Comments
 (0)