Skip to content

Commit f60155a

Browse files
committed
feat: allow const path creation
1 parent 69d25fc commit f60155a

File tree

3 files changed

+24
-5
lines changed

3 files changed

+24
-5
lines changed

library/std/src/ffi/os_str.rs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -629,8 +629,15 @@ impl OsStr {
629629
s.as_ref()
630630
}
631631

632+
/// Creates a new `OsStr` from a `str`.
632633
#[inline]
633-
fn from_inner(inner: &Slice) -> &OsStr {
634+
#[unstable(feature = "const_path", reason = "TBD", issue = "none")]
635+
pub const fn from_str(s: &str) -> &OsStr {
636+
Self::from_inner(Slice::from_str(s))
637+
}
638+
639+
#[inline]
640+
const fn from_inner(inner: &Slice) -> &OsStr {
634641
// SAFETY: OsStr is just a wrapper of Slice,
635642
// therefore converting &Slice to &OsStr is safe.
636643
unsafe { &*(inner as *const Slice as *const OsStr) }
@@ -1249,7 +1256,7 @@ impl AsRef<OsStr> for OsString {
12491256
impl AsRef<OsStr> for str {
12501257
#[inline]
12511258
fn as_ref(&self) -> &OsStr {
1252-
OsStr::from_inner(Slice::from_str(self))
1259+
OsStr::from_str(self)
12531260
}
12541261
}
12551262

library/std/src/path.rs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1948,7 +1948,19 @@ impl Path {
19481948
/// ```
19491949
#[stable(feature = "rust1", since = "1.0.0")]
19501950
pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1951-
unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
1951+
Self::from_os_str(s.as_ref())
1952+
}
1953+
1954+
/// Creates a new `Path` from an `OsStr`.
1955+
///
1956+
/// This is a cost-free conversion.
1957+
///
1958+
/// You should probably use the [`Path::new`] method instead,
1959+
/// however, this method supports const expressions
1960+
#[inline]
1961+
#[unstable(feature = "const_path", reason = "TBD", issue = "none")]
1962+
pub const fn from_os_str(s: &OsStr) -> &Path {
1963+
unsafe { &*(s as *const OsStr as *const Path) }
19521964
}
19531965

19541966
/// Yields the underlying [`OsStr`] slice.

library/std/src/sys/unix/os_str.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -186,12 +186,12 @@ impl Buf {
186186

187187
impl Slice {
188188
#[inline]
189-
fn from_u8_slice(s: &[u8]) -> &Slice {
189+
const fn from_u8_slice(s: &[u8]) -> &Slice {
190190
unsafe { mem::transmute(s) }
191191
}
192192

193193
#[inline]
194-
pub fn from_str(s: &str) -> &Slice {
194+
pub const fn from_str(s: &str) -> &Slice {
195195
Slice::from_u8_slice(s.as_bytes())
196196
}
197197

0 commit comments

Comments
 (0)