1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
use runng_sys::*;
use super::*;
use std::ptr;


pub trait Aio {
    fn aio(&self) -> &NngAio;
    fn aio_mut(&mut self) -> &mut NngAio;
}

pub struct NngAio {
    aio: *mut nng_aio,
    // This isn't strictly correct from an NNG perspective.  It may be associated with:
    // - nng_context: nng_ctx_open(.., socket); nng_ctx_send(ctx, aio);
    // - nng_aio: nng_send_aio(socket, aio);
    socket: NngSocket,
}

pub type AioCallbackArg = *mut ::std::os::raw::c_void;
pub type AioCallback = unsafe extern "C" fn(arg1: AioCallbackArg);

impl NngAio {
    pub fn new(socket: NngSocket) -> NngAio {
        NngAio {
            aio: ptr::null_mut(),
            socket,
            }
    }
    pub fn init(&mut self, callback: AioCallback, arg: AioCallbackArg) -> NngReturn {
        unsafe {
            let mut aio: *mut nng_aio = ptr::null_mut();
            //https://doc.rust-lang.org/stable/book/first-edition/ffi.html#callbacks-from-c-code-to-rust-functions
            let res = nng_aio_alloc(&mut aio, Some(callback), arg);
            self.aio = aio;
            NngFail::from_i32(res)
        }
    }
    pub unsafe fn nng_aio(&self) -> *mut nng_aio {
        if self.aio == ptr::null_mut() {
            panic!("NngAio::init() not called");
        }
        self.aio
    }
}

impl Drop for NngAio {
    fn drop(&mut self) {
        unsafe {
            debug!("NngAio.drop {:x}", self.aio as u64);
            if self.aio != ptr::null_mut() {
                nng_aio_free(self.aio);
            }
        }
    }
}

impl RawSocket for NngAio {
    fn socket(&self) -> &NngSocket {
        &self.socket
    }
}