garnet/rust/lib.rs

84 lines
1.4 KiB
Rust
Raw Permalink Normal View History

#![allow(dead_code)]
2026-02-19 21:28:00 +00:00
use std::{
ffi::{CStr, c_char},
ops::Add,
};
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())
}
2026-02-19 11:11:23 +00:00
#[repr(C)]
#[derive(Debug)]
struct T {
a: bool,
b: u8,
}
2026-02-19 19:37:46 +00:00
2026-02-19 11:11:23 +00:00
#[unsafe(no_mangle)]
2026-02-19 11:15:38 +00:00
extern "C" fn hello_struct(t: T) -> () {
2026-02-19 11:11:23 +00:00
say_hello(&format!("{:?}", t))
}
#[repr(C)]
2026-02-19 11:11:23 +00:00
#[derive(Debug)]
enum Shape {
Circle { radius: f64 },
Rectangle { width: f64, height: f64 },
}
#[unsafe(no_mangle)]
2026-02-19 11:15:38 +00:00
extern "C" fn hello_shape(s: Shape) -> () {
2026-02-19 11:11:23 +00:00
say_hello(&format!("{:?}", s))
}
2026-02-19 15:26:27 +00:00
2026-02-19 15:56:55 +00:00
/// cbindgen:prefix=__attribute__((const))
2026-02-19 15:26:27 +00:00
#[unsafe(no_mangle)]
extern "C" fn add(a: i64, b: i64) -> i64 {
2026-02-19 15:26:27 +00:00
a + b
}
2026-02-19 20:44:04 +00:00
#[repr(C)]
2026-02-19 21:28:00 +00:00
enum BTree<A> {
Leaf {
value: A,
},
Fork {
left: Box<BTree<A>>,
right: Box<BTree<A>>,
},
2026-02-19 21:11:23 +00:00
}
2026-02-19 21:28:00 +00:00
impl<A> BTree<A>
where
A: Add<Output = A> + Copy,
{
fn sum(&self) -> A {
2026-02-19 21:11:23 +00:00
match self {
2026-02-19 21:11:58 +00:00
BTree::Leaf { value } => *value,
BTree::Fork { left, right } => left.sum() + right.sum(),
2026-02-19 21:11:23 +00:00
}
}
}
#[repr(C)]
2026-02-19 21:11:58 +00:00
enum BTreeC {
2026-02-19 20:44:04 +00:00
Leaf {
value: i64,
},
Fork {
2026-02-19 21:11:58 +00:00
left: *const BTreeC,
right: *const BTreeC,
2026-02-19 20:44:04 +00:00
},
}
#[unsafe(no_mangle)]
2026-02-19 21:11:58 +00:00
extern "C" fn sum_tree(t: BTreeC) -> i64 {
2026-02-19 21:28:00 +00:00
(unsafe { std::mem::transmute::<_, &BTree<i64>>(&t) }).sum()
2026-02-19 20:44:04 +00:00
}