Skip to content

Commit 134695a

Browse files
authored
Merge pull request #252 from dtolnay/safedisplay
Remove unsafe code from AsDisplay
2 parents 8245799 + bb49bb3 commit 134695a

File tree

2 files changed

+21
-38
lines changed

2 files changed

+21
-38
lines changed

src/display.rs

Lines changed: 20 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,55 +1,38 @@
1-
use std::fmt::{self, Display};
2-
use std::path::{Path, PathBuf};
1+
use std::fmt::Display;
2+
use std::path::{self, Path, PathBuf};
33

44
#[doc(hidden)]
5-
pub trait AsDisplay {
6-
type Target: Display + ?Sized;
5+
pub trait AsDisplay<'a> {
6+
type Target: Display;
77

8-
fn as_display(&self) -> &Self::Target;
8+
fn as_display(&'a self) -> Self::Target;
99
}
1010

11-
impl<T: Display> AsDisplay for &T {
12-
type Target = T;
11+
impl<'a, T> AsDisplay<'a> for &T
12+
where
13+
T: Display + 'a,
14+
{
15+
type Target = &'a T;
1316

14-
fn as_display(&self) -> &Self::Target {
15-
self
17+
fn as_display(&'a self) -> Self::Target {
18+
*self
1619
}
1720
}
1821

19-
impl AsDisplay for Path {
20-
type Target = PathDisplay;
22+
impl<'a> AsDisplay<'a> for Path {
23+
type Target = path::Display<'a>;
2124

2225
#[inline]
23-
fn as_display(&self) -> &Self::Target {
24-
PathDisplay::new(self)
26+
fn as_display(&'a self) -> Self::Target {
27+
self.display()
2528
}
2629
}
2730

28-
impl AsDisplay for PathBuf {
29-
type Target = PathDisplay;
31+
impl<'a> AsDisplay<'a> for PathBuf {
32+
type Target = path::Display<'a>;
3033

3134
#[inline]
32-
fn as_display(&self) -> &Self::Target {
33-
PathDisplay::new(self.as_path())
34-
}
35-
}
36-
37-
#[doc(hidden)]
38-
#[repr(transparent)]
39-
pub struct PathDisplay(Path);
40-
41-
impl PathDisplay {
42-
#[inline]
43-
fn new(path: &Path) -> &Self {
44-
// SAFETY: PathDisplay is repr(transparent) so casting pointers between
45-
// it and its payload is safe.
46-
unsafe { &*(path as *const Path as *const Self) }
47-
}
48-
}
49-
50-
impl Display for PathDisplay {
51-
#[inline]
52-
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
53-
self.0.display().fmt(formatter)
35+
fn as_display(&'a self) -> Self::Target {
36+
self.display()
5437
}
5538
}

tests/ui/no-display.stderr

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ error[E0599]: the method `as_display` exists for reference `&NoDisplay`, but its
99
|
1010
= note: the following trait bounds were not satisfied:
1111
`NoDisplay: std::fmt::Display`
12-
which is required by `&NoDisplay: AsDisplay`
12+
which is required by `&NoDisplay: AsDisplay<'_>`
1313
note: the trait `std::fmt::Display` must be implemented
1414
--> $RUST/core/src/fmt/mod.rs
1515
|

0 commit comments

Comments
 (0)