-
Notifications
You must be signed in to change notification settings - Fork 140
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create
utils.rs
in tests-integration
..to hold utility functions used internaly only.
- Loading branch information
Showing
2 changed files
with
35 additions
and
30 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
use once_cell::sync::Lazy; | ||
use std::{ | ||
collections::HashSet, | ||
net::{SocketAddr, TcpListener}, | ||
sync::Mutex, | ||
}; | ||
|
||
// prevents get_available_port from ever returning the same port twice | ||
static UNIQUE_PORTS: Lazy<Mutex<HashSet<u16>>> = Lazy::new(|| Mutex::new(HashSet::new())); | ||
|
||
pub fn get_available_address() -> SocketAddr { | ||
let port = get_available_port(); | ||
SocketAddr::from(([127, 0, 0, 1], port)) | ||
} | ||
|
||
fn get_available_port() -> u16 { | ||
let mut unique_ports = UNIQUE_PORTS.lock().unwrap(); | ||
|
||
loop { | ||
let port = TcpListener::bind("127.0.0.1:0") | ||
.unwrap() | ||
.local_addr() | ||
.unwrap() | ||
.port(); | ||
if !unique_ports.contains(&port) { | ||
unique_ports.insert(port); | ||
return port; | ||
} | ||
} | ||
} |