From 7c723d2bfd3e8b8cf6fa289b822a254180601528 Mon Sep 17 00:00:00 2001 From: huntc Date: Wed, 14 Jul 2021 11:31:15 +1000 Subject: [PATCH] Removed UB code around the send future --- embassy/src/util/mpsc.rs | 32 +++++++++++++++----------------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/embassy/src/util/mpsc.rs b/embassy/src/util/mpsc.rs index 8d534dc4..f049b621 100644 --- a/embassy/src/util/mpsc.rs +++ b/embassy/src/util/mpsc.rs @@ -210,7 +210,7 @@ where pub async fn send(&self, message: T) -> Result<(), SendError> { SendFuture { sender: self.clone(), - message: UnsafeCell::new(message), + message: Some(message), } .await } @@ -266,7 +266,7 @@ where M: Mutex, { sender: Sender<'ch, M, T, N>, - message: UnsafeCell, + message: Option, } impl<'ch, M, T, const N: usize> Future for SendFuture<'ch, M, T, N> @@ -275,25 +275,23 @@ where { type Output = Result<(), SendError>; - fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { - match self - .sender - .channel - .get() - .try_send_with_context(unsafe { self.message.get().read() }, Some(cx)) - { - Ok(..) => Poll::Ready(Ok(())), - Err(TrySendError::Closed(m)) => Poll::Ready(Err(SendError(m))), - Err(TrySendError::Full(..)) => { - Poll::Pending - // Note we leave the existing UnsafeCell contents - they still - // contain the original message. We could create another UnsafeCell - // with the message of Full, but there's no real need. - } + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + match self.message.take() { + Some(m) => match self.sender.channel.get().try_send_with_context(m, Some(cx)) { + Ok(..) => Poll::Ready(Ok(())), + Err(TrySendError::Closed(m)) => Poll::Ready(Err(SendError(m))), + Err(TrySendError::Full(m)) => { + self.message.insert(m); + Poll::Pending + } + }, + None => panic!("Message cannot be None"), } } } +impl<'ch, M, T, const N: usize> Unpin for SendFuture<'ch, M, T, N> where M: Mutex {} + struct CloseFuture<'ch, M, T, const N: usize> where M: Mutex,