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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
//! Standard error type for ocl.
//!

use std;
use num::FromPrimitive;
use ::Status;
use ::EmptyInfoResult;

/// `ocl::Error` result type.
pub type Result<T> = std::result::Result<T, self::Error>;

static SDK_DOCS_URL_PRE: &'static str = "https://www.khronos.org/registry/cl/sdk/1.2/docs/man/xhtml/";
static SDK_DOCS_URL_SUF: &'static str = ".html#errors";


fn fmt_status_desc(status: Status, fn_name: &'static str, fn_info: &str) -> String {
    let fn_info_string = if fn_info.is_empty() == false {
        format!("(\"{}\")", fn_info)
    } else {
        String::with_capacity(0)
    };

    format!("\n\n\
        ################################ OPENCL ERROR ############################### \
        \n\nError executing function: {}{}  \
        \n\nStatus error code: {:?} ({})  \
        \n\nPlease visit the following url for more information: \n\n{}{}{}  \n\n\
        ############################################################################# \n",
        fn_name, fn_info_string, status.clone(), status as i32,
        SDK_DOCS_URL_PRE, fn_name, SDK_DOCS_URL_SUF)
}


fn gen_status_error<S: Into<String>>(errcode: i32, fn_name: &'static str, fn_info: S) -> self::Error {
    let status = match Status::from_i32(errcode) {
        Some(s) => s,
        None => panic!("ocl_core::Error::err_status: Invalid error code: '{}'. Aborting.", errcode),
    };

    let fn_info = fn_info.into();
    let desc = fmt_status_desc(status.clone(), fn_name, &fn_info);
    let status_string = format!("{:?}", status);

    Error::Status {
            status: status,
            status_string: status_string,
            fn_name: fn_name,
            fn_info: fn_info,
            desc: desc
    }
}


/// An enum containing either a `String` or one of several other error types.
///
/// Implements the usual error traits.
///
/// ## Stability
///
/// The `String` variant may eventually be removed. Many more variants and
/// sub-types will be added as time goes on and things stabilize.
///
/// `Status` will eventually be changed internally to contain a sub-error type
/// unique to each function which generates it (yeah that'll be fun to
/// implement).
///
/// `UnspecifiedDimensions` may be moved into a sub-type.
///
/// For now, don't assume the existence of or check for any of the above.
///
pub enum Error {
    Void,
    Conversion(String),
    Status {
        status: Status, status_string: String, fn_name: &'static str, fn_info: String, desc: String
    },
    String(String),
    Nul(std::ffi::NulError),
    Io(std::io::Error),
    FromUtf8Error(std::string::FromUtf8Error),
    UnspecifiedDimensions,
    IntoStringError(std::ffi::IntoStringError),
    EmptyInfoResult(EmptyInfoResult),
}

impl self::Error {
    /// Returns a new `Error` with the description string:
    /// `desc`.
    ///
    /// ### Depricated
    ///
    /// Use `::from` instead.
    //
    #[deprecated(since="0.4.0", note="Use `::from` instead.")]
    pub fn new<S: Into<String>>(desc: S) -> Self {
        self::Error::String(desc.into())
    }

    /// Returns a new `Error::String` with the given description.
    #[deprecated(since="0.4.0", note="Use `::from` instead.")]
    pub fn string<S: Into<String>>(desc: S) -> Self {
        self::Error::String(desc.into())
    }

    /// Returns a new `ocl_core::Result::Err` containing an
    /// `ocl_core::Error::String` variant with the given description.
    ///
    /// ### Depricated
    ///
    /// Use `::err_string` or `Err("...".into())` instead.
    //
    #[deprecated(since="0.4.0", note="Use `Err(\"...\".into())` instead.")]
    pub fn err<T, S: Into<String>>(desc: S) -> self::Result<T> {
        Err(Error::String(desc.into()))
    }

    /// Returns a new `Err(ocl_core::Error::String(...))` variant with the
    /// given description.
    // #[deprecated(since="0.4.0", note="Use `Err(\"...\".into())` instead.")]
    pub fn err_string<T, S: Into<String>>(desc: S) -> self::Result<T> {
        Err(Error::String(desc.into()))
    }

    /// Returns a new `ocl::Result::Err` containing an `ocl::Error` with the
    /// given error code and description.
    #[inline(always)]
    pub fn eval_errcode<T, S: Into<String>>(errcode: i32, result: T, fn_name: &'static str, fn_info: S)
            -> self::Result<T>
    {
        if (Status::CL_SUCCESS as i32) == errcode {
            Ok(result)
        } else {
            Err(gen_status_error(errcode, fn_name, fn_info))
        }
    }

    /// Returns a new `ocl::Result::Err` containing an
    /// `ocl::Error::Conversion` variant with the given description.
    pub fn err_conversion<T, S: Into<String>>(desc: S) -> self::Result<T> {
        Err(Error::Conversion(desc.into()))
    }

    /// If this is a `String` variant, concatenate `txt` to the front of the
    /// contained string. Otherwise, do nothing at all.
    pub fn prepend<'s, S: AsRef<&'s str>>(&'s mut self, txt: S) {
        if let &mut Error::String(ref mut string) = self {
            string.reserve_exact(txt.as_ref().len());
            let old_string_copy = string.clone();
            string.clear();
            string.push_str(txt.as_ref());
            string.push_str(&old_string_copy);
        }
    }

    // /// Returns the error status const code name or nothing.
    // pub fn status_code(&self) -> String {
    //     match *self {
    //         Error::Status { ref status, .. } => format!("{:?}", status),
    //         _ => format!("{:?}", self),
    //     }
    // }

    /// Returns the error status code for `Status` variants.
    pub fn status(&self) -> Option<Status> {
        match *self {
            Error::Status { ref status, .. } => Some(status.clone()),
            _ => None,
        }
    }
}

impl std::fmt::Debug for self::Error {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        use std::error::Error;
        f.write_str(self.description())
    }
}

impl std::fmt::Display for self::Error {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        use std::error::Error;
        f.write_str(self.description())
    }
}

impl std::error::Error for self::Error {
    fn description(&self) -> &str {
        match *self {
            Error::Void => "OpenCL Error",
            Error::Conversion(ref desc) => desc.as_str(),
            Error::Nul(ref err) => err.description(),
            Error::Io(ref err) => err.description(),
            Error::FromUtf8Error(ref err) => err.description(),
            Error::IntoStringError(ref err) => err.description(),
            Error::Status { ref desc, .. } => desc.as_str(),
            Error::String(ref desc) => desc.as_str(),
            Error::UnspecifiedDimensions => "Cannot convert to a valid set of dimensions. \
                Please specify some dimensions.",
            Error::EmptyInfoResult(ref err) => err.description(),
            // _ => panic!("OclError::description()"),
        }
    }
}

impl From<()> for self::Error {
    fn from(_: ()) -> Self {
        self::Error::Void
    }
}

impl From<EmptyInfoResult> for self::Error {
    fn from(err: EmptyInfoResult) -> Self {
        self::Error::EmptyInfoResult(err)
    }
}

impl From<String> for self::Error {
    fn from(desc: String) -> Self {
        self::Error::String(desc)
    }
}

impl From<self::Error> for String {
    fn from(err: self::Error) -> String {
        // use std::error::Error;
        // err.description().to_string()
        format!("{}", err)
    }
}

impl<'a> From<&'a str> for self::Error {
    fn from(desc: &'a str) -> Self {
        self::Error::from(String::from(desc))
    }
}

impl From<std::ffi::NulError> for self::Error {
    fn from(err: std::ffi::NulError) -> Self {
        self::Error::Nul(err)
    }
}

impl From<std::io::Error> for self::Error {
    fn from(err: std::io::Error) -> Self {
        self::Error::Io(err)
    }
}

impl From<std::string::FromUtf8Error> for self::Error {
    fn from(err: std::string::FromUtf8Error) -> Self {
        self::Error::FromUtf8Error(err)
    }
}

impl From<std::ffi::IntoStringError> for self::Error {
    fn from(err: std::ffi::IntoStringError) -> Self {
        self::Error::IntoStringError(err)
    }
}

unsafe impl std::marker::Send for self::Error {}