Skip to content

Commit bc45e47

Browse files
committed
Add std::os::unix::fs::DirEntryExt2::file_name_ref(&self) -> &OsStr
DirEntryExt2 is a new trait with the same purpose as DirEntryExt, but sealed
1 parent 5dc8789 commit bc45e47

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

library/std/src/os/unix/fs.rs

+38
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ use crate::path::Path;
99
use crate::sys;
1010
use crate::sys_common::{AsInner, AsInnerMut, FromInner};
1111
// Used for `File::read` on intra-doc links
12+
use crate::ffi::OsStr;
13+
use crate::sealed::Sealed;
1214
#[allow(unused_imports)]
1315
use io::{Read, Write};
1416

@@ -839,6 +841,42 @@ impl DirEntryExt for fs::DirEntry {
839841
}
840842
}
841843

844+
/// Sealed Unix-specific extension methods for [`fs::DirEntry`].
845+
#[unstable(feature = "dir_entry_ext2", issue = "85573")]
846+
pub trait DirEntryExt2: Sealed {
847+
/// Returns a reference to the underlying `OsStr` of this entry's filename.
848+
///
849+
/// # Examples
850+
///
851+
/// ```
852+
/// use std::os::unix::fs::DirEntryExt2;
853+
/// use std::{fs, io};
854+
///
855+
/// fn main() -> io::Result<()> {
856+
/// let mut entries = fs::read_dir(".")?.collect::<Result<Vec<_>, io::Error>>()?;
857+
/// entries.sort_unstable_by(|a, b| a.file_name_ref().cmp(b.file_name_ref()));
858+
///
859+
/// for p in entries {
860+
/// println!("{:?}", p);
861+
/// }
862+
///
863+
/// Ok(())
864+
/// }
865+
/// ```
866+
fn file_name_ref(&self) -> &OsStr;
867+
}
868+
869+
/// Allows extension traits within `std`.
870+
#[unstable(feature = "sealed", issue = "none")]
871+
impl Sealed for fs::DirEntry {}
872+
873+
#[unstable(feature = "dir_entry_ext2", issue = "85573")]
874+
impl DirEntryExt2 for fs::DirEntry {
875+
fn file_name_ref(&self) -> &OsStr {
876+
self.as_inner().file_name_os_str()
877+
}
878+
}
879+
842880
/// Creates a new symbolic link on the filesystem.
843881
///
844882
/// The `link` path will be a symbolic link pointing to the `original` path.

library/std/src/sys/unix/fs.rs

+4
Original file line numberDiff line numberDiff line change
@@ -647,6 +647,10 @@ impl DirEntry {
647647
fn name_bytes(&self) -> &[u8] {
648648
&*self.name
649649
}
650+
651+
pub fn file_name_os_str(&self) -> &OsStr {
652+
OsStr::from_bytes(self.name_bytes())
653+
}
650654
}
651655

652656
impl OpenOptions {

0 commit comments

Comments
 (0)