Skip to content

Commit dc7e073

Browse files
tormolThomas Bahn
authored andcommitted
Remove unsound trait impls
* impl From<&mut AsciiStr> for &mut [u8] * impl From<&mut AsciiStr> for &mut str They allow writing non-ASCII values to an AsciiStr which when read out as an AsciiChar will produce values outside the valid niche.
1 parent 828f954 commit dc7e073

File tree

1 file changed

+30
-20
lines changed

1 file changed

+30
-20
lines changed

src/ascii_str.rs

Lines changed: 30 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -38,13 +38,13 @@ impl AsciiStr {
3838
/// Converts `&self` to a `&str` slice.
3939
#[inline]
4040
pub fn as_str(&self) -> &str {
41-
From::from(self)
41+
unsafe { &*(self as *const AsciiStr as *const str) }
4242
}
4343

4444
/// Converts `&self` into a byte slice.
4545
#[inline]
4646
pub fn as_bytes(&self) -> &[u8] {
47-
From::from(self)
47+
unsafe { &*(self as *const AsciiStr as *const[u8]) }
4848
}
4949

5050
/// Returns the entire string as slice of `AsciiChar`s.
@@ -381,22 +381,32 @@ impl AsMut<AsciiStr> for [AsciiChar] {
381381
}
382382
}
383383

384-
macro_rules! impl_into {
384+
impl<'a> From<&'a AsciiStr> for &'a [AsciiChar] {
385+
#[inline]
386+
fn from(astr: &AsciiStr) -> &[AsciiChar] {
387+
&astr.slice
388+
}
389+
}
390+
impl<'a> From<&'a mut AsciiStr> for &'a mut [AsciiChar] {
391+
#[inline]
392+
fn from(astr: &mut AsciiStr) -> &mut [AsciiChar] {
393+
&mut astr.slice
394+
}
395+
}
396+
impl<'a> From<&'a AsciiStr> for &'a [u8] {
397+
#[inline]
398+
fn from(astr: &AsciiStr) -> &[u8] {
399+
astr.as_bytes()
400+
}
401+
}
402+
impl<'a> From<&'a AsciiStr> for &'a str {
403+
#[inline]
404+
fn from(astr: &AsciiStr) -> &str {
405+
astr.as_str()
406+
}
407+
}
408+
macro_rules! widen_box {
385409
($wider: ty) => {
386-
impl<'a> From<&'a AsciiStr> for &'a$wider {
387-
#[inline]
388-
fn from(slice: &AsciiStr) -> &$wider {
389-
let ptr = slice as *const AsciiStr as *const $wider;
390-
unsafe { &*ptr }
391-
}
392-
}
393-
impl<'a> From<&'a mut AsciiStr> for &'a mut $wider {
394-
#[inline]
395-
fn from(slice: &mut AsciiStr) -> &mut $wider {
396-
let ptr = slice as *mut AsciiStr as *mut $wider;
397-
unsafe { &mut *ptr }
398-
}
399-
}
400410
#[cfg(feature = "std")]
401411
impl From<Box<AsciiStr>> for Box<$wider> {
402412
#[inline]
@@ -407,9 +417,9 @@ macro_rules! impl_into {
407417
}
408418
}
409419
}
410-
impl_into! {[AsciiChar]}
411-
impl_into! {[u8]}
412-
impl_into! {str}
420+
widen_box! {[AsciiChar]}
421+
widen_box! {[u8]}
422+
widen_box! {str}
413423

414424
impl fmt::Display for AsciiStr {
415425
#[inline]

0 commit comments

Comments
 (0)