Skip to content

Commit

Permalink
refactor(endpoint): use array::from_fn instead of unsafe MaybeUninit
Browse files Browse the repository at this point in the history
With Rust 1.63.0 one can initialize a `std::array` via `std::array::from_fn`.

https://doc.rust-lang.org/std/array/fn.from_fn.html

Thus there is no need to start with an uninitialized array via `MaybeUninit`,
initialize it and then use `unsafe` to `assume_init`. Instead one can initialize
the array with the concrete elements right away.
  • Loading branch information
mxinden authored Apr 4, 2024
1 parent 1f8611d commit 65bddc9
Showing 1 changed file with 12 additions and 13 deletions.
25 changes: 12 additions & 13 deletions quinn/src/endpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use std::{
future::Future,
io,
io::IoSliceMut,
mem::MaybeUninit,
net::{SocketAddr, SocketAddrV6},
pin::Pin,
str,
Expand Down Expand Up @@ -432,20 +431,20 @@ pub(crate) struct Shared {
}

impl State {
fn drive_recv<'a>(&'a mut self, cx: &mut Context, now: Instant) -> Result<bool, io::Error> {
fn drive_recv(&mut self, cx: &mut Context, now: Instant) -> Result<bool, io::Error> {
self.recv_limiter.start_cycle();
let mut metas = [RecvMeta::default(); BATCH_SIZE];
let mut iovs = MaybeUninit::<[IoSliceMut<'a>; BATCH_SIZE]>::uninit();
self.recv_buf
.chunks_mut(self.recv_buf.len() / BATCH_SIZE)
.enumerate()
.for_each(|(i, buf)| unsafe {
iovs.as_mut_ptr()
.cast::<IoSliceMut>()
.add(i)
.write(IoSliceMut::<'a>::new(buf));
});
let mut iovs = unsafe { iovs.assume_init() };
let mut iovs: [IoSliceMut; BATCH_SIZE] = {
let mut bufs = self
.recv_buf
.chunks_mut(self.recv_buf.len() / BATCH_SIZE)
.map(IoSliceMut::new);

// expect() safe as self.recv_buf is chunked into BATCH_SIZE items
// and iovs will be of size BATCH_SIZE, thus from_fn is called
// exactly BATCH_SIZE times.
std::array::from_fn(|_| bufs.next().expect("BATCH_SIZE elements"))
};
loop {
match self.socket.poll_recv(cx, &mut iovs, &mut metas) {
Poll::Ready(Ok(msgs)) => {
Expand Down

0 comments on commit 65bddc9

Please sign in to comment.