Created
October 18, 2019 00:26
-
-
Save rust-play/16803002422b2e8306247501663fa0b8 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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
use std::future::Future; | |
use std::pin::Pin; | |
use std::task::{Context, Poll}; | |
/// Poll a future once. | |
struct PollOnce<'a, F>(Option<&'a mut F>); | |
impl<'a, F: Future + Unpin> Future for PollOnce<'a, F> { | |
type Output = Option<F::Output>; | |
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { | |
if let Some(future) = self.0.take() { | |
if let Poll::Ready(value) = Pin::new(future).poll(cx) { | |
return Poll::Ready(Some(value)); | |
} | |
} | |
Poll::Ready(None) | |
} | |
} | |
/// An operation that borrows a slice and modifies it in another thread or via the OS. | |
async fn os_or_thread_operation(_buf: &mut [u8]) {} | |
pub async fn leak_memory() { | |
let mut buf = vec![0_u8; 10]; | |
// Create a future that borrows a buffer from this future's stack. | |
let mut future = Box::pin(os_or_thread_operation(&mut buf)); | |
// Start work: | |
PollOnce(Some(&mut future)).await; | |
// Never drop future: | |
std::mem::forget(future); | |
// Free the buffer that the `os_or_thread_operation` future is using: | |
drop(buf); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment