Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Using Box::leak for a shared state
I'm building an HTTP server using Hyper, and I'm wondering if there are any concerns about using Box::leak for a shared state.
In Hyper's examples, an Arc is used to pass a shared state to the service_fn (see here).
However, since I can guarantee that the shared state will last for the entire application, I think passing around a static reference to the state would be possible (and more efficient).
I don't want to use a static variable because I want to be able to create multiple independent states for testing purposes.
This would be my adapted hyper example:
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let addr: SocketAddr = ([127, 0, 0, 1], 4000).into();
// Using Box::leak instead of Arc.
let counter: &'static AtomicUsize = Box::leak(Box::new(AtomicUsize::new(0)));
// let counter = Arc::new(AtomicUsize::new(0));
let listener = TcpListener::bind(addr).await?;
println!("Listening on http://{}", addr);
loop {
let (stream, _) = listener.accept().await?;
let io = TokioIo::new(stream);
let service = service_fn(move |_req| {
let count = counter.fetch_add(1, Ordering::AcqRel);
async move {
Ok::<_, Error>(Response::new(Full::new(Bytes::from(format!(
"Request #{}",
count
)))))
}
});
if let Err(err) = http1::Builder::new().serve_connection(io, service).await {
println!("Error serving connection: {:?}", err);
}
}
}
1 post - 1 participant
🏷️ Rust_feed