emacs_native_async/
lib.rs1use libc::{kill, pid_t, write, SIGUSR1};
2use parking_lot::Mutex;
3use std::{collections::HashMap, io, sync::atomic::AtomicI64};
4
5pub mod to_lisp;
6
7#[repr(C)]
8pub struct NotificationHandler {
9 pid: pid_t,
10 notify_fd: i32,
11 pending: Mutex<HashMap<i64, emacs::Result<to_lisp::ToLispConvert>>>,
12 id_gen: AtomicI64,
13}
14
15impl NotificationHandler {
16 pub fn new(fd: i32, pid: pid_t) -> NotificationHandler {
17 NotificationHandler {
18 pid,
19 notify_fd: fd,
20 pending: Mutex::new(HashMap::new()),
21 id_gen: AtomicI64::new(0),
22 }
23 }
24
25 pub fn submit<T: Into<to_lisp::ToLispConvert>>(
26 &self,
27 value: emacs::Result<T>,
28 id: i64,
29 ) -> anyhow::Result<()> {
30 self.pending.lock().insert(id, value.map(|v| v.into()));
31 let id = id.to_le_bytes();
32 let mut index: usize = 0;
33 while index != id.len() {
34 let written = unsafe {
35 write(
36 self.notify_fd,
37 id.as_ptr().add(index).cast(),
38 id.len() - index,
39 )
40 };
41 index += usize::try_from(if written == -1 {
42 Err(std::io::Error::last_os_error())
43 } else {
44 Ok(written)
45 }?)?;
46 }
47 Ok(())
48 }
49 pub fn register(&self) -> i64 {
50 self.id_gen
51 .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
52 }
53 pub fn retrieve(&self, id: i64) -> emacs::Result<to_lisp::ToLispConvert> {
54 self.pending
55 .lock()
56 .remove(&id)
57 .ok_or_else(|| anyhow::anyhow!("id not available"))?
58 }
59}
60
61impl Drop for NotificationHandler {
62 fn drop(&mut self) {
63 if -1 == unsafe { kill(self.pid, SIGUSR1) } {
64 eprintln!("error killing child: {}", io::Error::last_os_error())
65 }
66 }
67}