use std::io::{self, Write};
use serde::Serialize;
use crate::error::{AppError, AppResult, ErrorDetail, InternalOp};
pub(crate) fn map_stdout_err(e: io::Error) -> AppError {
if e.kind() == io::ErrorKind::BrokenPipe {
AppError::broken_pipe()
} else {
AppError::of_with_source(
ErrorDetail::Internal {
op: InternalOp::StdoutWrite,
},
e,
)
}
}
pub(crate) fn write_json<Out: Write, T: Serialize>(stdout: &mut Out, v: &T) -> AppResult<()> {
let mut buf = Vec::with_capacity(256);
serde_json::to_writer(&mut buf, v).map_err(|e| {
AppError::of_with_source(
ErrorDetail::Internal {
op: InternalOp::JsonSerialize,
},
e,
)
})?;
buf.push(b'\n');
stdout.write_all(&buf).map_err(map_stdout_err)?;
let _ = stdout.flush();
Ok(())
}