@@ -882,8 +882,20 @@ unsafe fn build_retained_tensor_data_array(
882882) -> Result < * mut Object , KernelError > {
883883 let mut datas: Vec < * mut Object > = Vec :: with_capacity ( specs. len ( ) ) ;
884884 for & ( buf, shape, dtype) in specs {
885+ // SAFETY: `shape` is a borrowed slice; `ns_array_from_usize` documents
886+ // that it reads the slice and builds an autoreleased NSArray<NSNumber>.
887+ // Caller of `build_retained_tensor_data_array` guarantees an active
888+ // autoreleasepool per this fn's `# Safety` contract.
885889 let shape_arr = unsafe { ns_array_from_usize ( shape) ? } ;
890+ // SAFETY: `[Class alloc]` is always safe to call on a valid Class*;
891+ // `tensor_data_cls` is the MPSGraphTensorData class we looked up at
892+ // compile time and retained.
886893 let alloc: * mut Object = unsafe { msg_send ! [ tensor_data_cls, alloc] } ;
894+ // SAFETY: `alloc` is a freshly-allocated MPSGraphTensorData instance
895+ // (one retain). `buf.as_ptr()` returns a valid MTLBuffer pointer whose
896+ // lifetime is guaranteed by this fn's contract ("buffers must outlive
897+ // the returned NSArray"). `shape_arr` is a valid autoreleased
898+ // NSArray<NSNumber>. `dtype` is a u32 enum value expected by the init.
887899 let td: * mut Object = unsafe {
888900 msg_send ! [ alloc,
889901 initWithMTLBuffer: buf. as_ptr( )
@@ -892,13 +904,23 @@ unsafe fn build_retained_tensor_data_array(
892904 } ;
893905 datas. push ( td) ;
894906 }
907+ // SAFETY: `datas` is a contiguous slice of valid Objective-C pointers we
908+ // just created; `arrayWithObjects:count:` reads `datas.len()` pointers
909+ // and returns a new autoreleased NSArray that retains each element.
895910 let ns_array: * mut Object = unsafe {
896911 msg_send ! [ ns_array_cls,
897912 arrayWithObjects: datas. as_ptr( )
898913 count: datas. len( ) ]
899914 } ;
915+ // SAFETY: `ns_array` is a valid NSArray pointer returned from
916+ // `arrayWithObjects:count:`. `retain` is a no-arg message on the
917+ // NSObject root class — always safe on a valid pointer.
900918 let _: ( ) = unsafe { msg_send ! [ ns_array, retain] } ;
901919 for td in & datas {
920+ // SAFETY: every `td` in `datas` is balanced with exactly one retain
921+ // from `alloc/init` above. The NSArray took its own retain in
922+ // `arrayWithObjects:count:`, so we can safely release our reference
923+ // here — the array keeps the element alive.
902924 let _: ( ) = unsafe { msg_send ! [ * td, release] } ;
903925 }
904926 Ok ( ns_array)
0 commit comments