mtl-rs 0.1.7

Rust bindings for Apple's Metal API
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
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
use std::{ffi::c_void, path::Path, ptr::NonNull};

use dispatch2::DispatchData;
use objc2::{Message, extern_protocol, msg_send, rc::Retained, runtime::ProtocolObject};
use objc2_foundation::{NSArray, NSError, NSObjectProtocol, NSString, NSURL};

use super::MTLArchitecture;
use crate::{
    MTL4ArgumentTable, MTL4ArgumentTableDescriptor, MTLAccelerationStructure, MTLArgumentBuffersTier,
    MTLArgumentEncoder, MTLBuffer, MTLCommandQueue, MTLCompileOptions, MTLComputePipelineDescriptor,
    MTLComputePipelineState, MTLCounterSampleBuffer, MTLCounterSampleBufferDescriptor, MTLCounterSamplingPoint,
    MTLCounterSet, MTLDepthStencilDescriptor, MTLDepthStencilState, MTLDeviceLocation, MTLDynamicLibrary, MTLEvent,
    MTLFeatureSet, MTLFence, MTLFunction, MTLGPUFamily, MTLHeap, MTLHeapDescriptor, MTLIOCommandQueue,
    MTLIOCommandQueueDescriptor, MTLLibrary, MTLLogState, MTLLogStateDescriptor, MTLPipelineOption, MTLPixelFormat,
    MTLReadWriteTextureTier, MTLRenderPipelineDescriptor, MTLRenderPipelineState, MTLResidencySet,
    MTLResidencySetDescriptor, MTLResourceOptions, MTLSamplerDescriptor, MTLSamplerState, MTLSharedEvent,
    MTLSharedEventHandle, MTLSize, MTLTexture, MTLTextureDescriptor,
    acceleration_structure::MTLAccelerationStructureDescriptor, argument::MTLArgumentDescriptor,
    compute_pipeline::MTLComputePipelineReflection, function_stitching::MTLStitchedLibraryDescriptor,
};

extern_protocol!(
    /// A Metal device that represents a GPU.
    ///
    /// See Apple's documentation for  for details.
    pub unsafe trait MTLDevice: NSObjectProtocol + Send + Sync {
        /// Returns the IORegistry ID for the Metal device.
        #[unsafe(method(registryID))]
        #[unsafe(method_family = none)]
        fn registry_id(&self) -> u64;

        /// The device's architecture information.
        #[unsafe(method(architecture))]
        #[unsafe(method_family = none)]
        fn architecture(&self) -> Retained<MTLArchitecture>;

        /// The maximum number of threads along each dimension.
        #[unsafe(method(maxThreadsPerThreadgroup))]
        #[unsafe(method_family = none)]
        fn max_threads_per_threadgroup(&self) -> MTLSize;

        /// Whether this GPU is a low-power device.
        #[unsafe(method(isLowPower))]
        #[unsafe(method_family = none)]
        fn is_low_power(&self) -> bool;

        /// Whether this GPU has no displays attached.
        #[unsafe(method(isHeadless))]
        #[unsafe(method_family = none)]
        fn is_headless(&self) -> bool;

        /// Whether this GPU shares its memory with the CPU.
        #[unsafe(method(hasUnifiedMemory))]
        #[unsafe(method_family = none)]
        fn has_unified_memory(&self) -> bool;

        /// Approximation of how much memory this device can use with good performance.
        #[unsafe(method(recommendedMaxWorkingSetSize))]
        #[unsafe(method_family = none)]
        fn recommended_max_working_set_size(&self) -> u64;

        /// Preferred location of the GPU relative to the host.
        #[unsafe(method(location))]
        #[unsafe(method_family = none)]
        fn location(&self) -> MTLDeviceLocation;

        /// Further specifies the GPU's location (slot or port number).
        #[unsafe(method(locationNumber))]
        #[unsafe(method_family = none)]
        fn location_number(&self) -> usize;

        /// Upper bound of System RAM <=> VRAM transfer rate in bytes/sec.
        #[unsafe(method(maxTransferRate))]
        #[unsafe(method_family = none)]
        fn max_transfer_rate(&self) -> u64;

        /// Query support tier for read-write texture formats.
        #[unsafe(method(readWriteTextureSupport))]
        #[unsafe(method_family = none)]
        fn read_write_texture_support(&self) -> MTLReadWriteTextureTier;

        /// Query support tier for argument buffers.
        #[unsafe(method(argumentBuffersSupport))]
        #[unsafe(method_family = none)]
        fn argument_buffers_support(&self) -> MTLArgumentBuffersTier;

        /// Whether the device supports MTLPixelFormatDepth24Unorm_Stencil8.
        #[unsafe(method(isDepth24Stencil8PixelFormatSupported))]
        #[unsafe(method_family = none)]
        fn is_depth24_stencil8_pixel_format_supported(&self) -> bool;

        /// Whether the device supports the specified GPU family.
        #[unsafe(method(supportsFamily:))]
        #[unsafe(method_family = none)]
        fn supports_family(
            &self,
            family: MTLGPUFamily,
        ) -> bool;

        /// Whether the device supports textures with a given sample count.
        #[unsafe(method(supportsTextureSampleCount:))]
        #[unsafe(method_family = none)]
        fn supports_texture_sample_count(
            &self,
            sample_count: usize,
        ) -> bool;

        /// Minimum alignment for linear textures for a pixel format (offset and rowBytes).
        #[unsafe(method(minimumLinearTextureAlignmentForPixelFormat:))]
        #[unsafe(method_family = none)]
        fn minimum_linear_texture_alignment_for_pixel_format(
            &self,
            format: MTLPixelFormat,
        ) -> usize;

        /// Minimum alignment for texture buffers for a pixel format.
        #[unsafe(method(minimumTextureBufferAlignmentForPixelFormat:))]
        #[unsafe(method_family = none)]
        fn minimum_texture_buffer_alignment_for_pixel_format(
            &self,
            format: MTLPixelFormat,
        ) -> usize;

        /// Returns a new depth/stencil state object.
        #[unsafe(method(newDepthStencilStateWithDescriptor:))]
        #[unsafe(method_family = new)]
        fn new_depth_stencil_state_with_descriptor(
            &self,
            descriptor: &MTLDepthStencilDescriptor,
        ) -> Option<Retained<ProtocolObject<dyn MTLDepthStencilState>>>;

        /// Allocate a new counter sample buffer.
        #[unsafe(method(newCounterSampleBufferWithDescriptor:error:_))]
        #[unsafe(method_family = none)]
        fn new_counter_sample_buffer_with_descriptor_error(
            &self,
            descriptor: &MTLCounterSampleBufferDescriptor,
        ) -> Result<Retained<ProtocolObject<dyn MTLCounterSampleBuffer>>, Retained<NSError>>;

        /// Sample the CPU and GPU timestamps as closely as possible.
        #[unsafe(method(sampleTimestamps:gpuTimestamp:))]
        #[unsafe(method_family = none)]
        fn sample_timestamps_gpu_timestamp(
            &self,
            cpu_timestamp: *mut u64,
            gpu_timestamp: *mut u64,
        );

        /// Query device for counter sampling points support.
        #[unsafe(method(supportsCounterSampling:))]
        #[unsafe(method_family = none)]
        fn supports_counter_sampling(
            &self,
            sampling_point: MTLCounterSamplingPoint,
        ) -> bool;

        /// Whether the device supports query of texture LOD.
        #[unsafe(method(supportsQueryTextureLOD))]
        #[unsafe(method_family = none)]
        fn supports_query_texture_lod(&self) -> bool;

        /// Whether the device supports BC texture compression.
        #[unsafe(method(supportsBCTextureCompression))]
        #[unsafe(method_family = none)]
        fn supports_bc_texture_compression(&self) -> bool;

        /// Whether the device supports pull model interpolation.
        #[unsafe(method(supportsPullModelInterpolation))]
        #[unsafe(method_family = none)]
        fn supports_pull_model_interpolation(&self) -> bool;

        /// Deprecated in favor of .
        #[unsafe(method(areBarycentricCoordsSupported))]
        #[unsafe(method_family = none)]
        fn barycentric_coords_supported(&self) -> bool;

        /// Whether the device supports shader barycentric coordinates.
        #[unsafe(method(supportsShaderBarycentricCoordinates))]
        #[unsafe(method_family = none)]
        fn supports_shader_barycentric_coordinates(&self) -> bool;

        /// Current size in bytes of all resources allocated by this device.
        #[unsafe(method(currentAllocatedSize))]
        #[unsafe(method_family = none)]
        fn current_allocated_size(&self) -> usize;
    }
);

#[allow(unused)]
pub trait MTLDeviceExt: MTLDevice + Message {
    /// The full name of the vendor device.
    fn name(&self) -> String;

    /// Array of the Counter Sets exposed by the device, or None.
    fn counter_sets(&self) -> Option<Box<[Retained<ProtocolObject<dyn MTLCounterSet>>]>>;

    /// Create a buffer by allocating new memory.
    fn new_buffer(
        &self,
        length: usize,
        options: MTLResourceOptions,
    ) -> Option<Retained<ProtocolObject<dyn MTLBuffer>>>;

    /// Create a buffer by copying data from a byte slice.
    fn new_buffer_with_data(
        &self,
        data: &[u8],
        options: MTLResourceOptions,
    ) -> Option<Retained<ProtocolObject<dyn MTLBuffer>>>;

    /// Create a buffer wrapping existing memory without copying.
    /// Safety: The pointer must remain valid for the lifetime of the buffer.
    fn new_buffer_with_bytes_no_copy(
        &self,
        ptr: NonNull<c_void>,
        length: usize,
        options: MTLResourceOptions,
    ) -> Option<Retained<ProtocolObject<dyn MTLBuffer>>>;

    /// Create a new command queue with default max command buffer count (64).
    fn new_command_queue(&self) -> Option<Retained<ProtocolObject<dyn MTLCommandQueue>>>;

    /// Create a new command queue with specified max command buffer count.
    fn new_command_queue_with_max_command_buffer_count(
        &self,
        max_count: usize,
    ) -> Option<Retained<ProtocolObject<dyn MTLCommandQueue>>>;

    /// Get the default library from the main bundle.
    fn new_default_library(&self) -> Option<Retained<ProtocolObject<dyn MTLLibrary>>>;

    /// Load a library from compiled metallib data.
    fn new_library_with_data(
        &self,
        data: &[u8],
    ) -> Result<Retained<ProtocolObject<dyn MTLLibrary>>, Retained<NSError>>;

    /// Load a library from a file path.
    fn new_library_with_path(
        &self,
        path: &Path,
    ) -> Result<Retained<ProtocolObject<dyn MTLLibrary>>, Retained<NSError>>;

    /// Compile a library from Metal Shading Language source code.
    fn new_library_with_source(
        &self,
        source: &str,
        options: Option<&MTLCompileOptions>,
    ) -> Result<Retained<ProtocolObject<dyn MTLLibrary>>, Retained<NSError>>;

    /// Create a render pipeline state from a descriptor.
    fn new_render_pipeline_state_with_descriptor(
        &self,
        descriptor: &MTLRenderPipelineDescriptor,
    ) -> Result<Retained<ProtocolObject<dyn MTLRenderPipelineState>>, Retained<NSError>>;

    /// Create a compute pipeline state from a function.
    fn new_compute_pipeline_state_with_function(
        &self,
        function: &ProtocolObject<dyn MTLFunction>,
    ) -> Result<Retained<ProtocolObject<dyn MTLComputePipelineState>>, Retained<NSError>>;

    /// Create a compute pipeline state from a descriptor with reflection.
    fn new_compute_pipeline_state_with_descriptor(
        &self,
        descriptor: &MTLComputePipelineDescriptor,
        options: MTLPipelineOption,
    ) -> Result<
        (Retained<ProtocolObject<dyn MTLComputePipelineState>>, Option<Retained<MTLComputePipelineReflection>>),
        Retained<NSError>,
    >;

    /// Create a new heap.
    fn new_heap_with_descriptor(
        &self,
        descriptor: &MTLHeapDescriptor,
    ) -> Option<Retained<ProtocolObject<dyn MTLHeap>>>;

    /// Create a new texture.
    fn new_texture_with_descriptor(
        &self,
        descriptor: &MTLTextureDescriptor,
    ) -> Option<Retained<ProtocolObject<dyn MTLTexture>>>;

    /// Create a new sampler state.
    fn new_sampler_state_with_descriptor(
        &self,
        descriptor: &MTLSamplerDescriptor,
    ) -> Option<Retained<ProtocolObject<dyn MTLSamplerState>>>;

    /// Create a new event for GPU synchronization.
    fn new_event(&self) -> Option<Retained<ProtocolObject<dyn MTLEvent>>>;

    /// Create a new fence for resource tracking.
    fn new_fence(&self) -> Option<Retained<ProtocolObject<dyn MTLFence>>>;

    /// The maximum threadgroup memory available, in bytes.
    fn max_threadgroup_memory_length(&self) -> usize;

    /// The maximum buffer length supported by this device.
    fn max_buffer_length(&self) -> usize;

    /// Whether raster order groups are supported.
    fn raster_order_groups_supported(&self) -> bool;

    /// Whether the device supports a specific feature set (deprecated, use supports_family).
    fn supports_feature_set(
        &self,
        feature_set: MTLFeatureSet,
    ) -> bool;

    /// Creates a new shareable event.
    fn new_shared_event(&self) -> Option<Retained<ProtocolObject<dyn MTLSharedEvent>>>;

    /// Creates a shareable event from a shared event handle.
    fn new_shared_event_with_handle(
        &self,
        handle: &MTLSharedEventHandle,
    ) -> Option<Retained<ProtocolObject<dyn MTLSharedEvent>>>;

    /// Creates a dynamic library from a library.
    fn new_dynamic_library(
        &self,
        library: &ProtocolObject<dyn MTLLibrary>,
    ) -> Result<Retained<ProtocolObject<dyn MTLDynamicLibrary>>, Retained<NSError>>;

    /// Creates a dynamic library from a file path.
    fn new_dynamic_library_with_path(
        &self,
        path: &Path,
    ) -> Result<Retained<ProtocolObject<dyn MTLDynamicLibrary>>, Retained<NSError>>;

    /// Creates a new I/O command queue.
    fn new_io_command_queue_with_descriptor(
        &self,
        descriptor: &MTLIOCommandQueueDescriptor,
    ) -> Result<Retained<ProtocolObject<dyn MTLIOCommandQueue>>, Retained<NSError>>;

    /// Creates a new acceleration structure with the specified size.
    fn new_acceleration_structure_with_size(
        &self,
        size: usize,
    ) -> Option<Retained<ProtocolObject<dyn MTLAccelerationStructure>>>;

    /// Creates a new acceleration structure with the specified descriptor.
    fn new_acceleration_structure_with_descriptor(
        &self,
        descriptor: &MTLAccelerationStructureDescriptor,
    ) -> Option<Retained<ProtocolObject<dyn MTLAccelerationStructure>>>;

    /// Creates an argument encoder with the specified arguments.
    fn new_argument_encoder_with_arguments(
        &self,
        arguments: &[&MTLArgumentDescriptor],
    ) -> Option<Retained<ProtocolObject<dyn MTLArgumentEncoder>>>;

    /// Creates a new log state with the specified descriptor.
    fn new_log_state_with_descriptor(
        &self,
        descriptor: &MTLLogStateDescriptor,
    ) -> Result<Retained<ProtocolObject<dyn MTLLogState>>, Retained<NSError>>;

    /// Creates a new library with the specified stitched library descriptor.
    fn new_library_with_stitched_descriptor(
        &self,
        descriptor: &MTLStitchedLibraryDescriptor,
    ) -> Result<Retained<ProtocolObject<dyn MTLLibrary>>, Retained<NSError>>;

    /// Creates a new argument table from the given descriptor.
    fn new_argument_table_with_descriptor(
        &self,
        descriptor: &MTL4ArgumentTableDescriptor,
    ) -> Result<Retained<ProtocolObject<dyn MTL4ArgumentTable>>, Retained<NSError>>;

    /// Creates a new Metal 4 command queue.
    fn new_mtl4_command_queue(&self) -> Option<Retained<ProtocolObject<dyn crate::MTL4CommandQueue>>>;

    /// Creates a new Metal 4 command allocator.
    fn new_command_allocator(&self) -> Option<Retained<ProtocolObject<dyn crate::MTL4CommandAllocator>>>;

    /// Creates a new Metal 4 command buffer.
    fn new_mtl4_command_buffer(&self) -> Option<Retained<ProtocolObject<dyn crate::MTL4CommandBuffer>>>;

    /// Creates a new residency set with the given descriptor.
    fn new_residency_set_with_descriptor(
        &self,
        descriptor: &MTLResidencySetDescriptor,
    ) -> Result<Retained<ProtocolObject<dyn MTLResidencySet>>, Retained<NSError>>;
}

impl MTLDeviceExt for ProtocolObject<dyn MTLDevice> {
    fn name(&self) -> String {
        let ns: Retained<NSString> = unsafe { msg_send![self, name] };
        ns.to_string()
    }

    fn counter_sets(&self) -> Option<Box<[Retained<ProtocolObject<dyn MTLCounterSet>>]>> {
        let array: Option<Retained<NSArray<ProtocolObject<dyn MTLCounterSet>>>> =
            unsafe { msg_send![self, counterSets] };
        array.map(|a| a.to_vec().into_boxed_slice())
    }

    fn new_buffer(
        &self,
        length: usize,
        options: MTLResourceOptions,
    ) -> Option<Retained<ProtocolObject<dyn MTLBuffer>>> {
        unsafe { msg_send![self, newBufferWithLength: length, options: options] }
    }

    fn new_buffer_with_data(
        &self,
        data: &[u8],
        options: MTLResourceOptions,
    ) -> Option<Retained<ProtocolObject<dyn MTLBuffer>>> {
        unsafe {
            msg_send![
                self,
                newBufferWithBytes: data.as_ptr() as *const c_void,
                length: data.len(),
                options: options
            ]
        }
    }

    fn new_buffer_with_bytes_no_copy(
        &self,
        ptr: NonNull<c_void>,
        length: usize,
        options: MTLResourceOptions,
    ) -> Option<Retained<ProtocolObject<dyn MTLBuffer>>> {
        // Pass null for deallocator - caller is responsible for memory management
        let deallocator: Option<&crate::block2::Block<dyn Fn(*mut c_void, usize)>> = None;
        unsafe {
            msg_send![
                self,
                newBufferWithBytesNoCopy: ptr.as_ptr(),
                length: length,
                options: options,
                deallocator: deallocator
            ]
        }
    }

    fn new_command_queue(&self) -> Option<Retained<ProtocolObject<dyn MTLCommandQueue>>> {
        unsafe { msg_send![self, newCommandQueue] }
    }

    fn new_command_queue_with_max_command_buffer_count(
        &self,
        max_count: usize,
    ) -> Option<Retained<ProtocolObject<dyn MTLCommandQueue>>> {
        unsafe { msg_send![self, newCommandQueueWithMaxCommandBufferCount: max_count] }
    }

    fn new_default_library(&self) -> Option<Retained<ProtocolObject<dyn MTLLibrary>>> {
        unsafe { msg_send![self, newDefaultLibrary] }
    }

    fn new_library_with_data(
        &self,
        data: &[u8],
    ) -> Result<Retained<ProtocolObject<dyn MTLLibrary>>, Retained<NSError>> {
        let dispatch_data = DispatchData::from_bytes(data);

        let mut error: *mut NSError = std::ptr::null_mut();
        let result: Option<Retained<ProtocolObject<dyn MTLLibrary>>> =
            unsafe { msg_send![self, newLibraryWithData: &*dispatch_data, error: &mut error] };

        match result {
            Some(lib) => Ok(lib),
            None => Err(unsafe { Retained::retain(error).unwrap() }),
        }
    }

    fn new_library_with_path(
        &self,
        path: &Path,
    ) -> Result<Retained<ProtocolObject<dyn MTLLibrary>>, Retained<NSError>> {
        let url = NSURL::from_file_path(path).expect("path must be a valid file URL path");
        let mut error: *mut NSError = std::ptr::null_mut();
        let result: Option<Retained<ProtocolObject<dyn MTLLibrary>>> =
            unsafe { msg_send![self, newLibraryWithURL: &*url, error: &mut error] };

        match result {
            Some(lib) => Ok(lib),
            None => Err(unsafe { Retained::retain(error).unwrap() }),
        }
    }

    fn new_library_with_source(
        &self,
        source: &str,
        options: Option<&MTLCompileOptions>,
    ) -> Result<Retained<ProtocolObject<dyn MTLLibrary>>, Retained<NSError>> {
        let source = NSString::from_str(source);
        let mut error: *mut NSError = std::ptr::null_mut();
        let result: Option<Retained<ProtocolObject<dyn MTLLibrary>>> = unsafe {
            msg_send![
                self,
                newLibraryWithSource: &*source,
                options: options,
                error: &mut error
            ]
        };

        match result {
            Some(lib) => Ok(lib),
            None => Err(unsafe { Retained::retain(error).unwrap() }),
        }
    }

    fn new_render_pipeline_state_with_descriptor(
        &self,
        descriptor: &MTLRenderPipelineDescriptor,
    ) -> Result<Retained<ProtocolObject<dyn MTLRenderPipelineState>>, Retained<NSError>> {
        let mut error: *mut NSError = std::ptr::null_mut();
        let result: Option<Retained<ProtocolObject<dyn MTLRenderPipelineState>>> = unsafe {
            msg_send![
                self,
                newRenderPipelineStateWithDescriptor: descriptor,
                error: &mut error
            ]
        };

        match result {
            Some(pso) => Ok(pso),
            None => Err(unsafe { Retained::retain(error).unwrap() }),
        }
    }

    fn new_compute_pipeline_state_with_function(
        &self,
        function: &ProtocolObject<dyn MTLFunction>,
    ) -> Result<Retained<ProtocolObject<dyn MTLComputePipelineState>>, Retained<NSError>> {
        let mut error: *mut NSError = std::ptr::null_mut();
        let result: Option<Retained<ProtocolObject<dyn MTLComputePipelineState>>> =
            unsafe { msg_send![self, newComputePipelineStateWithFunction: function, error: &mut error] };

        match result {
            Some(pso) => Ok(pso),
            None => Err(unsafe { Retained::retain(error).unwrap() }),
        }
    }

    fn new_compute_pipeline_state_with_descriptor(
        &self,
        descriptor: &MTLComputePipelineDescriptor,
        options: MTLPipelineOption,
    ) -> Result<
        (Retained<ProtocolObject<dyn MTLComputePipelineState>>, Option<Retained<MTLComputePipelineReflection>>),
        Retained<NSError>,
    > {
        let mut reflection: *mut MTLComputePipelineReflection = std::ptr::null_mut();
        let mut error: *mut NSError = std::ptr::null_mut();

        let result: Option<Retained<ProtocolObject<dyn MTLComputePipelineState>>> = unsafe {
            msg_send![
                self,
                newComputePipelineStateWithDescriptor: descriptor,
                options: options,
                reflection: &mut reflection,
                error: &mut error
            ]
        };

        match result {
            Some(pso) => {
                let reflection_obj = if reflection.is_null() {
                    None
                } else {
                    unsafe { Retained::retain(reflection) }
                };
                Ok((pso, reflection_obj))
            },
            None => Err(unsafe { Retained::retain(error).unwrap() }),
        }
    }

    fn new_heap_with_descriptor(
        &self,
        descriptor: &MTLHeapDescriptor,
    ) -> Option<Retained<ProtocolObject<dyn MTLHeap>>> {
        unsafe { msg_send![self, newHeapWithDescriptor: descriptor] }
    }

    fn new_texture_with_descriptor(
        &self,
        descriptor: &MTLTextureDescriptor,
    ) -> Option<Retained<ProtocolObject<dyn MTLTexture>>> {
        unsafe { msg_send![self, newTextureWithDescriptor: descriptor] }
    }

    fn new_sampler_state_with_descriptor(
        &self,
        descriptor: &MTLSamplerDescriptor,
    ) -> Option<Retained<ProtocolObject<dyn MTLSamplerState>>> {
        unsafe { msg_send![self, newSamplerStateWithDescriptor: descriptor] }
    }

    fn new_event(&self) -> Option<Retained<ProtocolObject<dyn MTLEvent>>> {
        unsafe { msg_send![self, newEvent] }
    }

    fn new_fence(&self) -> Option<Retained<ProtocolObject<dyn MTLFence>>> {
        unsafe { msg_send![self, newFence] }
    }

    fn max_threadgroup_memory_length(&self) -> usize {
        unsafe { msg_send![self, maxThreadgroupMemoryLength] }
    }

    fn max_buffer_length(&self) -> usize {
        unsafe { msg_send![self, maxBufferLength] }
    }

    fn raster_order_groups_supported(&self) -> bool {
        unsafe { msg_send![self, areRasterOrderGroupsSupported] }
    }

    fn supports_feature_set(
        &self,
        feature_set: MTLFeatureSet,
    ) -> bool {
        unsafe { msg_send![self, supportsFeatureSet: feature_set] }
    }

    fn new_shared_event(&self) -> Option<Retained<ProtocolObject<dyn MTLSharedEvent>>> {
        unsafe { msg_send![self, newSharedEvent] }
    }

    fn new_shared_event_with_handle(
        &self,
        handle: &MTLSharedEventHandle,
    ) -> Option<Retained<ProtocolObject<dyn MTLSharedEvent>>> {
        unsafe { msg_send![self, newSharedEventWithHandle: handle] }
    }

    fn new_dynamic_library(
        &self,
        library: &ProtocolObject<dyn MTLLibrary>,
    ) -> Result<Retained<ProtocolObject<dyn MTLDynamicLibrary>>, Retained<NSError>> {
        let mut error: *mut NSError = std::ptr::null_mut();
        let result: Option<Retained<ProtocolObject<dyn MTLDynamicLibrary>>> =
            unsafe { msg_send![self, newDynamicLibrary: library, error: &mut error] };
        match result {
            Some(lib) => Ok(lib),
            None => Err(unsafe { Retained::retain(error).unwrap() }),
        }
    }

    fn new_dynamic_library_with_path(
        &self,
        path: &Path,
    ) -> Result<Retained<ProtocolObject<dyn MTLDynamicLibrary>>, Retained<NSError>> {
        let url = NSURL::from_file_path(path).expect("path must be a valid file URL path");
        let mut error: *mut NSError = std::ptr::null_mut();
        let result: Option<Retained<ProtocolObject<dyn MTLDynamicLibrary>>> =
            unsafe { msg_send![self, newDynamicLibraryWithURL: &*url, error: &mut error] };
        match result {
            Some(lib) => Ok(lib),
            None => Err(unsafe { Retained::retain(error).unwrap() }),
        }
    }

    fn new_io_command_queue_with_descriptor(
        &self,
        descriptor: &MTLIOCommandQueueDescriptor,
    ) -> Result<Retained<ProtocolObject<dyn MTLIOCommandQueue>>, Retained<NSError>> {
        let mut error: *mut NSError = std::ptr::null_mut();
        let result: Option<Retained<ProtocolObject<dyn MTLIOCommandQueue>>> =
            unsafe { msg_send![self, newIOCommandQueueWithDescriptor: descriptor, error: &mut error] };
        match result {
            Some(queue) => Ok(queue),
            None => Err(unsafe { Retained::retain(error).unwrap() }),
        }
    }

    fn new_acceleration_structure_with_size(
        &self,
        size: usize,
    ) -> Option<Retained<ProtocolObject<dyn MTLAccelerationStructure>>> {
        unsafe { msg_send![self, newAccelerationStructureWithSize: size] }
    }

    fn new_acceleration_structure_with_descriptor(
        &self,
        descriptor: &MTLAccelerationStructureDescriptor,
    ) -> Option<Retained<ProtocolObject<dyn MTLAccelerationStructure>>> {
        unsafe { msg_send![self, newAccelerationStructureWithDescriptor: descriptor] }
    }

    fn new_argument_encoder_with_arguments(
        &self,
        arguments: &[&MTLArgumentDescriptor],
    ) -> Option<Retained<ProtocolObject<dyn MTLArgumentEncoder>>> {
        let arguments = NSArray::from_slice(arguments);
        unsafe { msg_send![self, newArgumentEncoderWithArguments: &*arguments] }
    }

    fn new_log_state_with_descriptor(
        &self,
        descriptor: &MTLLogStateDescriptor,
    ) -> Result<Retained<ProtocolObject<dyn MTLLogState>>, Retained<NSError>> {
        let mut error: *mut NSError = std::ptr::null_mut();
        let result: Option<Retained<ProtocolObject<dyn MTLLogState>>> =
            unsafe { msg_send![self, newLogStateWithDescriptor: descriptor, error: &mut error] };
        match result {
            Some(log) => Ok(log),
            None => Err(unsafe { Retained::retain(error).unwrap() }),
        }
    }

    fn new_library_with_stitched_descriptor(
        &self,
        descriptor: &MTLStitchedLibraryDescriptor,
    ) -> Result<Retained<ProtocolObject<dyn MTLLibrary>>, Retained<NSError>> {
        let mut error: *mut NSError = std::ptr::null_mut();
        let result: Option<Retained<ProtocolObject<dyn MTLLibrary>>> =
            unsafe { msg_send![self, newLibraryWithStitchedDescriptor: descriptor, error: &mut error] };
        match result {
            Some(lib) => Ok(lib),
            None => Err(unsafe { Retained::retain(error).unwrap() }),
        }
    }

    fn new_argument_table_with_descriptor(
        &self,
        descriptor: &MTL4ArgumentTableDescriptor,
    ) -> Result<Retained<ProtocolObject<dyn MTL4ArgumentTable>>, Retained<NSError>> {
        let mut error: *mut NSError = std::ptr::null_mut();
        let result: Option<Retained<ProtocolObject<dyn MTL4ArgumentTable>>> =
            unsafe { msg_send![self, newArgumentTableWithDescriptor: descriptor, error: &mut error] };
        match result {
            Some(table) => Ok(table),
            None => Err(unsafe { Retained::retain(error).unwrap() }),
        }
    }

    fn new_mtl4_command_queue(&self) -> Option<Retained<ProtocolObject<dyn crate::MTL4CommandQueue>>> {
        unsafe { msg_send![self, newMTL4CommandQueue] }
    }

    fn new_command_allocator(&self) -> Option<Retained<ProtocolObject<dyn crate::MTL4CommandAllocator>>> {
        unsafe { msg_send![self, newCommandAllocator] }
    }

    fn new_mtl4_command_buffer(&self) -> Option<Retained<ProtocolObject<dyn crate::MTL4CommandBuffer>>> {
        unsafe { msg_send![self, newCommandBuffer] }
    }

    fn new_residency_set_with_descriptor(
        &self,
        descriptor: &MTLResidencySetDescriptor,
    ) -> Result<Retained<ProtocolObject<dyn MTLResidencySet>>, Retained<NSError>> {
        let mut error: *mut NSError = std::ptr::null_mut();
        let result: Option<Retained<ProtocolObject<dyn MTLResidencySet>>> =
            unsafe { msg_send![self, newResidencySetWithDescriptor: descriptor, error: &mut error] };
        match result {
            Some(set) => Ok(set),
            None => Err(unsafe { Retained::retain(error).unwrap() }),
        }
    }
}

impl dyn MTLDevice {
    /// Returns a reference to the preferred system default Metal device.
    #[inline]
    pub fn system_default() -> Option<Retained<ProtocolObject<dyn MTLDevice>>> {
        unsafe extern "C" {
            fn MTLCreateSystemDefaultDevice() -> *mut ProtocolObject<dyn MTLDevice>;
        }
        let ret = unsafe { MTLCreateSystemDefaultDevice() };
        unsafe { Retained::from_raw(ret) }
    }
}