Skip to content

Commit 7de190a

Browse files
committed
io::Error::downcast: avoid reallocation in case of failure
1 parent 6840234 commit 7de190a

File tree

3 files changed

+12
-24
lines changed

3 files changed

+12
-24
lines changed

library/std/src/io/error.rs

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -950,19 +950,19 @@ impl Error {
950950
where
951951
E: error::Error + Send + Sync + 'static,
952952
{
953-
match self.repr.into_data() {
954-
ErrorData::Custom(b) if b.error.is::<E>() => {
955-
let res = (*b).error.downcast::<E>();
956-
957-
// downcast is a really trivial and is marked as inline, so
958-
// it's likely be inlined here.
959-
//
960-
// And the compiler should be able to eliminate the branch
961-
// that produces `Err` here since b.error.is::<E>()
962-
// returns true.
963-
Ok(*res.unwrap())
953+
if let ErrorData::Custom(c) = self.repr.data()
954+
&& c.error.is::<E>()
955+
{
956+
if let ErrorData::Custom(b) = self.repr.into_data()
957+
&& let Ok(err) = b.error.downcast::<E>()
958+
{
959+
Ok(*err)
960+
} else {
961+
// Safety: We have just checked that the condition is true
962+
unsafe { crate::hint::unreachable_unchecked() }
964963
}
965-
repr_data => Err(Self { repr: Repr::new(repr_data) }),
964+
} else {
965+
Err(self)
966966
}
967967
}
968968

library/std/src/io/error/repr_bitpacked.rs

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -133,15 +133,6 @@ unsafe impl Send for Repr {}
133133
unsafe impl Sync for Repr {}
134134

135135
impl Repr {
136-
pub(super) fn new(dat: ErrorData<Box<Custom>>) -> Self {
137-
match dat {
138-
ErrorData::Os(code) => Self::new_os(code),
139-
ErrorData::Simple(kind) => Self::new_simple(kind),
140-
ErrorData::SimpleMessage(simple_message) => Self::new_simple_message(simple_message),
141-
ErrorData::Custom(b) => Self::new_custom(b),
142-
}
143-
}
144-
145136
pub(super) fn new_custom(b: Box<Custom>) -> Self {
146137
let p = Box::into_raw(b).cast::<u8>();
147138
// Should only be possible if an allocator handed out a pointer with

library/std/src/io/error/repr_unpacked.rs

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,6 @@ pub(super) struct Repr(Inner);
1010

1111
impl Repr {
1212
#[inline]
13-
pub(super) fn new(dat: ErrorData<Box<Custom>>) -> Self {
14-
Self(dat)
15-
}
1613
pub(super) fn new_custom(b: Box<Custom>) -> Self {
1714
Self(Inner::Custom(b))
1815
}

0 commit comments

Comments
 (0)