cargo_rhack/
error.rs

1use anyhow::{bail, Context, Result};
2
3use std::fmt::{self, Display, Formatter};
4use std::io;
5
6// Custom error type for early exit.
7#[derive(Debug)]
8pub struct SilentExit {
9    pub code: i32,
10}
11
12impl Display for SilentExit {
13    fn fmt(&self, _: &mut Formatter<'_>) -> fmt::Result {
14        Ok(())
15    }
16}
17
18pub trait WriteErrorHandler {
19    fn handle_err(self, device: &str) -> Result<()>;
20}
21
22impl WriteErrorHandler for io::Result<()> {
23    fn handle_err(self, device: &str) -> Result<()> {
24        match self {
25            Err(e) if e.kind() == io::ErrorKind::BrokenPipe => bail!(SilentExit { code: 0 }),
26            result => result.with_context(|| format!("could not write to {device}")),
27        }
28    }
29}