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
49
50
51
52
use std::{ffi::NulError, io, str::Utf8Error};
use thiserror::Error;

pub type BlkIdResult<T, E = BlkIdError> = std::result::Result<T, E>;

#[derive(Error, Debug)]
pub enum BlkIdError {
    #[error(transparent)]
    Utf8(#[from] Utf8Error),

    #[error(transparent)]
    Nul(#[from] NulError),

    #[error(transparent)]
    Io(#[from] io::Error),
}

pub(crate) trait RawResult: Copy {
    fn is_error(self) -> bool;
}

pub(crate) fn c_result<T: RawResult>(value: T) -> BlkIdResult<T> {
    if value.is_error() {
        Err(BlkIdError::Io(std::io::Error::last_os_error()))
    } else {
        Ok(value)
    }
}

impl RawResult for i32 {
    fn is_error(self) -> bool {
        self < 0
    }
}

impl RawResult for i64 {
    fn is_error(self) -> bool {
        self < 0
    }
}

impl<T> RawResult for *const T {
    fn is_error(self) -> bool {
        self.is_null()
    }
}

impl<T> RawResult for *mut T {
    fn is_error(self) -> bool {
        self.is_null()
    }
}