Skip to content

Commit

Permalink
Use pin projection and remove Unpin requirement
Browse files Browse the repository at this point in the history
  • Loading branch information
fwcd committed May 31, 2024
1 parent 75b214c commit aa4fd17
Showing 1 changed file with 9 additions and 9 deletions.
18 changes: 9 additions & 9 deletions lighthouse-client/src/utils/stream_guard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,23 @@ use pin_project::{pin_project, pinned_drop};

/// A stream wrapper that automatically runs a closure when dropped.
#[pin_project(PinnedDrop)]
pub struct StreamGuard<S, F> where S: Stream + Unpin, F: FnOnce() {
pub struct StreamGuard<S, F> where S: Stream, F: FnOnce() {
#[pin]
stream: S,
on_drop: Option<F>,
}

impl<S, F> StreamGuard<S, F> where S: Stream + Unpin, F: FnOnce() {
impl<S, F> StreamGuard<S, F> where S: Stream, F: FnOnce() {
pub fn new(stream: S, on_drop: F) -> Self {
Self { stream, on_drop: Some(on_drop) }
}
}

impl<S, F> Stream for StreamGuard<S, F> where S: Stream + Unpin, F: FnOnce() {
impl<S, F> Stream for StreamGuard<S, F> where S: Stream, F: FnOnce() {
type Item = S::Item;

fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Pin::new(&mut self.stream).poll_next(cx)
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.project().stream.poll_next(cx)
}

fn size_hint(&self) -> (usize, Option<usize>) {
Expand All @@ -30,17 +30,17 @@ impl<S, F> Stream for StreamGuard<S, F> where S: Stream + Unpin, F: FnOnce() {
}

#[pinned_drop]
impl<S, F> PinnedDrop for StreamGuard<S, F> where S: Stream + Unpin, F: FnOnce() {
impl<S, F> PinnedDrop for StreamGuard<S, F> where S: Stream, F: FnOnce() {
fn drop(mut self: Pin<&mut Self>) {
self.on_drop.take().expect("No on_drop function in StreamGuard, was drop called twice or constructed wrongly?")()
self.project().on_drop.take().expect("No on_drop function in StreamGuard, was drop called twice or constructed wrongly?")()
}
}

pub trait StreamExt: Stream + Sized + Unpin {
pub trait StreamExt: Stream + Sized {
fn guard<F>(self, on_drop: F) -> StreamGuard<Self, F> where F: FnOnce();
}

impl<S> StreamExt for S where S: Stream + Sized + Unpin {
impl<S> StreamExt for S where S: Stream + Sized {
fn guard<F>(self, on_drop: F) -> StreamGuard<Self, F> where F: FnOnce() {
StreamGuard::new(self, on_drop)
}
Expand Down

0 comments on commit aa4fd17

Please sign in to comment.