@@ -753,6 +753,22 @@ impl Display for BorrowMutError {
753753 }
754754}
755755
756+ // This ensures the panicking code is outlined from `borrow_mut` for `RefCell`.
757+ #[ inline( never) ]
758+ #[ track_caller]
759+ #[ cold]
760+ fn panic_already_borrowed ( err : BorrowMutError ) -> ! {
761+ panic ! ( "already borrowed: {:?}" , err)
762+ }
763+
764+ // This ensures the panicking code is outlined from `borrow` for `RefCell`.
765+ #[ inline( never) ]
766+ #[ track_caller]
767+ #[ cold]
768+ fn panic_already_mutably_borrowed ( err : BorrowError ) -> ! {
769+ panic ! ( "already mutably borrowed: {:?}" , err)
770+ }
771+
756772// Positive values represent the number of `Ref` active. Negative values
757773// represent the number of `RefMut` active. Multiple `RefMut`s can only be
758774// active at a time if they refer to distinct, nonoverlapping components of a
@@ -934,7 +950,10 @@ impl<T: ?Sized> RefCell<T> {
934950 #[ inline]
935951 #[ track_caller]
936952 pub fn borrow ( & self ) -> Ref < ' _ , T > {
937- self . try_borrow ( ) . expect ( "already mutably borrowed" )
953+ match self . try_borrow ( ) {
954+ Ok ( b) => b,
955+ Err ( err) => panic_already_mutably_borrowed ( err) ,
956+ }
938957 }
939958
940959 /// Immutably borrows the wrapped value, returning an error if the value is currently mutably
@@ -1027,7 +1046,10 @@ impl<T: ?Sized> RefCell<T> {
10271046 #[ inline]
10281047 #[ track_caller]
10291048 pub fn borrow_mut ( & self ) -> RefMut < ' _ , T > {
1030- self . try_borrow_mut ( ) . expect ( "already borrowed" )
1049+ match self . try_borrow_mut ( ) {
1050+ Ok ( b) => b,
1051+ Err ( err) => panic_already_borrowed ( err) ,
1052+ }
10311053 }
10321054
10331055 /// Mutably borrows the wrapped value, returning an error if the value is currently borrowed.
0 commit comments