use std::os::raw::c_void;
use crate::{YogBytesSink, YogStr};
pub type YogAddress = u32;
pub const NO_ADDRESS: YogAddress = u32::MAX;
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct YogBytes {
pub ptr: *const u8,
pub len: usize,
}
impl YogBytes {
pub const EMPTY: YogBytes = YogBytes {
ptr: std::ptr::null(),
len: 0,
};
pub fn new(bytes: &[u8]) -> YogBytes {
YogBytes {
ptr: bytes.as_ptr(),
len: bytes.len(),
}
}
pub unsafe fn as_slice<'a>(self) -> &'a [u8] {
if self.ptr.is_null() || self.len == 0 {
&[]
} else {
unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
}
}
}
#[repr(C)]
#[derive(Clone, Copy)]
pub struct YogReply {
pub sink: *mut c_void,
pub write: YogBytesSink,
}
impl YogReply {
pub fn to_vec(out: &mut Vec<u8>) -> Self {
Self {
sink: (out as *mut Vec<u8>).cast::<c_void>(),
write: append_to_vec,
}
}
pub fn discard() -> Self {
Self {
sink: std::ptr::null_mut(),
write: append_to_vec,
}
}
pub unsafe fn send(reply: *const Self, bytes: &[u8]) {
if bytes.is_empty() {
return;
}
if let Some(r) = unsafe { reply.as_ref() } {
unsafe { (r.write)(r.sink, bytes.as_ptr(), bytes.len()) };
}
}
}
unsafe extern "C" fn append_to_vec(sink: *mut c_void, data: *const u8, len: usize) {
if sink.is_null() || data.is_null() {
return;
}
unsafe { (*sink.cast::<Vec<u8>>()).extend_from_slice(std::slice::from_raw_parts(data, len)) }
}
pub mod priority {
pub const FIRST: i32 = i32::MAX;
pub const DEFAULT: i32 = 0;
pub const LATE: i32 = i32::MIN + 1;
pub const LAST: i32 = i32::MIN;
}
pub type YogStatus = u32;
pub mod status {
use crate::YogStatus;
pub const OK: YogStatus = 0;
pub const NO_HANDLER: YogStatus = 1;
pub const BAD_PAYLOAD: YogStatus = 2;
pub const FAILED: YogStatus = 3;
pub const CANCELLED: YogStatus = 4;
}
pub type YogHandlerFn =
unsafe extern "C" fn(ud: *mut c_void, payload: YogBytes, reply: *const YogReply) -> YogStatus;
#[repr(C)]
pub struct YogBus {
pub abi_version: u32,
pub size: u32,
pub ctx: *mut c_void,
pub resolve: unsafe extern "C" fn(ctx: *mut c_void, address: YogStr) -> YogAddress,
pub call: unsafe extern "C" fn(
ctx: *mut c_void,
to: YogAddress,
payload: YogBytes,
reply: *const YogReply,
) -> YogStatus,
pub emit: unsafe extern "C" fn(
ctx: *mut c_void,
event: YogAddress,
payload: YogBytes,
reply: *const YogReply,
) -> YogStatus,
pub on: unsafe extern "C" fn(
ctx: *mut c_void,
event: YogAddress,
priority: i32,
ud: *mut c_void,
handler: YogHandlerFn,
),
pub provide: unsafe extern "C" fn(
ctx: *mut c_void,
address: YogAddress,
ud: *mut c_void,
handler: YogHandlerFn,
) -> YogStatus,
pub provided: unsafe extern "C" fn(ctx: *mut c_void, address: YogAddress) -> bool,
pub atom: unsafe extern "C" fn(ctx: *mut c_void, name: YogStr) -> u32,
pub atom_name: unsafe extern "C" fn(ctx: *mut c_void, n: u32) -> YogStr,
}
unsafe impl Send for YogBus {}
unsafe impl Sync for YogBus {}