summaryrefslogtreecommitdiffstats
path: root/src/util.rs
blob: 4e996e8aabf8e488c45aeb09439c6d5eacad6a3b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
use std::{
	io::{Error, ErrorKind, Result},
	process::ExitStatus,
};

use nix::sys::wait;

pub trait ToIOResult<T> {
	fn to_io_result(self) -> Result<T>;
}

impl<T> ToIOResult<T> for nix::Result<T> {
	fn to_io_result(self) -> Result<T> {
		self.map_err(|error| match error {
			nix::Error::Sys(code) => Error::from_raw_os_error(code as i32),
			_ => Error::new(ErrorKind::Other, error),
		})
	}
}

pub trait Checkable {
	fn check(&self) -> Result<()>;
}

impl Checkable for ExitStatus {
	fn check(&self) -> Result<()> {
		if self.success() {
			Ok(())
		} else {
			Err(Error::new(
				ErrorKind::Other,
				format!("process exited with status {}", self),
			))
		}
	}
}

impl Checkable for wait::WaitStatus {
	fn check(&self) -> Result<()> {
		match self {
			wait::WaitStatus::Exited(_, 0) => Ok(()),
			_ => Err(Error::new(
				ErrorKind::Other,
				format!("process exited with status {:?}", self),
			)),
		}
	}
}