Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement DerefMut for PathBuf #105018

Merged
merged 1 commit into from
Dec 16, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions library/std/src/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1724,6 +1724,14 @@ impl ops::Deref for PathBuf {
}
}

#[stable(feature = "path_buf_deref_mut", since = "CURRENT_RUSTC_VERSION")]
impl ops::DerefMut for PathBuf {
#[inline]
fn deref_mut(&mut self) -> &mut Path {
Path::from_inner_mut(&mut self.inner)
}
}

#[stable(feature = "rust1", since = "1.0.0")]
impl Borrow<Path> for PathBuf {
#[inline]
Expand Down Expand Up @@ -1976,6 +1984,12 @@ impl Path {
unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
}

fn from_inner_mut(inner: &mut OsStr) -> &mut Path {
// SAFETY: Path is just a wrapper around OsStr,
// therefore converting &mut OsStr to &mut Path is safe.
unsafe { &mut *(inner as *mut OsStr as *mut Path) }
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't see a #[repr(transparent)] on the struct definition - I don't think this transmute is correct.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is correct for standard library code.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dtolnay Can you say more? What property of std lets it do this?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fact that if any future compiler change caused these types to be given different layout or disrupted the present behavior of this code in any other way, the same change would atomically adjust std to accommodate that. In other words the standard library is written to function under exactly one compiler version ever, whereas downstream code is required to be sound under all possible future compilers which are non-breaking evolutions of the current implicit "spec".

}

/// Yields the underlying [`OsStr`] slice.
///
/// # Examples
Expand Down