Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fs: add into_std implementation for File #1773

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 21 additions & 0 deletions tokio/src/fs/file.rs
Expand Up @@ -436,6 +436,27 @@ impl File {
self.last_write_err = Some(e.kind());
}
}

/// Destructures the `tokio_fs::File` into a [`std::fs::File`][std].
///
/// [std]: https://doc.rust-lang.org/std/fs/struct.File.html
///
/// # Examples
///
/// ```no_run
/// use tokio::fs::File;
///
/// # async fn dox() -> std::io::Result<()> {
/// let file = File::open("foo.txt").await?;
/// let std: std::fs::File = file.into_std();
///
/// println!("{:?}", std);
/// # Ok(())
/// # }
/// ```
pub fn into_std(self) -> sys::File {
Arc::try_unwrap(self.std).unwrap()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah... yeah, this can panic if there is an in-flight job working with the file. I'm not sure what to do about this.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure if it would be an alternative for a method, but I was thinking about adding a TryFrom implementation like this:

use std::convert::TryFrom;

impl TryFrom<File> for sys::File {
    type Error = File;

    fn try_from(f: File) -> Result<Self, Self::Error> {
        let File {
            std,
            state,
            last_write_err,
        } = f;
        Arc::try_unwrap(std).map_err(|std| File {
            std,
            state,
            last_write_err,
        })
    }
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could do that, but the caller has no way to know if the file is at a point where it can succeed.

We could make it an async fn...

Copy link
Contributor Author

@afinch7 afinch7 Nov 17, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't really want to make this async, but we could just 'try_clone' the std file and return that.

let std = self.std.clone();
asyncify(move || std.try_clone())

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think a TryFrom might work...

}
}

impl AsyncRead for File {
Expand Down