Skip to content

Instantly share code, notes, and snippets.

@polyzium
Created September 28, 2024 18:03
Show Gist options
  • Save polyzium/9090bbea65d169ea250bd32eb80babea to your computer and use it in GitHub Desktop.
Save polyzium/9090bbea65d169ea250bd32eb80babea to your computer and use it in GitHub Desktop.
Rust cursed RPC
use std::sync::mpsc::{Receiver, Sender};
// pub trait CrossThreadExecutor {
// fn set_rx(&mut self, rx: Receiver<Box<dyn Fn(&mut Self)>>);
// }
// struct CteBridge<T: CrossThreadExecutor> {
pub struct CteBridge<T> {
pub tx: Sender<Box<dyn Fn(&T) + Send>>
}
impl<T> CteBridge<T> {
pub fn exec<F: Fn(&T) + Send + 'static>(&mut self, function: F) {
self.tx.send(Box::new(function)).unwrap()
}
}
// impl<T: CrossThreadExecutor> CteBridge<T> {
// pub fn exec(&self, function: impl Fn(T) + 'static) {
// self.tx.send(Box::new(function)).unwrap();
// }
// }
use std::{rc::Rc, sync::mpsc::Receiver};
// use crate::cte::CrossThreadExecutor;
pub struct Engine {
pub cte_rx_c: Rc<Receiver<Box<dyn Fn(&Self) + Send>>>
}
impl Engine {
pub fn callback(&mut self) {
// ...do whatever
// For CTE to work, the engine shall pull closures from the channel
let rx = self.cte_rx_c.clone();
for function in rx.try_iter() {
(*function)(self)
}
}
pub fn log(&self, stuff: &str) {
println!("{:?} {}", self.cte_rx_c, stuff);
}
}
// impl CrossThreadExecutor for Engine {
// fn set_rx(&mut self, rx: Receiver<Box<dyn Fn(&mut Self)>>) {
// self.cte_rx_c = Rc::new(rx)
// }
// }
use std::{process::exit, rc::Rc, sync::mpsc, thread::{self, sleep}, time::Duration};
use cte::CteBridge;
use engine::Engine;
mod cte;
mod engine;
fn main() {
let (tx, rx) = mpsc::channel::<Box<dyn Fn(&Engine) + Send>>();
let mut bridge: CteBridge<Engine> = CteBridge { tx };
thread::spawn(move || {
let mut engine = Engine { cte_rx_c: Rc::new(rx) };
loop {
engine.callback();
};
});
sleep(Duration::from_secs(1));
bridge.exec(|engine| {
engine.log("cursed rpc test");
});
sleep(Duration::from_secs(1));
bridge.exec(|engine| {
engine.log("cursed rpc test 2");
});
sleep(Duration::from_secs(1));
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment