1mod bindings {
2 #![allow(non_upper_case_globals)]
3 #![allow(non_camel_case_types)]
4 #![allow(non_snake_case)]
5 #![allow(improper_ctypes)]
6 #![allow(dead_code)]
7 #![allow(clippy::all)]
8 include!(env!("C_BINDINGS_FILE"));
9}
10
11use std::io;
12
13pub use bindings::*;
14use libc::{c_char, c_void};
15
16use crate::error::Error;
17
18macro_rules! define_extern_c_log {
19 ($level:ident, $name:ident) => {
20 unsafe extern "C" fn $name(message: *const c_char) {
21 log::log!(log::Level::$level, "{}", to_string(message));
22 }
23 };
24}
25
26define_extern_c_log!(Error, c_log_error);
27define_extern_c_log!(Warn, c_log_warn);
28define_extern_c_log!(Info, c_log_info);
29define_extern_c_log!(Debug, c_log_debug);
30define_extern_c_log!(Trace, c_log_trace);
31
32#[no_mangle]
33pub static PUFFIN: bindings::PUFFIN_BINDINGS = PUFFIN_BINDINGS {
34 error: Some(c_log_error),
35 warn: Some(c_log_warn),
36 info: Some(c_log_info),
37 debug: Some(c_log_debug),
38 trace: Some(c_log_trace),
39 make_result: Some(make_result),
40};
41
42pub unsafe fn to_string(ptr: *const c_char) -> String {
49 use std::ffi::CStr;
50
51 if ptr.is_null() {
52 return "".to_owned();
53 }
54
55 CStr::from_ptr(ptr).to_string_lossy().as_ref().to_owned()
56}
57
58unsafe extern "C" fn make_result(code: RESULT_CODE, description: *const c_char) -> *mut c_void {
59 let reason = to_string(description);
60
61 let result = Box::new(match code {
62 RESULT_CODE::RESULT_OK => Ok(reason),
63 RESULT_CODE::RESULT_IO_WOULD_BLOCK => Err(CError {
64 kind: CErrorKind::IOWouldBlock,
65 reason,
66 }),
67 _ => Err(CError {
68 kind: CErrorKind::Error,
69 reason,
70 }),
71 });
72
73 log::trace!("PUT error log: {:?}", &result);
74 Box::into_raw(result) as *mut _
75}
76
77#[derive(Debug, Clone)]
78pub struct CError {
79 pub kind: CErrorKind,
80 pub reason: String,
81}
82
83#[derive(Debug, Clone)]
84pub enum CErrorKind {
85 IOWouldBlock,
86 Error,
87 Fatal,
88}
89
90impl From<CError> for io::Error {
91 fn from(e: CError) -> io::Error {
92 io::Error::new(
93 match e.kind {
94 CErrorKind::IOWouldBlock => io::ErrorKind::WouldBlock,
95 _ => io::ErrorKind::Other,
96 },
97 e.reason,
98 )
99 }
100}
101
102impl From<CError> for Error {
103 fn from(e: CError) -> Error {
104 Error::Put(e.reason)
105 }
106}