logo
  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
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
use crate::session::Session;

pub use crate::ffi::raw::{HapiResult, StatusType, StatusVerbosity};
use std::borrow::Cow;
use std::fmt::Formatter;

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

/// Error type returned by all APIs
pub struct HapiError {
    /// A specific error type.
    pub kind: Kind,
    /// Optional error message some APIs can set.
    pub context_message: Option<Cow<'static, str>>,
    /// Error message retrieved from the server. Server doesn't always return a message.
    pub server_message: Option<String>,
}

impl PartialEq for HapiError {
    fn eq(&self, other: &Self) -> bool {
        self.kind.eq(&other.kind)
    }
}

#[derive(Debug, PartialEq)]
#[non_exhaustive]
pub enum Kind {
    /// Error returned by ffi calls
    Hapi(HapiResult),
    /// CString contains null byte
    NullByte,
    /// String is not a valid utf-8
    Utf8Error,
    /// Any other error
    Other(String),
}

impl Kind {
    fn description(&self) -> &str {
        use HapiResult::*;

        match self {
            Kind::Hapi(Success) => "SUCCESS",
            Kind::Hapi(Failure) => "FAILURE",
            Kind::Hapi(AlreadyInitialized) => "ALREADY_INITIALIZED",
            Kind::Hapi(NotInitialized) => "NOT_INITIALIZED",
            Kind::Hapi(CantLoadfile) => "CANT_LOADFILE",
            Kind::Hapi(ParmSetFailed) => "PARM_SET_FAILED",
            Kind::Hapi(InvalidArgument) => "INVALID_ARGUMENT",
            Kind::Hapi(CantLoadGeo) => "CANT_LOAD_GEO",
            Kind::Hapi(CantGeneratePreset) => "CANT_GENERATE_PRESET",
            Kind::Hapi(CantLoadPreset) => "CANT_LOAD_PRESET",
            Kind::Hapi(AssetDefAlreadyLoaded) => "ASSET_DEF_ALREADY_LOADED",
            Kind::Hapi(NoLicenseFound) => "NO_LICENSE_FOUND",
            Kind::Hapi(DisallowedNcLicenseFound) => "DISALLOWED_NC_LICENSE_FOUND",
            Kind::Hapi(DisallowedNcAssetWithCLicense) => "DISALLOWED_NC_ASSET_WITH_C_LICENSE",
            Kind::Hapi(DisallowedNcAssetWithLcLicense) => "DISALLOWED_NC_ASSET_WITH_LC_LICENSE",
            Kind::Hapi(DisallowedLcAssetWithCLicense) => "DISALLOWED_LC_ASSET_WITH_C_LICENSE",
            Kind::Hapi(DisallowedHengineindieW3partyPlugin) => {
                "DISALLOWED_HENGINEINDIE_W_3PARTY_PLUGIN"
            }
            Kind::Hapi(AssetInvalid) => "ASSET_INVALID",
            Kind::Hapi(NodeInvalid) => "NODE_INVALID",
            Kind::Hapi(UserInterrupted) => "USER_INTERRUPTED",
            Kind::Hapi(InvalidSession) => "INVALID_SESSION",
            Kind::NullByte => "String contains null byte!",
            Kind::Utf8Error => "String is not UTF-8!",
            Kind::Other(s) => s,
        }
    }
}

impl From<HapiResult> for HapiError {
    fn from(r: HapiResult) -> Self {
        HapiError {
            kind: Kind::Hapi(r),
            context_message: None,
            server_message: None,
        }
    }
}

impl HapiError {
    pub(crate) fn new(
        kind: Kind,
        context_message: Option<Cow<'static, str>>,
        server_message: Option<String>,
    ) -> HapiError {
        HapiError {
            kind,
            context_message,
            server_message,
        }
    }
}

impl std::fmt::Display for HapiError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.kind {
            Kind::Hapi(_) => {
                write!(f, "[{}]: ", self.kind.description())?;
                if let Some(ref msg) = self.server_message {
                    write!(f, "[Engine Message]: {}", msg)?;
                }
                if let Some(ref msg) = self.context_message {
                    write!(f, "[Context Message]: {}", msg)?;
                }
                Ok(())
            }
            e => unreachable!("Unhandled error kind: {:?}", &e),
        }
    }
}

impl std::fmt::Debug for HapiError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self)
    }
}

impl From<std::ffi::NulError> for HapiError {
    fn from(_: std::ffi::NulError) -> Self {
        HapiError::new(Kind::NullByte, None, None)
    }
}

impl From<std::string::FromUtf8Error> for HapiError {
    fn from(_: std::string::FromUtf8Error) -> Self {
        HapiError::new(Kind::Utf8Error, None, None)
    }
}

impl std::error::Error for HapiError {}

impl HapiResult {
    fn _into_result<R: Default>(
        self,
        session: Option<&Session>,
        context_msg: Option<Cow<'static, str>>,
    ) -> Result<R> {
        match self {
            HapiResult::Success => Ok(R::default()),
            err => {
                let mut server_msg = None;
                if let Some(session) = session {
                    let err_msg = session
                        .get_status_string(StatusType::CallResult, StatusVerbosity::All)
                        .unwrap_or_else(|_| String::from("could not retrieve error message"));
                    server_msg.replace(err_msg);
                }
                Err(HapiError::new(Kind::Hapi(err), context_msg, server_msg))
            }
        }
    }

    #[inline]
    pub(crate) fn check_err<R: Default>(self, session: Option<&Session>) -> Result<R> {
        self._into_result(session, None)
    }

    #[inline]
    pub(crate) fn error_message<I: Into<Cow<'static, str>>, R: Default>(
        self,
        message: I,
    ) -> Result<R> {
        self._into_result(None, Some(message.into()))
    }
}