cell/fmt/
mod.rs

1// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Modified work Copyright 2018-2019 Daniel Mueller (deso@posteo.net).
6//
7// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
8// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
9// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
10// option. This file may not be copied, modified, or distributed
11// except according to those terms.
12
13//! Utilities for formatting and printing strings.
14
15use std::fmt::Debug;
16use std::fmt::Formatter;
17use std::fmt::Result;
18use std::ops::Deref;
19
20use crate::cell::Ref;
21use crate::cell::RefCell;
22use crate::cell::RefMut;
23use crate::cell::RefVal;
24use crate::RefValMut;
25
26
27impl<T: ?Sized + Debug> Debug for RefCell<T> {
28    fn fmt(&self, f: &mut Formatter) -> Result {
29        match self.try_borrow() {
30            Ok(borrow) => {
31                f.debug_struct("RefCell")
32                    .field("value", &borrow)
33                    .finish()
34            }
35            Err(_) => {
36                // The RefCell is mutably borrowed so we can't look at its value
37                // here. Show a placeholder instead.
38                struct BorrowedPlaceholder;
39
40                impl Debug for BorrowedPlaceholder {
41                    fn fmt(&self, f: &mut Formatter) -> Result {
42                        f.write_str("<borrowed>")
43                    }
44                }
45
46                f.debug_struct("RefCell")
47                    .field("value", &BorrowedPlaceholder)
48                    .finish()
49            }
50        }
51    }
52}
53
54impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
55    fn fmt(&self, f: &mut Formatter) -> Result {
56        Debug::fmt(&**self, f)
57    }
58}
59
60impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
61    fn fmt(&self, f: &mut Formatter) -> Result {
62        Debug::fmt(&*(self.deref()), f)
63    }
64}
65
66impl<T: Sized + Debug> Debug for RefVal<'_, T> {
67    fn fmt(&self, f: &mut Formatter) -> Result {
68        Debug::fmt(&*(self.deref()), f)
69    }
70}
71
72impl<T: Sized + Debug> Debug for RefValMut<'_, T> {
73    fn fmt(&self, f: &mut Formatter) -> Result {
74        Debug::fmt(&*(self.deref()), f)
75    }
76}
77
78// If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
79// it's a lot easier than creating all of the rt::Piece structures here.