ket/c_api/
error.rs

1// SPDX-FileCopyrightText: 2020 Evandro Chagas Ribeiro da Rosa <evandro@quantuloop.com>
2// SPDX-FileCopyrightText: 2020 Rafael de Santiago <r.santiago@ufsc.br>
3//
4// SPDX-License-Identifier: Apache-2.0
5
6//! Error handler for the C API.
7
8use log::trace;
9
10use crate::error::{KetError, Result};
11
12/// Retrieves the error message associated with an error code.
13///
14/// This function takes an error code as input and returns a pointer to
15/// the error message string. The `size` parameter is a mutable reference
16/// that will be updated with the length of the error message string.
17///
18/// # Arguments
19///
20/// * `error_code` - \[in\] The error code for which to retrieve the error message.
21/// * `buffer` - \[out\] A mutable pointer to store the error message string.
22/// * `buffer_size` - \[in\] The size of the buffer provided.
23/// * `write_size` - \[out\] A mutable reference to store the size of the error message.
24///
25/// # Safety
26///
27/// This function is marked as unsafe because it deals with raw pointers.
28#[no_mangle]
29pub unsafe extern "C" fn ket_error_message(
30    error_code: i32,
31    buffer: *mut u8,
32    buffer_size: usize,
33    write_size: &mut usize,
34) -> i32 {
35    let msg = unsafe { KetError::from_error_code(error_code) }.to_string();
36
37    trace!("ket_error_message( error_code={error_code}, buffer_size={buffer_size}, msg={msg} )",);
38
39    let msg = msg.as_bytes();
40    *write_size = msg.len();
41
42    if buffer_size >= *write_size {
43        let buffer = unsafe { std::slice::from_raw_parts_mut(buffer, buffer_size) };
44        buffer[..*write_size].copy_from_slice(msg);
45        0
46    } else {
47        1
48    }
49}
50
51/// Wraps the error handling logic for FFI functions.
52///
53/// This function is used to handle errors returned from FFI functions.
54/// It takes a `Result` as input, where the `Ok` variant indicates success and
55/// the `Err` variant represents an error. It returns the corresponding error
56/// code based on the success or error case.
57///
58/// # Arguments
59///
60/// * `error` - The `Result` representing the success or failure of an operation.
61///
62/// # Returns
63///
64/// The error code. If the operation succeeded, it returns the error code for
65/// success (`0`). If an error occurred, it returns the corresponding error code.
66pub(super) fn wrapper(error: Result<()>) -> i32 {
67    match error {
68        Ok(_) => KetError::Success.error_code(),
69        Err(error) => error.error_code(),
70    }
71}