Skip to content

Commit 21c0dfc

Browse files
authored
Rollup merge of rust-lang#44770 - dtolnay:borrowed, r=sfackler
Less confusing placeholder when RefCell is exclusively borrowed Based on ExpHP's comment in [*RefCell.borrow_mut get strange result*](https://users.rust-lang.org/t/refcell-borrow-mut-get-strange-result/12994): > it would perhaps be nicer if it didn't put something that could be misinterpreted as a valid string value The previous Debug implementation would show: RefCell { value: "<borrowed>" } The new one is: RefCell { value: <borrowed> }
2 parents 8915683 + f9d92d2 commit 21c0dfc

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

src/libcore/fmt/mod.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1700,8 +1700,18 @@ impl<T: ?Sized + Debug> Debug for RefCell<T> {
17001700
.finish()
17011701
}
17021702
Err(_) => {
1703+
// The RefCell is mutably borrowed so we can't look at its value
1704+
// here. Show a placeholder instead.
1705+
struct BorrowedPlaceholder;
1706+
1707+
impl Debug for BorrowedPlaceholder {
1708+
fn fmt(&self, f: &mut Formatter) -> Result {
1709+
f.write_str("<borrowed>")
1710+
}
1711+
}
1712+
17031713
f.debug_struct("RefCell")
1704-
.field("value", &"<borrowed>")
1714+
.field("value", &BorrowedPlaceholder)
17051715
.finish()
17061716
}
17071717
}

src/test/run-pass/ifmt.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
#![allow(unused_features)]
1414
#![feature(box_syntax)]
1515

16+
use std::cell::RefCell;
1617
use std::fmt::{self, Write};
1718
use std::usize;
1819

@@ -240,6 +241,8 @@ pub fn main() {
240241
// test that trailing commas are acceptable
241242
format!("{}", "test",);
242243
format!("{foo}", foo="test",);
244+
245+
test_refcell();
243246
}
244247

245248
// Basic test to make sure that we can invoke the `write!` macro with an
@@ -319,3 +322,12 @@ fn test_once() {
319322
assert_eq!(format!("{0} {0} {0} {a} {a} {a}", foo(), a=foo()),
320323
"1 1 1 2 2 2".to_string());
321324
}
325+
326+
fn test_refcell() {
327+
let refcell = RefCell::new(5);
328+
assert_eq!(format!("{:?}", refcell), "RefCell { value: 5 }");
329+
let borrow = refcell.borrow_mut();
330+
assert_eq!(format!("{:?}", refcell), "RefCell { value: <borrowed> }");
331+
drop(borrow);
332+
assert_eq!(format!("{:?}", refcell), "RefCell { value: 5 }");
333+
}

0 commit comments

Comments
 (0)