Description
Proposal
Problem statement
Currently there's:
- No way to get a
&mut OsString
(or&mut OsStr
) from&mut PathBuf
(only fromPathBuf
viainto_os_string
), and; - No way to get a
&mut OsStr
from&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
'spush
extendsself
by adding path components, and can even clear the underlying path whenpush
ing an absolute path.OsString
always appends as-is. - This makes it possible, for example, to gradually build a filename on an existing
&mut PathBuf
without having to do an extra allocation in anOsString
to 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 PathBuf
that 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_string
oras_mut_os_str
be markedunsafe
?- Currently there's no guarantee offered by
PathBuf
that would be broken by exposing the underlyingOsString
. So makingunsafe
is 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_string
oras_mut_os_str
seems 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.