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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use anyhow::Error;
use std::cell::RefCell;
use std::{ptr, slice};

thread_local! {
    static LAST_ERROR: RefCell<Option<Error>> = RefCell::new(None);
}

pub fn set_last_error(err: Error) {
    LAST_ERROR.with(|prev| {
        *prev.borrow_mut() = Some(err);
    });
}

pub fn take_last_error() -> Option<Error> {
    LAST_ERROR.with(|prev| prev.borrow_mut().take())
}

pub fn clear_last_error() {
    let _ = take_last_error();
}

/// Checks if there was an error before.
///
/// # Returns
///
/// `0` if there was no error, `1` if error had occured.
#[no_mangle]
pub extern "C" fn linicon_have_last_error() -> libc::c_int {
    LAST_ERROR.with(|prev| match *prev.borrow() {
        Some(_) => 1,
        None => 0,
    })
}

/// Gets error message length if any error had occurred.
///
/// # Returns
///
/// If there was no error before, returns `0`,
/// otherwise returns message length including trailing `\0`.
#[no_mangle]
pub extern "C" fn linicon_last_error_length() -> libc::c_int {
    // TODO: Support Windows UTF-16 strings
    LAST_ERROR.with(|prev| match *prev.borrow() {
        Some(ref err) => err.to_string().len() as libc::c_int + 1,
        None => 0,
    })
}

/// Fills passed buffer with an error message.
///
/// Buffer length can be get with [battery_last_error_length](fn.battery_last_error_length.html) function.
///
/// # Returns
///
/// Returns `-1` is passed buffer is `NULL` or too small for error message.
/// Returns `0` if there was no error previously.
///
/// In all other cases returns error message length.
#[no_mangle]
pub unsafe extern "C" fn linicon_last_error_message(
    buffer: *mut libc::c_char,
    length: libc::c_int,
) -> libc::c_int {
    if buffer.is_null() {
        return -1;
    }

    let last_error = match take_last_error() {
        Some(err) => err,
        None => return 0,
    };

    let error_message = last_error.to_string();

    let buffer = slice::from_raw_parts_mut(buffer as *mut u8, length as usize);

    if error_message.len() >= buffer.len() {
        return -1;
    }

    ptr::copy_nonoverlapping(
        error_message.as_ptr(),
        buffer.as_mut_ptr(),
        error_message.len(),
    );

    buffer[error_message.len()] = b'\0';

    error_message.len() as libc::c_int
}