alef_component_abi/
producer.rs1use crate::{AlefOwnedBuffer, AlefStatus, AlefTaskV1};
8use alloc::boxed::Box;
9use alloc::string::{String, ToString};
10use alloc::sync::Arc;
11use alloc::vec::Vec;
12use core::any::Any;
13use core::ffi::c_void;
14use core::fmt;
15use core::mem::ManuallyDrop;
16use core::sync::atomic::{AtomicBool, Ordering};
17
18#[repr(transparent)]
26pub struct SyncStatic<T>(T);
27
28unsafe impl<T> Sync for SyncStatic<T> {}
32
33impl<T> SyncStatic<T> {
34 #[must_use]
42 pub const unsafe fn new(value: T) -> Self {
43 Self(value)
44 }
45
46 #[must_use]
48 pub const fn get(&self) -> &T {
49 &self.0
50 }
51
52 #[must_use]
54 pub const fn as_ptr(&self) -> *const T {
55 &raw const self.0
56 }
57}
58
59pub unsafe extern "C" fn free_owned_buffer(_context: *mut c_void, ptr: *mut u8, len: usize, capacity: usize) {
66 if !ptr.is_null() {
67 drop(unsafe { Vec::from_raw_parts(ptr, len, capacity) });
70 }
71}
72
73#[must_use]
76pub fn owned_buffer(bytes: Vec<u8>) -> AlefOwnedBuffer {
77 let mut bytes = ManuallyDrop::new(bytes);
78 AlefOwnedBuffer {
79 ptr: bytes.as_mut_ptr(),
80 len: bytes.len(),
81 capacity: bytes.capacity(),
82 context: core::ptr::null_mut(),
83 free: Some(free_owned_buffer),
84 }
85}
86
87#[must_use]
89pub fn error_buffer(message: impl fmt::Display) -> AlefOwnedBuffer {
90 owned_buffer(message.to_string().into_bytes())
91}
92
93#[must_use]
105pub unsafe fn take_owned_bytes(buffer: AlefOwnedBuffer) -> Vec<u8> {
106 let bytes = if buffer.ptr.is_null() || buffer.len == 0 {
107 Vec::new()
108 } else {
109 unsafe { core::slice::from_raw_parts(buffer.ptr, buffer.len) }.to_vec()
111 };
112 if let Some(free) = buffer.free {
113 unsafe { free(buffer.context, buffer.ptr, buffer.len, buffer.capacity) };
115 }
116 bytes
117}
118
119#[must_use]
121pub fn panic_message(payload: &(dyn Any + Send)) -> String {
122 if let Some(message) = payload.downcast_ref::<&'static str>() {
123 String::from(*message)
124 } else if let Some(message) = payload.downcast_ref::<String>() {
125 message.clone()
126 } else {
127 String::from("non-string panic payload")
128 }
129}
130
131#[must_use]
137pub fn cancel_flag_task(cancelled: Arc<AtomicBool>) -> AlefTaskV1 {
138 AlefTaskV1 {
139 struct_size: core::mem::size_of::<AlefTaskV1>(),
140 context: Box::into_raw(Box::new(cancelled)).cast(),
141 start: None,
142 cancel: Some(cancel_flag),
143 drop: Some(drop_cancel_flag),
144 }
145}
146
147unsafe extern "C" fn cancel_flag(context: *mut c_void) -> AlefStatus {
151 if context.is_null() {
152 return AlefStatus::INVALID_ARGUMENT;
153 }
154 unsafe { &*context.cast::<Arc<AtomicBool>>() }.store(true, Ordering::Release);
157 AlefStatus::OK
158}
159
160unsafe extern "C" fn drop_cancel_flag(context: *mut c_void) {
164 if !context.is_null() {
165 drop(unsafe { Box::from_raw(context.cast::<Arc<AtomicBool>>()) });
168 }
169}
170
171#[macro_export]
177macro_rules! construct_component {
178 ($implementation:ty, $host:expr) => {{
179 #[allow(unused_imports, reason = "only one of the two traits applies to a given type")]
180 use $crate::{ConstructDefault as _, ConstructFromHost as _};
181 #[allow(clippy::needless_borrow, reason = "the borrow selects the `Default` fallback")]
182 let value: $implementation = (&$crate::Construct::<$implementation>::new()).construct($host);
183 value
184 }};
185}
186
187#[cfg(test)]
188mod tests {
189 use super::*;
190 use crate::{AlefComponentV1, AlefStr, FromHost, HostApi};
191
192 #[test]
193 fn owned_buffer_round_trips_through_take_owned_bytes() {
194 let buffer = owned_buffer(alloc::vec![1, 2, 3]);
195 assert!(buffer.free.is_some());
196 assert_eq!(unsafe { take_owned_bytes(buffer) }, [1, 2, 3]);
198 assert!(unsafe { take_owned_bytes(AlefOwnedBuffer::EMPTY) }.is_empty());
200 }
201
202 #[test]
203 fn error_buffer_holds_the_display_text() {
204 let buffer = error_buffer(format_args!("bad {}", 7));
205 assert_eq!(unsafe { take_owned_bytes(buffer) }, b"bad 7");
207 }
208
209 #[test]
210 fn free_owned_buffer_ignores_null() {
211 unsafe { free_owned_buffer(core::ptr::null_mut(), core::ptr::null_mut(), 0, 0) };
213 }
214
215 #[test]
216 fn panic_message_reads_str_and_string_payloads() {
217 let text: Box<dyn Any + Send> = Box::new("static");
218 assert_eq!(panic_message(&*text), "static");
219 let owned: Box<dyn Any + Send> = Box::new(String::from("owned"));
220 assert_eq!(panic_message(&*owned), "owned");
221 let other: Box<dyn Any + Send> = Box::new(7_u8);
222 assert_eq!(panic_message(&*other), "non-string panic payload");
223 }
224
225 #[test]
226 fn cancel_flag_task_sets_the_shared_flag_and_releases_its_reference() {
227 let cancelled = Arc::new(AtomicBool::new(false));
228 let task = cancel_flag_task(Arc::clone(&cancelled));
229 assert_eq!(Arc::strong_count(&cancelled), 2);
230 let cancel = task.cancel.expect("cancel callback");
231 let drop_task = task.drop.expect("drop callback");
232 assert_eq!(unsafe { cancel(task.context) }, AlefStatus::OK);
234 assert!(cancelled.load(Ordering::Acquire));
235 assert_eq!(unsafe { cancel(core::ptr::null_mut()) }, AlefStatus::INVALID_ARGUMENT);
237 unsafe { drop_task(task.context) };
239 assert_eq!(Arc::strong_count(&cancelled), 1);
240 }
241
242 const ID: &[u8] = b"demo";
243
244 static DESCRIPTOR: SyncStatic<AlefComponentV1> = unsafe {
246 SyncStatic::new(AlefComponentV1 {
247 struct_size: core::mem::size_of::<AlefComponentV1>(),
248 abi_major: 1,
249 abi_minor: 0,
250 component_id: AlefStr {
251 ptr: ID.as_ptr().cast(),
252 len: ID.len(),
253 },
254 component_version: AlefStr::EMPTY,
255 contract_hash: [0; 32],
256 feature_set_hash: [0; 32],
257 contract: core::ptr::null(),
258 contract_size: 0,
259 create: None,
260 destroy: None,
261 })
262 };
263
264 #[test]
265 fn sync_static_is_a_transparent_plain_static() {
266 assert_eq!(
267 core::mem::size_of::<SyncStatic<AlefComponentV1>>(),
268 core::mem::size_of::<AlefComponentV1>()
269 );
270 assert_eq!(DESCRIPTOR.as_ptr(), core::ptr::from_ref(DESCRIPTOR.get()));
271 assert_eq!(DESCRIPTOR.get().component_id.len, 4);
272 }
273
274 #[derive(Default)]
275 struct OnlyDefault(u8);
276
277 struct Configured(bool);
278
279 impl FromHost for Configured {
280 fn from_host(host: &HostApi) -> Self {
281 Self(host.has_log())
282 }
283 }
284
285 #[test]
286 fn construct_component_prefers_from_host_and_falls_back_to_default() {
287 let host = HostApi::detached();
288 let configured = construct_component!(Configured, &host);
289 assert!(!configured.0);
290 let fallback = construct_component!(OnlyDefault, &host);
291 assert_eq!(fallback.0, 0);
292 }
293}