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

Add std::os::unix::fs::DirEntryExt2::file_name_ref(&self) -> &OsStr #83581

Merged
merged 2 commits into from
Jul 5, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
38 changes: 38 additions & 0 deletions library/std/src/os/unix/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ use crate::path::Path;
use crate::sys;
use crate::sys_common::{AsInner, AsInnerMut, FromInner};
// Used for `File::read` on intra-doc links
use crate::ffi::OsStr;
use crate::sealed::Sealed;
#[allow(unused_imports)]
use io::{Read, Write};

Expand Down Expand Up @@ -839,6 +841,42 @@ impl DirEntryExt for fs::DirEntry {
}
}

/// Sealed Unix-specific extension methods for [`fs::DirEntry`].
#[unstable(feature = "dir_entry_ext2", issue = "85573")]
pub trait DirEntryExt2: Sealed {
/// Returns a reference to the underlying `OsStr` of this entry's filename.
///
/// # Examples
///
/// ```
/// use std::os::unix::fs::DirEntryExt2;
m-ou-se marked this conversation as resolved.
Show resolved Hide resolved
/// use std::{fs, io};
///
/// fn main() -> io::Result<()> {
/// let mut entries = fs::read_dir(".")?.collect::<Result<Vec<_>, io::Error>>()?;
/// entries.sort_unstable_by(|a, b| a.file_name_ref().cmp(b.file_name_ref()));
///
/// for p in entries {
/// println!("{:?}", p);
/// }
///
/// Ok(())
/// }
/// ```
fn file_name_ref(&self) -> &OsStr;
}

/// Allows extension traits within `std`.
#[unstable(feature = "sealed", issue = "none")]
impl Sealed for fs::DirEntry {}

#[unstable(feature = "dir_entry_ext2", issue = "85573")]
impl DirEntryExt2 for fs::DirEntry {
fn file_name_ref(&self) -> &OsStr {
self.as_inner().file_name_os_str()
}
}

/// Creates a new symbolic link on the filesystem.
///
/// The `link` path will be a symbolic link pointing to the `original` path.
Expand Down
4 changes: 4 additions & 0 deletions library/std/src/sys/unix/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -647,6 +647,10 @@ impl DirEntry {
fn name_bytes(&self) -> &[u8] {
&*self.name
}

pub fn file_name_os_str(&self) -> &OsStr {
OsStr::from_bytes(self.name_bytes())
}
}

impl OpenOptions {
Expand Down