]> git.lizzy.rs Git - rust.git/commitdiff
Add std::os::unix::fs::DirEntryExt2::file_name_ref(&self) -> &OsStr
authorAaron Rennow <arennow@outlook.com>
Sat, 27 Mar 2021 18:25:52 +0000 (14:25 -0400)
committerAaron Rennow <arennow@outlook.com>
Sat, 22 May 2021 01:53:03 +0000 (21:53 -0400)
DirEntryExt2 is a new trait with the same purpose as DirEntryExt,
but sealed

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

index 9cf51be2836fb5c8276f6ee976fc50e4d4eedb73..3939d3c4ca67a13808cc1ef0e5933d9ab34c4a6e 100644 (file)
@@ -9,6 +9,8 @@
 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};
 
@@ -839,6 +841,42 @@ fn ino(&self) -> u64 {
     }
 }
 
+/// 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;
+    /// 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.
index ef14865fbcd39dc174197f68b21a1cd26896fb2a..eae156bff4156c6906372e99eadf5d08b7f791dc 100644 (file)
@@ -647,6 +647,10 @@ fn name_bytes(&self) -> &[u8] {
     fn name_bytes(&self) -> &[u8] {
         &*self.name
     }
+
+    pub fn file_name_os_str(&self) -> &OsStr {
+        OsStr::from_bytes(self.name_bytes())
+    }
 }
 
 impl OpenOptions {