From b27ad7ea41aa6adebaf9dd5b4624b1463e6fe232 Mon Sep 17 00:00:00 2001 From: Jiahao XU Date: Wed, 1 Mar 2023 23:41:23 +1100 Subject: [PATCH] Improve `windows::Client::new` impl (#39) - Use `u128` for the random int in the name for named semaphore in `windows::Client::new` to minimize possibility of collision. - Format the int as hex in `windows::Client::new` to reduce size of the name for the named semaphore. - Replace `String` with `Box` in `windows::Client`. Signed-off-by: Jiahao XU --- src/windows.rs | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/src/windows.rs b/src/windows.rs index 6ec9a28..67846cf 100644 --- a/src/windows.rs +++ b/src/windows.rs @@ -35,7 +35,7 @@ const WAIT_OBJECT_1: u32 = WAIT_OBJECT_0 + 1; #[derive(Debug)] pub struct Client { sem: Handle, - name: String, + name: Box, } #[derive(Debug)] @@ -58,13 +58,20 @@ impl Client { // but don't try for too long. let prefix = "__rust_jobslot_semaphore_"; - let mut name = prefix.to_string(); + let mut name = String::with_capacity( + prefix.len() + + // 32B for the max size of u128 + 32 + + // 1B for the null byte + 1, + ); + name.push_str(prefix); for _ in 0..100 { - let mut bytes = [0; 4]; + let mut bytes = [0; 16]; getrandom(&mut bytes)?; - write!(&mut name, "{}\0", u32::from_ne_bytes(bytes)).unwrap(); + write!(&mut name, "{}\0", u128::from_ne_bytes(bytes)).unwrap(); let res = unsafe { Handle::new_or_err(CreateSemaphoreA( @@ -78,7 +85,10 @@ impl Client { match res { Ok(sem) => { name.pop(); // chop off the trailing nul - let client = Client { sem, name }; + let client = Client { + sem, + name: name.into_boxed_str(), + }; if create_limit != limit { client.acquire()?; } @@ -120,7 +130,7 @@ impl Client { ); Handle::new(sem).map(|sem| Client { sem, - name: s.to_string(), + name: s.into(), }) }