-
Notifications
You must be signed in to change notification settings - Fork 24
Description
Proposal
Problem statement
Currently there's:
- No way to get a
&mut OsString(or&mut OsStr) from&mut PathBuf(only fromPathBufviainto_os_string), and; - No way to get a
&mut OsStrfrom&mut Path.
This puts &mut OsString's push, and &mut OsStr's make_ascii_lowercase / make_ascii_uppercase, out of reach for &mut PathBuf and &mut Path.
Motivation, use-cases
The proposed API change makes it possible for &mut PathBuf / &mut OsStr to take advantage of the APIs available on &mut OsString and &mut OsStr:
&mut OsString'spush.- This is the most useful API this proposal enables.
PathBuf'spushextendsselfby adding path components, and can even clear the underlying path whenpushing an absolute path.OsStringalways appends as-is. - This makes it possible, for example, to gradually build a filename on an existing
&mut PathBufwithout having to do an extra allocation in anOsStringto then append/replace on the&mut PathBuf.
- This is the most useful API this proposal enables.
&mut OsString'sclear,reserve,try_reserve,reserve_exact,try_reserve_exact,shrink_to_fit,shrink_to.- Equivalent methods already exist on
&mut PathBufthat are passthroughs to thePathBuf's underlyingOsString. So these would be of limited usefulness.
- Equivalent methods already exist on
&mut OsStr'smake_ascii_lowercase/make_ascii_uppercase.
There is already precedent for exposing a type's inner store via as_mut_* methods. String has a as_mut_vec and as_bytes_mut (via Deref<Target = str>). These are marked unsafe on String because with them it is possible for the caller to break the type's "valid UTF-8" invariant. On PathBuf, the proposed as_mut_os_string and as_mut_os_str need not be marked unsafe because PathBuf doesn't make any guarantees that can be broken by OsString.
Solution sketches
impl PathBuf {
// ...
pub fn as_mut_os_string(&mut self) -> &mut OsString {
&mut self.inner
}
// ...
}
impl Path {
// ...
pub fn as_mut_os_str(&mut self) -> &mut OsStr {
&mut self.inner
}
// ...
}Links and related work
- Should the proposed
as_mut_os_stringoras_mut_os_strbe markedunsafe?- Currently there's no guarantee offered by
PathBufthat would be broken by exposing the underlyingOsString. So makingunsafeis unnecessary. However, this proposal would make it impossible to offer any guarantee in the future. Given the stability of the API though, the possibility of offering some guarantee that would be broken by exposing safeas_mut_os_stringoras_mut_os_strseems remote enough to not warrant the ergonomics loss of marking themunsafe.
- Currently there's no guarantee offered by
What happens now?
This issue is part of the libs-api team API change proposal process. Once this issue is filed the libs-api team will review open proposals in its weekly meeting. You should receive feedback within a week or two.