objc2-metal 0.3.2

Bindings to the Metal framework
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
//! This file has been automatically generated by `objc2`'s `header-translator`.
//! DO NOT EDIT
use core::ffi::*;
use core::ptr::NonNull;
use objc2::__framework_prelude::*;
use objc2_foundation::*;

use crate::*;

/// The possible data types for the elements of a tensor.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/metal/mtltensordatatype?language=objc)
// NS_ENUM
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct MTLTensorDataType(pub NSInteger);
impl MTLTensorDataType {
    #[doc(alias = "MTLTensorDataTypeNone")]
    pub const None: Self = Self(0);
    #[doc(alias = "MTLTensorDataTypeFloat32")]
    pub const Float32: Self = Self(3);
    #[doc(alias = "MTLTensorDataTypeFloat16")]
    pub const Float16: Self = Self(16);
    #[doc(alias = "MTLTensorDataTypeBFloat16")]
    pub const BFloat16: Self = Self(121);
    #[doc(alias = "MTLTensorDataTypeInt8")]
    pub const Int8: Self = Self(45);
    #[doc(alias = "MTLTensorDataTypeUInt8")]
    pub const UInt8: Self = Self(49);
    #[doc(alias = "MTLTensorDataTypeInt16")]
    pub const Int16: Self = Self(37);
    #[doc(alias = "MTLTensorDataTypeUInt16")]
    pub const UInt16: Self = Self(41);
    #[doc(alias = "MTLTensorDataTypeInt32")]
    pub const Int32: Self = Self(29);
    #[doc(alias = "MTLTensorDataTypeUInt32")]
    pub const UInt32: Self = Self(33);
}

unsafe impl Encode for MTLTensorDataType {
    const ENCODING: Encoding = NSInteger::ENCODING;
}

unsafe impl RefEncode for MTLTensorDataType {
    const ENCODING_REF: Encoding = Encoding::Pointer(&Self::ENCODING);
}

extern_class!(
    /// An array of length matching the rank, holding the dimensions of a tensor.
    ///
    /// Supports rank up to ``MTL_TENSOR_MAX_RANK``.
    ///
    /// See also [Apple's documentation](https://developer.apple.com/documentation/metal/mtltensorextents?language=objc)
    #[unsafe(super(NSObject))]
    #[derive(Debug, PartialEq, Eq, Hash)]
    pub struct MTLTensorExtents;
);

extern_conformance!(
    unsafe impl NSObjectProtocol for MTLTensorExtents {}
);

impl MTLTensorExtents {
    extern_methods!(
        /// Creates a new tensor extents with the rank and extent values you provide.
        ///
        /// Zero rank extents represent scalars. `values` can only be `nil`if `rank` is 0.
        /// - Parameters:
        /// - rank: the number of dimensions.
        /// - values: an array of length `rank` that specifies the size of each dimension. The first dimension is the innermost dimension.
        /// - Returns: Tensor extents with the rank and extent values you provide. Returns `nil` if `rank` exceeds 0 and `values` is nil or if `rank` exceeds ``MTL_TENSOR_MAX_RANK``.
        ///
        /// # Safety
        ///
        /// `values` must be a valid pointer or null.
        #[unsafe(method(initWithRank:values:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithRank_values(
            this: Allocated<Self>,
            rank: NSUInteger,
            values: *const NSInteger,
        ) -> Option<Retained<Self>>;

        /// Obtains the rank of the tensor.
        ///
        /// The rank represents the number of dimensions.
        #[unsafe(method(rank))]
        #[unsafe(method_family = none)]
        pub fn rank(&self) -> NSUInteger;

        /// Returns the extent at an index.
        ///
        /// - Parameters:
        /// - dimensionIndex: the index of the dimension. The first dimension is the innermost dimension.
        /// - Returns: the extent at `dimensionIndex`. This method returns -1 if `dimensionIndex` is greater than or equal to `rank`.
        ///
        /// # Safety
        ///
        /// `dimensionIndex` might not be bounds-checked.
        #[unsafe(method(extentAtDimensionIndex:))]
        #[unsafe(method_family = none)]
        pub unsafe fn extentAtDimensionIndex(&self, dimension_index: NSUInteger) -> NSInteger;
    );
}

/// Methods declared on superclass `NSObject`.
impl MTLTensorExtents {
    extern_methods!(
        #[unsafe(method(init))]
        #[unsafe(method_family = init)]
        pub fn init(this: Allocated<Self>) -> Retained<Self>;

        #[unsafe(method(new))]
        #[unsafe(method_family = new)]
        pub fn new() -> Retained<Self>;
    );
}

impl DefaultRetained for MTLTensorExtents {
    #[inline]
    fn default_retained() -> Retained<Self> {
        Self::new()
    }
}

extern "C" {
    /// An error domain for errors that pertain to creating a tensor.
    ///
    /// See also [Apple's documentation](https://developer.apple.com/documentation/metal/mtltensordomain?language=objc)
    pub static MTLTensorDomain: &'static NSErrorDomain;
}

/// The error codes that Metal can raise when you create a tensor.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/metal/mtltensorerror?language=objc)
// NS_ENUM
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct MTLTensorError(pub NSInteger);
impl MTLTensorError {
    #[doc(alias = "MTLTensorErrorNone")]
    pub const None: Self = Self(0);
    #[doc(alias = "MTLTensorErrorInternalError")]
    pub const InternalError: Self = Self(1);
    #[doc(alias = "MTLTensorErrorInvalidDescriptor")]
    pub const InvalidDescriptor: Self = Self(2);
}

unsafe impl Encode for MTLTensorError {
    const ENCODING: Encoding = NSInteger::ENCODING;
}

unsafe impl RefEncode for MTLTensorError {
    const ENCODING_REF: Encoding = Encoding::Pointer(&Self::ENCODING);
}

/// The type that represents the different contexts for a tensor.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/metal/mtltensorusage?language=objc)
// NS_OPTIONS
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct MTLTensorUsage(pub NSUInteger);
bitflags::bitflags! {
    impl MTLTensorUsage: NSUInteger {
/// A tensor context that applies to compute encoders.
///
/// You can use tensors with this context in ``MTL4ComputeCommandEncoder`` or ``MTLComputeCommandEncoder`` instances.
        #[doc(alias = "MTLTensorUsageCompute")]
        const Compute = 1<<0;
/// A tensor context that applies to render encoders.
///
/// You can use tensors with this context in ``MTL4RenderCommandEncoder`` or ``MTLRenderCommandEncoder`` instances.
        #[doc(alias = "MTLTensorUsageRender")]
        const Render = 1<<1;
/// A tensor context that applies to machine learning encoders.
///
/// You can use tensors with this context in ``MTL4MachineLearningCommandEncoder`` instances.
        #[doc(alias = "MTLTensorUsageMachineLearning")]
        const MachineLearning = 1<<2;
    }
}

unsafe impl Encode for MTLTensorUsage {
    const ENCODING: Encoding = NSUInteger::ENCODING;
}

unsafe impl RefEncode for MTLTensorUsage {
    const ENCODING_REF: Encoding = Encoding::Pointer(&Self::ENCODING);
}

extern_class!(
    /// A configuration type for creating new tensor instances.
    ///
    /// See also [Apple's documentation](https://developer.apple.com/documentation/metal/mtltensordescriptor?language=objc)
    #[unsafe(super(NSObject))]
    #[derive(Debug, PartialEq, Eq, Hash)]
    pub struct MTLTensorDescriptor;
);

extern_conformance!(
    unsafe impl NSCopying for MTLTensorDescriptor {}
);

unsafe impl CopyingHelper for MTLTensorDescriptor {
    type Result = Self;
}

extern_conformance!(
    unsafe impl NSObjectProtocol for MTLTensorDescriptor {}
);

impl MTLTensorDescriptor {
    extern_methods!(
        /// An array of sizes, in elements, one for each dimension of the tensors you create with this descriptor.
        ///
        /// The default value of this property is a rank one extents with size one.
        #[unsafe(method(dimensions))]
        #[unsafe(method_family = none)]
        pub fn dimensions(&self) -> Retained<MTLTensorExtents>;

        /// Setter for [`dimensions`][Self::dimensions].
        ///
        /// This is [copied][objc2_foundation::NSCopying::copy] when set.
        #[unsafe(method(setDimensions:))]
        #[unsafe(method_family = none)]
        pub fn setDimensions(&self, dimensions: &MTLTensorExtents);

        /// An array of strides, in elements, one for each dimension in the tensors you create with this descriptor, if applicable.
        ///
        /// This property only applies to tensors you create from a buffer, otherwise it is nil. You are responsible for ensuring `strides` meets the following requirements:
        /// - Elements of `strides`are in monotonically non-decreasing order.
        /// - The first element of `strides` is one.
        /// - For any `i` larger than zero, `strides[i]` is greater than or equal to `strides[i-1] * dimensions[i-1]`.
        /// - If `usage` contains ``MTLTensorUsage/MTLTensorUsageMachineLearning``, the second element of `strides` is aligned to 64 bytes, and for any `i` larger than one, `strides[i]` is equal to `strides[i-1] * dimensions[i-1]`.
        #[unsafe(method(strides))]
        #[unsafe(method_family = none)]
        pub fn strides(&self) -> Option<Retained<MTLTensorExtents>>;

        /// Setter for [`strides`][Self::strides].
        ///
        /// This is [copied][objc2_foundation::NSCopying::copy] when set.
        #[unsafe(method(setStrides:))]
        #[unsafe(method_family = none)]
        pub fn setStrides(&self, strides: Option<&MTLTensorExtents>);

        /// A data format for the tensors you create with this descriptor.
        ///
        /// The default value of this property is ``MTLTensorDataType/MTLTensorDataTypeFloat32``.
        #[unsafe(method(dataType))]
        #[unsafe(method_family = none)]
        pub fn dataType(&self) -> MTLTensorDataType;

        /// Setter for [`dataType`][Self::dataType].
        #[unsafe(method(setDataType:))]
        #[unsafe(method_family = none)]
        pub fn setDataType(&self, data_type: MTLTensorDataType);

        /// A set of contexts in which you can use tensors you create with this descriptor.
        ///
        /// The default value for this property is a bitwise `OR` of:
        /// - ``MTLTensorUsage/MTLTensorUsageRender``
        /// - ``MTLTensorUsage/MTLTensorUsageCompute``
        #[unsafe(method(usage))]
        #[unsafe(method_family = none)]
        pub fn usage(&self) -> MTLTensorUsage;

        /// Setter for [`usage`][Self::usage].
        #[unsafe(method(setUsage:))]
        #[unsafe(method_family = none)]
        pub fn setUsage(&self, usage: MTLTensorUsage);

        #[cfg(feature = "MTLResource")]
        /// A packed set of the `storageMode`, `cpuCacheMode` and `hazardTrackingMode` properties.
        #[unsafe(method(resourceOptions))]
        #[unsafe(method_family = none)]
        pub fn resourceOptions(&self) -> MTLResourceOptions;

        #[cfg(feature = "MTLResource")]
        /// Setter for [`resourceOptions`][Self::resourceOptions].
        #[unsafe(method(setResourceOptions:))]
        #[unsafe(method_family = none)]
        pub fn setResourceOptions(&self, resource_options: MTLResourceOptions);

        #[cfg(feature = "MTLResource")]
        /// A value that configures the cache mode of CPU mapping of tensors you create with this descriptor.
        ///
        /// The default value of this property is ``MTLCPUCacheMode/MTLCPUCacheModeDefaultCache``.
        #[unsafe(method(cpuCacheMode))]
        #[unsafe(method_family = none)]
        pub fn cpuCacheMode(&self) -> MTLCPUCacheMode;

        #[cfg(feature = "MTLResource")]
        /// Setter for [`cpuCacheMode`][Self::cpuCacheMode].
        #[unsafe(method(setCpuCacheMode:))]
        #[unsafe(method_family = none)]
        pub fn setCpuCacheMode(&self, cpu_cache_mode: MTLCPUCacheMode);

        #[cfg(feature = "MTLResource")]
        /// A value that configures the memory location and access permissions of tensors you create with this descriptor.
        ///
        /// The default value of this property defaults to ``MTLStorageMode/MTLStorageModeShared``.
        #[unsafe(method(storageMode))]
        #[unsafe(method_family = none)]
        pub fn storageMode(&self) -> MTLStorageMode;

        #[cfg(feature = "MTLResource")]
        /// Setter for [`storageMode`][Self::storageMode].
        #[unsafe(method(setStorageMode:))]
        #[unsafe(method_family = none)]
        pub fn setStorageMode(&self, storage_mode: MTLStorageMode);

        #[cfg(feature = "MTLResource")]
        /// A value that configures the hazard tracking of tensors you create with this descriptor.
        ///
        /// The default value of this property is ``MTLHazardTrackingMode/MTLHazardTrackingModeDefault``.
        #[unsafe(method(hazardTrackingMode))]
        #[unsafe(method_family = none)]
        pub fn hazardTrackingMode(&self) -> MTLHazardTrackingMode;

        #[cfg(feature = "MTLResource")]
        /// Setter for [`hazardTrackingMode`][Self::hazardTrackingMode].
        #[unsafe(method(setHazardTrackingMode:))]
        #[unsafe(method_family = none)]
        pub fn setHazardTrackingMode(&self, hazard_tracking_mode: MTLHazardTrackingMode);
    );
}

/// Methods declared on superclass `NSObject`.
impl MTLTensorDescriptor {
    extern_methods!(
        #[unsafe(method(init))]
        #[unsafe(method_family = init)]
        pub fn init(this: Allocated<Self>) -> Retained<Self>;

        #[unsafe(method(new))]
        #[unsafe(method_family = new)]
        pub fn new() -> Retained<Self>;
    );
}

impl DefaultRetained for MTLTensorDescriptor {
    #[inline]
    fn default_retained() -> Retained<Self> {
        Self::new()
    }
}

extern_protocol!(
    /// A resource representing a multi-dimensional array that you can use with machine learning workloads.
    ///
    /// See also [Apple's documentation](https://developer.apple.com/documentation/metal/mtltensor?language=objc)
    #[cfg(all(feature = "MTLAllocation", feature = "MTLResource"))]
    pub unsafe trait MTLTensor: MTLResource {
        #[cfg(feature = "MTLTypes")]
        /// A handle that represents the GPU resource, which you can store in an argument buffer.
        #[unsafe(method(gpuResourceID))]
        #[unsafe(method_family = none)]
        fn gpuResourceID(&self) -> MTLResourceID;

        #[cfg(feature = "MTLBuffer")]
        /// A buffer instance this tensor shares its storage with or nil if this tensor does not wrap an underlying buffer.
        #[unsafe(method(buffer))]
        #[unsafe(method_family = none)]
        fn buffer(&self) -> Option<Retained<ProtocolObject<dyn MTLBuffer>>>;

        /// An offset, in bytes, into the buffer instance this tensor shares its storage with, or zero if this tensor does not wrap an underlying buffer.
        #[unsafe(method(bufferOffset))]
        #[unsafe(method_family = none)]
        fn bufferOffset(&self) -> NSUInteger;

        /// An array of strides, in elements, one for each dimension of this tensor.
        ///
        /// This property only applies if this tensor shares its storage with a buffer, otherwise it's nil.
        #[unsafe(method(strides))]
        #[unsafe(method_family = none)]
        fn strides(&self) -> Option<Retained<MTLTensorExtents>>;

        /// An array of sizes, in elements, one for each dimension of this tensor.
        #[unsafe(method(dimensions))]
        #[unsafe(method_family = none)]
        fn dimensions(&self) -> Retained<MTLTensorExtents>;

        /// An underlying data format of this tensor.
        #[unsafe(method(dataType))]
        #[unsafe(method_family = none)]
        fn dataType(&self) -> MTLTensorDataType;

        /// A set of contexts in which you can use this tensor.
        #[unsafe(method(usage))]
        #[unsafe(method_family = none)]
        fn usage(&self) -> MTLTensorUsage;

        /// Replaces the contents of a slice of this tensor with data you provide.
        ///
        /// - Parameters:
        /// - sliceOrigin: An array of offsets, in elements, to the first element of the slice that this method writes data to.
        /// - sliceDimensions: An array of sizes, in elements, of the slice this method writes data to.
        /// - bytes: A pointer to bytes of data that this method copies into the slice you specify with `sliceOrigin` and `sliceDimensions`.
        /// - strides: An array of strides, in elements, that describes the layout of the data in `bytes`. You are responsible for ensuring `strides` meets the following requirements:
        /// - Elements of `strides`are in monotonically non-decreasing order.
        /// - For any `i` larger than zero, `strides[i]` is greater than or equal to `strides[i-1] * dimensions[i-1]`.
        ///
        /// # Safety
        ///
        /// `bytes` must be a valid pointer.
        #[unsafe(method(replaceSliceOrigin:sliceDimensions:withBytes:strides:))]
        #[unsafe(method_family = none)]
        unsafe fn replaceSliceOrigin_sliceDimensions_withBytes_strides(
            &self,
            slice_origin: &MTLTensorExtents,
            slice_dimensions: &MTLTensorExtents,
            bytes: NonNull<c_void>,
            strides: &MTLTensorExtents,
        );

        /// Copies the data corresponding to a slice of this tensor into a pointer you provide.
        ///
        /// - Parameters:
        /// - bytes: A pointer to bytes of data that this method copies into the slice you specify with `sliceOrigin` and `sliceDimensions`.
        /// - strides: An array of strides, in elements, that describes the layout of the data in `bytes`. You are responsible for ensuring `strides` meets the following requirements:
        /// - Elements of `strides`are in monotonically non-decreasing order.
        /// - For any `i` larger than zero, `strides[i]` is greater than or equal to `strides[i-1] * dimensions[i-1]`.
        /// - sliceOrigin: An array of offsets, in elements, to the first element of the slice that this method reads data from.
        /// - sliceDimensions: An array of sizes, in elements, of the slice this method reads data from.
        ///
        /// # Safety
        ///
        /// `bytes` must be a valid pointer.
        #[unsafe(method(getBytes:strides:fromSliceOrigin:sliceDimensions:))]
        #[unsafe(method_family = none)]
        unsafe fn getBytes_strides_fromSliceOrigin_sliceDimensions(
            &self,
            bytes: NonNull<c_void>,
            strides: &MTLTensorExtents,
            slice_origin: &MTLTensorExtents,
            slice_dimensions: &MTLTensorExtents,
        );
    }
);