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!(
38        "ket_error_message( error_code={}, buffer_size={}, msg={} )",
39        error_code,
40        buffer_size,
41        msg,
42    );
43
44    let msg = msg.as_bytes();
45    *write_size = msg.len();
46
47    if buffer_size >= *write_size {
48        let buffer = unsafe { std::slice::from_raw_parts_mut(buffer, buffer_size) };
49        buffer[..*write_size].copy_from_slice(msg);
50        0
51    } else {
52        1
53    }
54}
55
56/// Wraps the error handling logic for FFI functions.
57///
58/// This function is used to handle errors returned from FFI functions.
59/// It takes a `Result` as input, where the `Ok` variant indicates success and
60/// the `Err` variant represents an error. It returns the corresponding error
61/// code based on the success or error case.
62///
63/// # Arguments
64///
65/// * `error` - The `Result` representing the success or failure of an operation.
66///
67/// # Returns
68///
69/// The error code. If the operation succeeded, it returns the error code for
70/// success (`0`). If an error occurred, it returns the corresponding error code.
71pub(super) fn wrapper(error: Result<()>) -> i32 {
72    match error {
73        Ok(_) => KetError::Success.error_code(),
74        Err(error) => error.error_code(),
75    }
76}