garnet/rust/lib.rs
2026-04-14 00:45:15 +01:00

111 lines
1.8 KiB
Rust

#![allow(dead_code)]
use std::{
ffi::{CStr, c_char},
ops::Add,
slice,
};
fn say_hello(name: &str) {
println!("Hello from Rust, {name}!");
}
#[unsafe(no_mangle)]
extern "C" fn hello(c: *const c_char) {
say_hello(unsafe { CStr::from_ptr(c) }.to_str().unwrap())
}
#[repr(C)]
#[derive(Debug)]
struct T {
a: bool,
b: u8,
}
#[unsafe(no_mangle)]
extern "C" fn hello_struct(t: &T) {
say_hello(&format!("{:?}", t))
}
#[repr(C)]
#[derive(Debug)]
enum E {
E1,
E2,
E3,
}
#[unsafe(no_mangle)]
extern "C" fn hello_enum(e: &E) {
say_hello(&format!("{:?}", e))
}
#[repr(C)]
#[derive(Debug)]
enum Shape {
Circle { radius: f64 },
Rectangle { width: f64, height: f64 },
}
#[unsafe(no_mangle)]
extern "C" fn hello_shape(s: &Shape) {
say_hello(&format!("{:?}", s))
}
/// cbindgen:prefix=__attribute__((const))
#[unsafe(no_mangle)]
extern "C" fn add(a: i64, b: i64) -> i64 {
a + b
}
#[repr(C)]
enum BTree<A> {
Leaf {
value: A,
},
Fork {
left: Box<BTree<A>>,
right: Box<BTree<A>>,
},
}
impl<A> BTree<A>
where
A: Add<Output = A> + Copy,
{
fn sum(&self) -> A {
match self {
BTree::Leaf { value } => *value,
BTree::Fork { left, right } => left.sum() + right.sum(),
}
}
}
#[repr(C)]
enum BTreeC {
Leaf {
value: i64,
},
Fork {
left: *const BTreeC,
right: *const BTreeC,
},
}
#[unsafe(no_mangle)]
extern "C" fn sum_tree(t: &BTreeC) -> i64 {
(unsafe { std::mem::transmute::<_, &BTree<i64>>(t) }).sum()
}
#[unsafe(no_mangle)]
extern "C" fn sum_slice(v: *const i64, s: usize) -> i64 {
unsafe { slice::from_raw_parts(v, s) }.iter().sum()
}
#[unsafe(no_mangle)]
extern "C" fn print_optional(x: Option<&i8>) -> () {
match x {
Some(x) => println!("{}", x / 2),
None => {}
}
}