hanzi-sort 0.2.0

Sort Chinese text by pinyin or stroke count, with polyphonic overrides and terminal-friendly output
use std::fmt::{Display, Formatter};
use std::path::PathBuf;

pub type Result<T> = std::result::Result<T, HanziSortError>;

#[derive(Debug)]
pub enum HanziSortError {
    InvalidArgument(String),
    Io {
        context: String,
        source: std::io::Error,
    },
    OverrideParse {
        path: PathBuf,
        source: toml::de::Error,
    },
    InvalidOverride(String),
}

impl HanziSortError {
    pub fn io(context: impl Into<String>, source: std::io::Error) -> Self {
        Self::Io {
            context: context.into(),
            source,
        }
    }
}

impl Display for HanziSortError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidArgument(message) => write!(f, "{message}"),
            Self::Io { context, source } => write!(f, "{context}: {source}"),
            Self::OverrideParse { path, source } => {
                write!(
                    f,
                    "failed to parse override config {}: {source}",
                    path.display()
                )
            }
            Self::InvalidOverride(message) => write!(f, "{message}"),
        }
    }
}

impl std::error::Error for HanziSortError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io { source, .. } => Some(source),
            Self::OverrideParse { source, .. } => Some(source),
            Self::InvalidArgument(_) | Self::InvalidOverride(_) => None,
        }
    }
}