#[cfg(doc)]
use crate::IoRead;
use crate::{Fmt, FmtArguments, FmtError, FmtResult, FmtWrite};
#[cfg(doc)]
use crate::{IoError, IoWrite};
#[doc = crate::_tags!(io text)]
#[doc = crate::_doc_meta!{location("sys/io")}]
pub trait TextIn {
type Error;
fn read_text<'a>(&mut self, buf: &'a mut [u8]) -> Result<&'a str, Self::Error>;
}
#[doc = crate::_tags!(io text)]
#[doc = crate::_doc_meta!{location("sys/io")}]
pub trait TextOut {
type Error;
fn write_text(&mut self, text: &str) -> Result<(), Self::Error>;
fn write_line(&mut self, text: &str) -> Result<(), Self::Error> {
self.write_text(text)?;
self.write_text("\n")
}
fn write_char(&mut self, c: char) -> Result<(), Self::Error> {
let mut buf = [0u8; 4];
self.write_text(c.encode_utf8(&mut buf))
}
fn write_fmt(&mut self, args: FmtArguments<'_>) -> Result<(), Self::Error> {
struct Adapter<'a, T: ?Sized + TextOut> {
out: &'a mut T,
err: Option<T::Error>,
}
impl<T: ?Sized + TextOut> FmtWrite for Adapter<'_, T> {
fn write_str(&mut self, s: &str) -> FmtResult<()> {
match self.out.write_text(s) {
Ok(()) => Ok(()),
Err(e) => {
self.err = Some(e);
Err(FmtError)
}
}
}
}
let mut a = Adapter { out: self, err: None };
match Fmt::write(&mut a, args) {
Ok(()) => Ok(()),
Err(_) => Err(a.err.expect("TextOut::write_fmt adapter lost inner error")),
}
}
}
#[cfg(feature = "io")]
impl TextOut for crate::IoEmpty {
type Error = crate::IoError;
fn write_text(&mut self, text: &str) -> Result<(), Self::Error> {
let _ = text;
Ok(())
}
}
#[cfg(feature = "alloc")]
impl TextOut for crate::String {
type Error = crate::Infallible;
fn write_text(&mut self, text: &str) -> Result<(), Self::Error> {
self.push_str(text);
Ok(())
}
}
#[cfg(feature = "std")]
mod impl_std {
use crate::{IoError, IoWrite, TextOut};
use crate::{Stderr, Stdout};
use ::std::io::{StderrLock, StdoutLock};
impl TextOut for Stdout {
type Error = IoError;
fn write_text(&mut self, text: &str) -> Result<(), Self::Error> {
self.write_all(text.as_bytes())
}
}
impl TextOut for StdoutLock<'_> {
type Error = IoError;
fn write_text(&mut self, text: &str) -> Result<(), Self::Error> {
self.write_all(text.as_bytes())
}
}
impl TextOut for Stderr {
type Error = IoError;
fn write_text(&mut self, text: &str) -> Result<(), Self::Error> {
self.write_all(text.as_bytes())
}
}
impl TextOut for StderrLock<'_> {
type Error = IoError;
fn write_text(&mut self, text: &str) -> Result<(), Self::Error> {
self.write_all(text.as_bytes())
}
}
}