use std::{
cell::RefCell,
fmt,
io::{self, IoSlice, Write},
rc::Rc,
};
#[derive(Debug)]
pub struct RcWriter<W: ?Sized> {
inner: Rc<RefCell<W>>,
}
impl<W: ?Sized> Clone for RcWriter<W> {
#[inline]
fn clone(&self) -> Self {
Self {
inner: self.inner.clone()
}
}
}
impl<W: ?Sized> From<Rc<RefCell<W>>> for RcWriter<W> {
#[inline]
fn from(writer: Rc<RefCell<W>>) -> Self {
Self::new(writer)
}
}
impl<W: ?Sized> RcWriter<W> {
#[inline]
pub const fn new(writer: Rc<RefCell<W>>) -> Self {
Self {
inner: writer
}
}
#[inline]
pub const fn get_ref(&self) -> &Rc<RefCell<W>> {
&self.inner
}
#[inline]
pub fn into_inner(self) -> Rc<RefCell<W>> {
self.inner
}
}
impl<W> RcWriter<W> {
#[inline]
pub fn try_into_writer(self) -> Option<W> {
Rc::into_inner(self.inner).map(RefCell::into_inner)
}
}
impl<W: Write + ?Sized> Write for RcWriter<W> {
#[inline]
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.inner.borrow_mut().write(buf)
}
#[inline]
fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
self.inner.borrow_mut().write_vectored(bufs)
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
self.inner.borrow_mut().flush()
}
#[inline]
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
self.inner.borrow_mut().write_all(buf)
}
#[inline]
fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
self.inner.borrow_mut().write_fmt(fmt)
}
}