Skip to main content

pixelscript/shared/
ffi.rs

1// Copyright 2026 Jordan Castro <jordan@grupojvm.com>
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
4//
5// http://www.apache.org/licenses/LICENSE-2.0
6//
7// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
8//
9/// Convert a borrowed C string (const char *) into a Rust &str.
10#[macro_export]
11macro_rules! borrow_string {
12    ($cstr:expr) => {{
13        if $cstr.is_null() {
14            ""
15        } else {
16            #[allow(unused_unsafe)]
17            unsafe {
18                let c_str = std::ffi::CStr::from_ptr($cstr);
19                c_str.to_str().unwrap_or("")
20            }
21        }
22    }};
23}
24
25/// Convert a owned C string (i.e. owned by us now.) into a Rust String.
26///
27/// The C memory will be freed automatically, and you get a nice clean String!
28#[macro_export]
29macro_rules! own_string {
30    ($cstr:expr) => {{
31        if $cstr.is_null() {
32            String::new()
33        } else {
34            #[allow(unused_unsafe)]
35            let owned_string = unsafe { std::ffi::CString::from_raw($cstr) };
36
37            owned_string
38                .into_string()
39                .unwrap_or_else(|_| String::from("Invalid UTF-8"))
40        }
41    }};
42}
43
44/// Create a raw string from &str.
45///
46/// Remember to FREE THIS!
47#[macro_export]
48macro_rules! create_raw_string {
49    ($rstr:expr) => {{ 
50        std::ffi::CString::new($rstr).unwrap().into_raw() }};
51}
52
53/// Free a raw sring
54#[macro_export]
55    macro_rules! free_raw_string {
56        ($rptr:expr) => {{
57            if !$rptr.is_null() {
58                let _ = std::ffi::CString::from_raw($rptr);
59            }
60        }};
61    }
62
63
64/// simple Borrow a Var.
65#[macro_export]
66macro_rules! borrow_var {
67    ($var:expr) => {{
68        unsafe{ pxs_Var::from_borrow($var) }   
69    }};
70}
71
72/// Own a Var.
73#[macro_export]
74macro_rules! own_var {
75    ($var:expr) => {{
76        pxs_Var::from_raw($var)    
77    }};
78}