comfy_print_sync/
utils.rs

1use std::fmt::{Display, Formatter};
2use std::io::Write;
3
4#[derive(Debug, Copy, Clone)]
5pub enum OutputKind {
6	Stdout,
7	Stderr,
8}
9
10pub struct Message {
11	string: String,
12	output: OutputKind,
13}
14
15impl Message {
16	pub fn str(&self) -> &str {
17		return self.string.as_str();
18	}
19	
20	pub fn output_kind(&self) -> OutputKind {
21		return self.output;
22	}
23
24	pub fn standard(string: String) -> Self {
25		return Self {
26			string,
27			output: OutputKind::Stdout,
28		};
29	}
30	
31	pub fn error(string: String) -> Self {
32		return Self {
33			string,
34			output: OutputKind::Stderr,
35		};
36	}
37}
38
39impl Display for Message {
40	fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
41		return write!(f, "{}", self.string);
42	}
43}
44
45pub fn try_write(msg_str: &impl Display, output_kind: OutputKind) -> std::io::Result<()> {
46	match output_kind {
47		OutputKind::Stdout => {
48			let mut stdout = std::io::stdout().lock();
49			write!(stdout, "{}", msg_str)?;
50			stdout.flush()?;
51			Ok(())
52		}
53		OutputKind::Stderr => {
54			let mut stderr = std::io::stderr().lock();
55			write!(stderr, "{}", msg_str)?;
56			stderr.flush()?;
57			Ok(())
58		}
59	}
60}