Skip to main content

piper1_rs/
error.rs

1use std::{ffi::NulError, fmt, os::raw::c_int};
2
3/// A wrapper around [`Result`] with a [`PiperError`].
4pub type PiperResult<T> = Result<T, PiperError>;
5
6/// Global error type for all errors that Piper can return.
7#[derive(Debug)]
8pub enum PiperError {
9	/// A string passed to Piper included a internal `\0` (NUL) character.
10	InternalNullByte(NulError),
11	/// Piper returned a null pointer.
12	NullPointer,
13	/// Piper returned a generic error code.
14	GenericError,
15	/// Piper returned a unknown error code.
16	UnknownError(c_int),
17	/// IO error
18	Io(std::io::Error),
19}
20
21impl fmt::Display for PiperError {
22	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23		match self {
24			PiperError::InternalNullByte(e) => {
25				write!(f, "got a null byte in a string passed to piper: {}", e)
26			}
27			PiperError::NullPointer => f.write_str("piper returned a null pointer"),
28			PiperError::GenericError => f.write_str("piper returned an error"),
29			PiperError::UnknownError(e) => {
30				write!(f, "piper returned an unknown error code: {}", e)
31			}
32			PiperError::Io(e) => write!(f, "IO error: {}", e),
33		}
34	}
35}
36
37impl std::error::Error for PiperError {}
38
39impl From<NulError> for PiperError {
40	fn from(err: NulError) -> PiperError {
41		PiperError::InternalNullByte(err)
42	}
43}
44
45impl From<std::io::Error> for PiperError {
46	fn from(err: std::io::Error) -> PiperError {
47		PiperError::Io(err)
48	}
49}