std::fs::DirEntry::file_name(&self) returns an owned
OsString, which is safely cross-platform. But on Unix (at least), this involves an unnecessary allocation, since the underlying
dirent C struct contains the filename, so we could just return a reference (which is part of the current Unix implementation of
I've implemented a variant that works the same as that, minus the call to
to_os_string(), and it works in trivial tests on my machines (x64 and arm64 Macs). I'm pretty new to Rust, though, so I might be missing something.
I'm unclear on how this would/could work on Windows, but even in the worst case, this new API could either be just part of the Unix extensions to
DirEntry (putting the responsibility on the caller to know when this "optimized" API is available), or the cross-platform façade of
DirEntry could have a new function that returns a
std::borrow::Cow<OsStr>, which on Unix would always be a borrow.
The most obvious usecase for this feature is sorting
DirEntrys (since the order is platform/filesystem-dependent), but any situation where an unnecessary allocation can be avoided is a win in my book.
I'd love to hear some thoughts on this. Like I said, I'm pretty new to Rust, so I may be missing something huge.
There was a previous conversation on this topic, but it trailed off a bit from the main point, I think: