avmnif-rs 0.4.1

Safe NIF toolkit for AtomVM written in Rust
Documentation
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
//! Resource management macros for AtomVM NIFs
//! 
//! Provides safe Rust wrappers around AtomVM's resource NIF API with trait abstraction

use crate::term::{NifError, NifResult};
use core::ffi::{c_void, c_char, c_int, c_uint};
use alloc::format;
use alloc::boxed::Box;

// Suppress naming warnings for FFI compatibility
#[allow(non_camel_case_types)]
pub type ERL_NIF_TERM = u64; // typedef term ERL_NIF_TERM (assuming 64-bit term)

pub type ErlNifEnv = c_void; // Opaque struct
pub type ErlNifResourceType = c_void; // Opaque struct  
pub type ErlNifPid = i32;
pub type ErlNifEvent = c_int;

/// Resource destructor callback type
pub type ErlNifResourceDtor = unsafe extern "C" fn(caller_env: *mut ErlNifEnv, obj: *mut c_void);

/// Select stop callback type  
pub type ErlNifResourceStop = unsafe extern "C" fn(
    caller_env: *mut ErlNifEnv, 
    obj: *mut c_void, 
    event: ErlNifEvent, 
    is_direct_call: c_int
);

/// Resource monitor callback type
pub type ErlNifResourceDown = unsafe extern "C" fn(
    caller_env: *mut ErlNifEnv, 
    obj: *mut c_void, 
    pid: *mut ErlNifPid, 
    mon: *mut ErlNifMonitor
);

/// Monitor type
#[repr(C)]
pub struct ErlNifMonitor {
    pub resource_type: *mut ErlNifResourceType,
    pub ref_ticks: u64,
}

/// Resource type initialization callbacks
#[repr(C)]
pub struct ErlNifResourceTypeInit {
    pub members: c_int,
    pub dtor: Option<ErlNifResourceDtor>,
    pub stop: Option<ErlNifResourceStop>, 
    pub down: Option<ErlNifResourceDown>,
}

/// Resource creation flags
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq)]
#[allow(non_camel_case_types)]
pub enum ErlNifResourceFlags {
    ERL_NIF_RT_CREATE = 1,
    // ERL_NIF_RT_TAKEOVER not supported yet
}

/// Select mode flags
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq)]
#[allow(non_camel_case_types)]
pub enum ErlNifSelectFlags {
    ERL_NIF_SELECT_READ = 1,
    ERL_NIF_SELECT_WRITE = 2,
    ERL_NIF_SELECT_STOP = 4,
}

// AtomVM Resource NIF FFI declarations (exact signatures from erl_nif.h)
extern "C" {
    /// Create or take over a resource type
    pub fn enif_init_resource_type(
        env: *mut ErlNifEnv,
        name: *const c_char,
        init: *const ErlNifResourceTypeInit,
        flags: ErlNifResourceFlags,
        tried: *mut ErlNifResourceFlags,
    ) -> *mut ErlNifResourceType;

    /// Allocate a new resource of the specified type and size
    pub fn enif_alloc_resource(
        resource_type: *mut ErlNifResourceType,
        size: c_uint,
    ) -> *mut c_void;

    /// Create an Erlang term from a resource pointer
    pub fn enif_make_resource(
        env: *mut ErlNifEnv,
        obj: *mut c_void,
    ) -> ERL_NIF_TERM;

    /// Extract a resource from an Erlang term
    pub fn enif_get_resource(
        env: *mut ErlNifEnv,
        t: ERL_NIF_TERM,
        resource_type: *mut ErlNifResourceType,
        objp: *mut *mut c_void,
    ) -> c_int;

    /// Increment resource reference count
    pub fn enif_keep_resource(obj: *mut c_void) -> c_int;

    /// Decrement resource reference count
    pub fn enif_release_resource(obj: *mut c_void) -> c_int;

    /// Select on file descriptors  
    pub fn enif_select(
        env: *mut ErlNifEnv,
        event: ErlNifEvent,
        mode: ErlNifSelectFlags,
        obj: *mut c_void,
        pid: *const ErlNifPid,
        reference: ERL_NIF_TERM,
    ) -> c_int;

    /// Monitor a process using a resource
    pub fn enif_monitor_process(
        env: *mut ErlNifEnv,
        obj: *mut c_void,
        target_pid: *const ErlNifPid,
        mon: *mut ErlNifMonitor,
    ) -> c_int;

    /// Remove a process monitor
    pub fn enif_demonitor_process(
        caller_env: *mut ErlNifEnv,
        obj: *mut c_void,
        mon: *const ErlNifMonitor,
    ) -> c_int;
}

/// Errors that can occur during resource operations
#[derive(Debug, PartialEq, Clone)]
pub enum ResourceError {
    /// Resource name is invalid (empty or too long)
    InvalidName,
    /// Memory allocation failed
    OutOfMemory,
    /// Invalid resource type pointer
    BadResourceType,
    /// Invalid argument provided
    BadArg,
    /// Resource type initialization failed
    InitializationFailed,
    /// Resource not found or wrong type
    ResourceNotFound,
    /// Operation not supported
    NotSupported,
}

impl From<ResourceError> for NifError {
    fn from(err: ResourceError) -> Self {
        match err {
            ResourceError::OutOfMemory => NifError::OutOfMemory,
            ResourceError::BadArg 
            | ResourceError::BadResourceType 
            | ResourceError::ResourceNotFound 
            | ResourceError::InvalidName 
            | ResourceError::InitializationFailed 
            | ResourceError::NotSupported => NifError::BadArg,
        }
    }
}

/// Trait abstraction for resource management operations
/// 
/// This allows for dependency injection and makes the resource system testable
/// while maintaining the same interface as the original FFI functions.
pub trait ResourceManager: Send + Sync {
    /// Initialize a new resource type
    fn init_resource_type(
        &mut self,
        env: *mut ErlNifEnv,
        name: &str,
        init: &ErlNifResourceTypeInit,
        flags: ErlNifResourceFlags,
    ) -> Result<*mut ErlNifResourceType, ResourceError>;

    /// Allocate memory for a new resource
    fn alloc_resource(
        &self,
        resource_type: *mut ErlNifResourceType,
        size: c_uint,
    ) -> Result<*mut c_void, ResourceError>;

    /// Create an Erlang term from a resource pointer
    fn make_resource(
        &self,
        env: *mut ErlNifEnv,
        obj: *mut c_void,
    ) -> Result<ERL_NIF_TERM, ResourceError>;

    /// Extract a resource pointer from an Erlang term
    fn get_resource(
        &self,
        env: *mut ErlNifEnv,
        term: ERL_NIF_TERM,
        resource_type: *mut ErlNifResourceType,
    ) -> Result<*mut c_void, ResourceError>;

    /// Increment resource reference count
    fn keep_resource(&self, obj: *mut c_void) -> Result<(), ResourceError>;

    /// Decrement resource reference count
    fn release_resource(&self, obj: *mut c_void) -> Result<(), ResourceError>;

    /// Select on file descriptors for I/O readiness
    fn select(
        &self,
        env: *mut ErlNifEnv,
        event: ErlNifEvent,
        mode: ErlNifSelectFlags,
        obj: *mut c_void,
        pid: *const ErlNifPid,
        reference: ERL_NIF_TERM,
    ) -> Result<(), ResourceError>;

    /// Monitor a process for termination
    fn monitor_process(
        &self,
        env: *mut ErlNifEnv,
        obj: *mut c_void,
        target_pid: *const ErlNifPid,
        mon: *mut ErlNifMonitor,
    ) -> Result<(), ResourceError>;

    /// Remove a process monitor
    fn demonitor_process(
        &self,
        env: *mut ErlNifEnv,
        obj: *mut c_void,
        mon: *const ErlNifMonitor,
    ) -> Result<(), ResourceError>;
}

/// Production implementation using real AtomVM FFI calls
#[derive(Debug, Default)]
pub struct AtomVMResourceManager;

impl AtomVMResourceManager {
    /// Create a new AtomVM resource manager
    pub fn new() -> Self {
        Self::default()
    }
}

impl ResourceManager for AtomVMResourceManager {
    fn init_resource_type(
        &mut self,
        env: *mut ErlNifEnv,
        name: &str,
        init: &ErlNifResourceTypeInit,
        flags: ErlNifResourceFlags,
    ) -> Result<*mut ErlNifResourceType, ResourceError> {
        // Validate input parameters
        if env.is_null() {
            return Err(ResourceError::BadArg);
        }
        if name.is_empty() || name.len() > 255 {
            return Err(ResourceError::InvalidName);
        }

        // Ensure name is null-terminated for C FFI
        let name_cstr = format!("{}\0", name);
        let mut tried_flags = flags;
        
        let resource_type = unsafe {
            enif_init_resource_type(
                env,
                name_cstr.as_ptr() as *const c_char,
                init,
                flags,
                &mut tried_flags,
            )
        };

        if resource_type.is_null() {
            Err(ResourceError::InitializationFailed)
        } else {
            Ok(resource_type)
        }
    }

    fn alloc_resource(
        &self,
        resource_type: *mut ErlNifResourceType,
        size: c_uint,
    ) -> Result<*mut c_void, ResourceError> {
        if resource_type.is_null() {
            return Err(ResourceError::BadResourceType);
        }
        if size == 0 {
            return Err(ResourceError::BadArg);
        }

        let ptr = unsafe { enif_alloc_resource(resource_type, size) };
        if ptr.is_null() {
            Err(ResourceError::OutOfMemory)
        } else {
            Ok(ptr)
        }
    }

    fn make_resource(
        &self,
        env: *mut ErlNifEnv,
        obj: *mut c_void,
    ) -> Result<ERL_NIF_TERM, ResourceError> {
        if env.is_null() || obj.is_null() {
            return Err(ResourceError::BadArg);
        }

        let term = unsafe { enif_make_resource(env, obj) };
        if term == 0 {
            Err(ResourceError::BadArg)
        } else {
            Ok(term)
        }
    }

    fn get_resource(
        &self,
        env: *mut ErlNifEnv,
        term: ERL_NIF_TERM,
        resource_type: *mut ErlNifResourceType,
    ) -> Result<*mut c_void, ResourceError> {
        if env.is_null() || resource_type.is_null() {
            return Err(ResourceError::BadArg);
        }

        let mut obj_ptr: *mut c_void = core::ptr::null_mut();
        let success = unsafe {
            enif_get_resource(env, term, resource_type, &mut obj_ptr)
        };

        if success != 0 && !obj_ptr.is_null() {
            Ok(obj_ptr)
        } else {
            Err(ResourceError::ResourceNotFound)
        }
    }

    fn keep_resource(&self, obj: *mut c_void) -> Result<(), ResourceError> {
        if obj.is_null() {
            return Err(ResourceError::BadArg);
        }

        let result = unsafe { enif_keep_resource(obj) };
        if result != 0 {
            Ok(())
        } else {
            Err(ResourceError::BadArg)
        }
    }

    fn release_resource(&self, obj: *mut c_void) -> Result<(), ResourceError> {
        if obj.is_null() {
            return Err(ResourceError::BadArg);
        }

        let result = unsafe { enif_release_resource(obj) };
        if result != 0 {
            Ok(())
        } else {
            Err(ResourceError::BadArg)
        }
    }

    fn select(
        &self,
        env: *mut ErlNifEnv,
        event: ErlNifEvent,
        mode: ErlNifSelectFlags,
        obj: *mut c_void,
        pid: *const ErlNifPid,
        reference: ERL_NIF_TERM,
    ) -> Result<(), ResourceError> {
        if env.is_null() || obj.is_null() || pid.is_null() {
            return Err(ResourceError::BadArg);
        }

        let result = unsafe {
            enif_select(env, event, mode, obj, pid, reference)
        };
        if result == 0 {
            Ok(())
        } else {
            Err(ResourceError::BadArg)
        }
    }

    fn monitor_process(
        &self,
        env: *mut ErlNifEnv,
        obj: *mut c_void,
        target_pid: *const ErlNifPid,
        mon: *mut ErlNifMonitor,
    ) -> Result<(), ResourceError> {
        if env.is_null() || obj.is_null() || target_pid.is_null() || mon.is_null() {
            return Err(ResourceError::BadArg);
        }

        let result = unsafe {
            enif_monitor_process(env, obj, target_pid, mon)
        };
        if result == 0 {
            Ok(())
        } else {
            Err(ResourceError::BadArg)
        }
    }

    fn demonitor_process(
        &self,
        env: *mut ErlNifEnv,
        obj: *mut c_void,
        mon: *const ErlNifMonitor,
    ) -> Result<(), ResourceError> {
        if env.is_null() || obj.is_null() || mon.is_null() {
            return Err(ResourceError::BadArg);
        }

        let result = unsafe {
            enif_demonitor_process(env, obj, mon)
        };
        if result == 0 {
            Ok(())
        } else {
            Err(ResourceError::BadArg)
        }
    }
}

/// Global resource manager instance
/// 
/// This can be swapped out for testing or different implementations
static mut RESOURCE_MANAGER: Option<Box<dyn ResourceManager>> = None;
static RESOURCE_MANAGER_INIT: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false);

/// Initialize the global resource manager
/// 
/// This should be called once during NIF initialization
pub fn init_resource_manager<T: ResourceManager + 'static>(manager: T) {
    unsafe {
        RESOURCE_MANAGER = Some(Box::new(manager));
        RESOURCE_MANAGER_INIT.store(true, core::sync::atomic::Ordering::SeqCst);
    }
}

/// Get a reference to the global resource manager
/// 
/// # Panics
/// Panics if the resource manager hasn't been initialized
pub fn get_resource_manager() -> &'static dyn ResourceManager {
    if !RESOURCE_MANAGER_INIT.load(core::sync::atomic::Ordering::SeqCst) {
        panic!("Resource manager not initialized. Call init_resource_manager() first.");
    }
    
    unsafe {
        RESOURCE_MANAGER.as_ref()
            .expect("Resource manager should be initialized")
            .as_ref()
    }
}

/// Get a mutable reference to the global resource manager
/// 
/// # Safety
/// This is unsafe because it provides mutable access to global state.
/// Caller must ensure no other threads are accessing the manager.
/// 
/// # Panics  
/// Panics if the resource manager hasn't been initialized
pub unsafe fn get_resource_manager_mut() -> &'static mut dyn ResourceManager {
    if !RESOURCE_MANAGER_INIT.load(core::sync::atomic::Ordering::SeqCst) {
        panic!("Resource manager not initialized. Call init_resource_manager() first.");
    }
    
    RESOURCE_MANAGER.as_mut()
        .expect("Resource manager should be initialized")
        .as_mut()
}

/// Helper for creating resource type initialization structs
pub const fn resource_type_init() -> ErlNifResourceTypeInit {
    ErlNifResourceTypeInit {
        members: 0,
        dtor: None,
        stop: None,
        down: None,
    }
}

/// Helper for creating resource type initialization with destructor
pub const fn resource_type_init_with_dtor(dtor: ErlNifResourceDtor) -> ErlNifResourceTypeInit {
    ErlNifResourceTypeInit {
        members: 1,
        dtor: Some(dtor),
        stop: None,
        down: None,
    }
}

/// Helper for creating resource type initialization with all callbacks
pub const fn resource_type_init_full(
    dtor: Option<ErlNifResourceDtor>,
    stop: Option<ErlNifResourceStop>,
    down: Option<ErlNifResourceDown>,
) -> ErlNifResourceTypeInit {
    let mut members = 0;
    if dtor.is_some() { members += 1; }
    if stop.is_some() { members += 1; }
    if down.is_some() { members += 1; }
    
    ErlNifResourceTypeInit {
        members,
        dtor,
        stop,
        down,
    }
}

/// Convenience functions that use the global resource manager or fallback to direct FFI
/// Manually increment resource reference count
pub fn keep_resource(resource: *mut c_void) -> NifResult<()> {
    if RESOURCE_MANAGER_INIT.load(core::sync::atomic::Ordering::SeqCst) {
        let manager = get_resource_manager();
        manager.keep_resource(resource).map_err(|e| e.into())
    } else {
        // Fallback to direct FFI call if no manager is initialized
        let result = unsafe { enif_keep_resource(resource) };
        if result != 0 {
            Ok(())
        } else {
            Err(NifError::BadArg)
        }
    }
}

/// Manually decrement resource reference count
pub fn release_resource(resource: *mut c_void) -> NifResult<()> {
    if RESOURCE_MANAGER_INIT.load(core::sync::atomic::Ordering::SeqCst) {
        let manager = get_resource_manager();
        manager.release_resource(resource).map_err(|e| e.into())
    } else {
        // Fallback to direct FFI call if no manager is initialized
        let result = unsafe { enif_release_resource(resource) };
        if result != 0 {
            Ok(())
        } else {
            Err(NifError::BadArg)
        }
    }
}

/// Register a new resource type with AtomVM
/// 
/// # Usage
/// ```rust,ignore
/// use avmnif_rs::resource_type;
/// 
/// resource_type!(DISPLAY_TYPE, DisplayContext, display_destructor);
/// ```
#[macro_export]
macro_rules! resource_type {
    ($resource_name:ident, $rust_type:ty, $destructor_fn:ident) => {
        // Create global static to hold the resource type pointer
        static mut $resource_name: *mut $crate::resource::ErlNifResourceType = core::ptr::null_mut();
        
        // Create a module init function that registers this resource type
        paste::paste! {
            #[no_mangle]
            pub extern "C" fn [<init_ $resource_name:lower>](env: *mut $crate::resource::ErlNifEnv) -> bool {
                let resource_name_cstr = concat!(stringify!($resource_name), "\0");
                let init_callbacks = $crate::resource::resource_type_init_with_dtor($destructor_fn);
                let mut tried_flags = $crate::resource::ErlNifResourceFlags::ERL_NIF_RT_CREATE;
                
                unsafe {
                    $resource_name = $crate::resource::enif_init_resource_type(
                        env,
                        resource_name_cstr.as_ptr() as *const core::ffi::c_char,
                        &init_callbacks,
                        $crate::resource::ErlNifResourceFlags::ERL_NIF_RT_CREATE,
                        &mut tried_flags,
                    );
                    
                    !$resource_name.is_null()
                }
            }
            
            // Provide a getter function for the resource type
            #[no_mangle]
            pub extern "C" fn [<get_ $resource_name:lower>]() -> *mut $crate::resource::ErlNifResourceType {
                unsafe { $resource_name }
            }
        }
    };
    
    // Version without destructor
    ($resource_name:ident, $rust_type:ty) => {
        // Create global static to hold the resource type pointer
        static mut $resource_name: *mut $crate::resource::ErlNifResourceType = core::ptr::null_mut();
        
        paste::paste! {
            #[no_mangle]
            pub extern "C" fn [<init_ $resource_name:lower>](env: *mut $crate::resource::ErlNifEnv) -> bool {
                let resource_name_cstr = concat!(stringify!($resource_name), "\0");
                let init_callbacks = $crate::resource::resource_type_init();
                let mut tried_flags = $crate::resource::ErlNifResourceFlags::ERL_NIF_RT_CREATE;
                
                unsafe {
                    $resource_name = $crate::resource::enif_init_resource_type(
                        env,
                        resource_name_cstr.as_ptr() as *const core::ffi::c_char,
                        &init_callbacks,
                        $crate::resource::ErlNifResourceFlags::ERL_NIF_RT_CREATE,
                        &mut tried_flags,
                    );
                    
                    !$resource_name.is_null()
                }
            }
            
            #[no_mangle]
            pub extern "C" fn [<get_ $resource_name:lower>]() -> *mut $crate::resource::ErlNifResourceType {
                unsafe { $resource_name }
            }
        }
    };
}

/// Create a new resource instance
/// 
/// # Usage
/// ```rust,ignore
/// use avmnif_rs::create_resource;
/// 
/// let display_ptr = create_resource!(display_type, DisplayContext {
///     width: 240,
///     height: 320,
///     initialized: true,
/// })?;
/// ```
#[macro_export]
macro_rules! create_resource {
    ($type_var:ident, $data:expr) => {{
        let data = $data;
        let size = core::mem::size_of_val(&data) as core::ffi::c_uint;
        let ptr = unsafe {
            paste::paste! {
                extern "C" {
                    fn [<get_ $type_var:lower>]() -> *mut $crate::resource::ErlNifResourceType;
                }
                let resource_type = [<get_ $type_var:lower>]();
                $crate::resource::enif_alloc_resource(resource_type, size)
            }
        };
        if ptr.is_null() {
            Err($crate::term::NifError::OutOfMemory)
        } else {
            // Write the data to the allocated resource
            unsafe {
                core::ptr::write(ptr as *mut _, data);
            }
            Ok(ptr)
        }
    }};
}

/// Extract a resource from an Erlang term
/// 
/// # Usage
/// ```rust,ignore
/// use avmnif_rs::get_resource;
/// 
/// let display = get_resource!(env, args[0], display_type)?;
/// display.width = 320;
/// ```
#[macro_export]
macro_rules! get_resource {
    ($env:expr, $term:expr, $type_var:ident) => {{
        let mut ptr: *mut core::ffi::c_void = core::ptr::null_mut();
        let success = unsafe {
            paste::paste! {
                extern "C" {
                    fn [<get_ $type_var:lower>]() -> *mut $crate::resource::ErlNifResourceType;
                }
                let resource_type = [<get_ $type_var:lower>]();
                $crate::resource::enif_get_resource(
                    $env.as_c_ptr(),
                    $term.as_raw(),
                    resource_type,
                    &mut ptr as *mut *mut core::ffi::c_void,
                )
            }
        };
        if success != 0 && !ptr.is_null() {
            // SAFETY: Resource type system ensures this cast is valid
            Ok(unsafe { &mut *(ptr as *mut _) })
        } else {
            Err($crate::term::NifError::BadArg)
        }
    }};
}

/// Convert a resource pointer to an Erlang term
/// 
/// # Usage
/// ```rust,ignore
/// avmnif_rs::make_resource_term;
/// 
/// let term = make_resource_term!(env, display_ptr);
/// ```
#[macro_export]
macro_rules! make_resource_term {
    ($env:expr, $resource_ptr:expr) => {{
        let raw_term = unsafe {
            $crate::resource::enif_make_resource(
                $env.as_c_ptr(),
                $resource_ptr,
            )
        };
        $crate::term::Term::from_raw(raw_term)
    }};
}