nu_utils/fmt_handle.rs
1use std::{cell::RefCell, fmt, rc::Rc};
2
3/// A cloneable handle to a single-threaded [`fmt`] writer.
4///
5/// Clones of this handle write to the same underlying writer.
6/// This type uses interior mutability and is not thread-safe, i.e. it is not [Send] nor [Sync].
7///
8/// # Example
9///
10/// ```rust
11/// use std::fmt::Write;
12/// use nu_utils::FmtHandle;
13///
14/// let mut string = String::new();
15/// let mut a = FmtHandle::new(&mut string);
16/// let mut b = a.clone();
17/// a.write_str("abc").unwrap();
18/// b.write_str("def").unwrap();
19/// drop(a);
20/// drop(b);
21///
22/// assert_eq!(string, "abcdef");
23/// ```
24#[derive(Debug)]
25pub struct FmtHandle<W>(Rc<RefCell<W>>);
26
27impl<W> FmtHandle<W> {
28 pub fn new(writer: W) -> Self {
29 Self(Rc::new(RefCell::new(writer)))
30 }
31}
32
33impl<W: Default> FmtHandle<W> {
34 pub fn take(&self) -> W {
35 self.0.take()
36 }
37}
38
39impl<W> Clone for FmtHandle<W> {
40 fn clone(&self) -> Self {
41 Self(self.0.clone())
42 }
43}
44
45impl<W: fmt::Write> fmt::Write for FmtHandle<W> {
46 fn write_str(&mut self, s: &str) -> fmt::Result {
47 self.0.borrow_mut().write_str(s)
48 }
49}