Skip to main content

bestool_psql/repl/describe/
output.rs

1use std::sync::Arc;
2
3use tokio::{
4	fs::File,
5	io::{self, AsyncWriteExt},
6	sync::Mutex as TokioMutex,
7};
8
9pub(super) struct OutputWriter {
10	file: Option<Arc<TokioMutex<File>>>,
11}
12
13impl OutputWriter {
14	pub fn new(file: Option<Arc<TokioMutex<File>>>) -> Self {
15		Self { file }
16	}
17
18	pub async fn write(&self, msg: &str) {
19		if let Some(ref file_arc) = self.file {
20			let mut file = file_arc.lock().await;
21			let _ = file.write_all(msg.as_bytes()).await;
22			let _ = file.flush().await;
23		} else {
24			let mut stdout = io::stdout();
25			let _ = stdout.write_all(msg.as_bytes()).await;
26			let _ = stdout.flush().await;
27		}
28	}
29
30	pub async fn writeln(&self, msg: &str) {
31		self.write(&format!("{}\n", msg)).await;
32	}
33}
34
35#[macro_export]
36macro_rules! write_output {
37	($writer:expr, $($arg:tt)*) => {{
38		$writer.write(&format!($($arg)*)).await;
39	}};
40}
41
42#[macro_export]
43macro_rules! writeln_output {
44	($writer:expr, $($arg:tt)*) => {{
45		$writer.writeln(&format!($($arg)*)).await;
46	}};
47}