dlpark 0.8.0-alpha.3

dlpack Rust binding for Python
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
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
777
778
779
//! Deferred DLPack builder.
//!
//! The metadata type determines the allocation layout, whether metadata is
//! copied or borrowed, and whether building can fail. The builder itself stays
//! on the stack and only collects the scalar `DLTensor` fields.

use crate::{
    DlpackFlags, ManagedBox, ManagedTensorBase, OpaqueContext,
    ffi::{DLDataType, DLDevice},
    metadata::{BorrowedArray, BorrowedSlice, FromContext, InfallibleMetadata, Metadata},
};
use std::{ffi::c_void, ptr::NonNull};

pub use crate::metadata::Error;

/// Deferred construction of a DLPack managed tensor.
///
/// `C` is transferred into `manager_ctx` and keeps the data allocation alive.
/// `L` controls shape/stride storage, allocation layout, and whether building
/// can fail. The managed tensor ABI is selected by the type parameter passed
/// to `build` or `try_build`.
pub struct Builder<C, L> {
    ctx: C,
    metadata: L,
    fields: TensorFields,
}

#[derive(Clone, Copy)]
struct TensorFields {
    data: *mut c_void,
    device: DLDevice,
    dtype: DLDataType,
    byte_offset: u64,
    flags: DlpackFlags,
}

impl<C, L> Builder<C, L> {
    /// Creates a builder with CPU device, null data, default dtype, zero byte
    /// offset, and empty flags.
    #[inline]
    pub fn new(ctx: C, metadata: L) -> Self {
        Self {
            ctx,
            metadata,
            fields: TensorFields {
                data: std::ptr::null_mut(),
                device: DLDevice::CPU,
                dtype: DLDataType::default(),
                byte_offset: 0,
                flags: DlpackFlags::empty(),
            },
        }
    }

    /// Sets the base data pointer stored in `DLTensor`.
    ///
    /// The context must keep the pointed-to allocation valid until the
    /// managed tensor deleter runs.
    #[inline]
    pub fn data(mut self, data: *mut c_void) -> Self {
        self.fields.data = data;
        self
    }

    /// Replaces the shape/stride storage strategy without changing scalar
    /// tensor fields or the owning context.
    #[inline]
    pub fn metadata<L2>(self, metadata: L2) -> Builder<C, L2> {
        let Self { ctx, fields, .. } = self;
        Builder {
            ctx,
            metadata,
            fields,
        }
    }

    /// Sets the DLPack device descriptor.
    #[inline]
    pub fn device(mut self, device: DLDevice) -> Self {
        self.fields.device = device;
        self
    }

    /// Sets the DLPack element type descriptor.
    #[inline]
    pub fn dtype(mut self, dtype: DLDataType) -> Self {
        self.fields.dtype = dtype;
        self
    }

    /// Sets the byte offset from the base data pointer to the first element.
    #[inline]
    pub fn byte_offset(mut self, byte_offset: u64) -> Self {
        self.fields.byte_offset = byte_offset;
        self
    }

    /// Sets DLPack flags, erroring if this would newly assert
    /// [`DlpackFlags::IS_COPIED`] (turn it on when it wasn't already set on
    /// this builder). See [`Self::flags_unchecked`].
    #[inline]
    pub fn flags(mut self, flags: DlpackFlags) -> Result<Self, crate::tensor::Error> {
        if flags.newly_asserts_is_copied(self.fields.flags) {
            return Err(crate::tensor::Error::CannotAssertIsCopied);
        }
        self.fields.flags = flags;
        Ok(self)
    }

    /// Adds DLPack flags without clearing flags already set on the builder.
    ///
    /// This errors if the operation would newly assert
    /// [`DlpackFlags::IS_COPIED`]. Use [`Self::insert_flags_unchecked`] when
    /// the caller can prove the required ownership guarantee.
    #[inline]
    pub fn insert_flags(mut self, flags: DlpackFlags) -> Result<Self, crate::tensor::Error> {
        if flags.newly_asserts_is_copied(self.fields.flags) {
            return Err(crate::tensor::Error::CannotAssertIsCopied);
        }
        self.fields.flags.insert(flags);
        Ok(self)
    }

    /// Sets DLPack flags verbatim, including [`DlpackFlags::IS_COPIED`].
    ///
    /// # Safety
    ///
    /// If `flags` includes `IS_COPIED`, the caller must ensure that no other
    /// reference to the tensor's data exists — see
    /// [`ManagedTensorBase::set_flags_unchecked`].
    #[inline]
    pub unsafe fn flags_unchecked(mut self, flags: DlpackFlags) -> Self {
        self.fields.flags = flags;
        self
    }

    /// Adds DLPack flags without clearing flags already set on the builder.
    ///
    /// # Safety
    ///
    /// If `flags` includes `IS_COPIED`, the caller must ensure that no other
    /// reference to the tensor's data exists.
    #[inline]
    pub unsafe fn insert_flags_unchecked(mut self, flags: DlpackFlags) -> Self {
        self.fields.flags.insert(flags);
        self
    }
}

impl<C> Builder<C, ()> {
    /// Creates a builder whose shape and strides are derived from its context
    /// during allocation.
    ///
    /// The closure is invoked after the context has completed its final move
    /// into the build operation. Its returned slices are converted to `i64`
    /// and copied before the context is transferred to `manager_ctx`.
    #[inline]
    pub fn from_context<F, A, B>(ctx: C, derive: F) -> Builder<C, FromContext<F, A, B>>
    where
        A: Copy + TryInto<i64>,
        B: Copy + TryInto<i64>,
        F: FnOnce(&C) -> (&[A], &[B]),
    {
        Builder::new(ctx, FromContext::new(derive))
    }
}

impl<C, L> Builder<C, L>
where
    C: OpaqueContext,
    L: Metadata,
{
    /// Tries to build the tensor and transfer ownership to a raw DLPack
    /// pointer.
    #[inline]
    pub fn try_build_raw<M>(self) -> Result<*mut M, L::Error>
    where
        M: ManagedTensorBase,
    {
        let Self {
            ctx,
            metadata,
            fields,
        } = self;
        let managed = metadata.try_allocate::<C, M>(ctx)?;
        Ok(unsafe { finish(managed, fields) }.as_ptr())
    }

    /// Validates runtime metadata, allocates the managed tensor, and returns
    /// an owning handle.
    #[inline]
    pub fn try_build<M>(self) -> Result<ManagedBox<M>, L::Error>
    where
        M: ManagedTensorBase,
    {
        self.try_build_raw()
            .map(|raw| unsafe { ManagedBox::new_unchecked(raw) })
    }

    /// Builds the tensor without checking runtime metadata invariants.
    ///
    /// # Safety
    ///
    /// The metadata must satisfy the invariants required by its unchecked
    /// allocator. For dynamic metadata this includes matching shape/strides
    /// lengths and `ndim <= i32::MAX`; violating those requirements may cause
    /// out-of-bounds reads or an invalid `DLTensor`.
    #[inline]
    pub unsafe fn build_raw_unchecked<M>(self) -> *mut M
    where
        M: ManagedTensorBase,
    {
        let Self {
            ctx,
            metadata,
            fields,
        } = self;
        let managed = unsafe { metadata.allocate_unchecked::<C, M>(ctx) };
        unsafe { finish(managed, fields) }.as_ptr()
    }

    /// Builds the tensor without checking runtime metadata invariants.
    ///
    /// # Safety
    ///
    /// The metadata must satisfy the invariants required by its unchecked
    /// allocator. For dynamic metadata this includes matching shape/strides
    /// lengths and `ndim <= i32::MAX`; violating those requirements may cause
    /// out-of-bounds reads or an invalid `DLTensor`.
    #[inline]
    pub unsafe fn build_unchecked<M>(self) -> ManagedBox<M>
    where
        M: ManagedTensorBase,
    {
        unsafe { ManagedBox::new_unchecked(self.build_raw_unchecked()) }
    }
}

impl<C, F, A, B> Builder<C, FromContext<F, A, B>>
where
    C: OpaqueContext,
    A: Copy + TryInto<i64>,
    B: Copy + TryInto<i64>,
    F: FnOnce(&C) -> (&[A], &[B]),
{
    /// Derives, validates, and copies metadata, then transfers ownership to a
    /// raw DLPack pointer.
    #[inline]
    pub fn try_build_raw<M>(self) -> Result<*mut M, Error>
    where
        M: ManagedTensorBase,
    {
        let Self {
            ctx,
            metadata,
            fields,
        } = self;
        let managed =
            crate::metadata::try_allocate_generic_from_context(ctx, metadata.into_inner())?;
        Ok(unsafe { finish(managed, fields) }.as_ptr())
    }

    /// Derives metadata from the context and returns an owning managed tensor.
    #[inline]
    pub fn try_build<M>(self) -> Result<ManagedBox<M>, Error>
    where
        M: ManagedTensorBase,
    {
        self.try_build_raw()
            .map(|raw| unsafe { ManagedBox::new_unchecked(raw) })
    }
}

impl<C, L> Builder<C, L>
where
    C: OpaqueContext,
    L: InfallibleMetadata,
{
    /// Builds the tensor and transfers ownership to a raw DLPack pointer.
    #[inline]
    pub fn build_raw<M>(self) -> *mut M
    where
        M: ManagedTensorBase,
    {
        let Self {
            ctx,
            metadata,
            fields,
        } = self;
        let managed = metadata.allocate::<C, M>(ctx);
        unsafe { finish(managed, fields) }.as_ptr()
    }

    /// Builds an owning managed tensor when the metadata layout is infallible.
    #[inline]
    pub fn build<M>(self) -> ManagedBox<M>
    where
        M: ManagedTensorBase,
    {
        unsafe { ManagedBox::new_unchecked(self.build_raw()) }
    }
}

impl<C, const N: usize> Builder<C, BorrowedArray<'_, N>>
where
    C: OpaqueContext,
{
    /// Builds the tensor and transfers ownership to a raw DLPack pointer.
    ///
    /// # Safety
    ///
    /// The borrowed arrays must outlive the returned managed tensor and must
    /// not be mutated through the DLPack `shape`/`strides` pointers while it
    /// is alive.
    #[inline]
    pub unsafe fn build_raw<M>(self) -> *mut M
    where
        M: ManagedTensorBase,
    {
        let Self {
            ctx,
            metadata,
            fields,
        } = self;
        let managed = unsafe { metadata.allocate::<C, M>(ctx) };
        unsafe { finish(managed, fields) }.as_ptr()
    }

    /// Builds a tensor that points to caller-owned shape and strides arrays.
    ///
    /// # Safety
    ///
    /// The borrowed arrays must outlive the returned managed tensor and must
    /// not be mutated through the DLPack `shape`/`strides` pointers while it
    /// is alive.
    #[inline]
    pub unsafe fn build<M>(self) -> ManagedBox<M>
    where
        M: ManagedTensorBase,
    {
        unsafe { ManagedBox::new_unchecked(self.build_raw()) }
    }

    /// Tries to build the tensor and transfer ownership to a raw DLPack
    /// pointer.
    ///
    /// # Safety
    ///
    /// The borrowed arrays must outlive the returned managed tensor and must
    /// not be mutated through the DLPack `shape`/`strides` pointers while it
    /// is alive.
    #[inline]
    pub unsafe fn try_build_raw<M>(self) -> Result<*mut M, std::convert::Infallible>
    where
        M: ManagedTensorBase,
    {
        Ok(unsafe { self.build_raw() })
    }

    /// Tries to build a tensor that points to caller-owned shape and strides
    /// arrays.
    ///
    /// # Safety
    ///
    /// The borrowed arrays must outlive the returned managed tensor and must
    /// not be mutated through the DLPack `shape`/`strides` pointers while it
    /// is alive.
    #[inline]
    pub unsafe fn try_build<M>(self) -> Result<ManagedBox<M>, std::convert::Infallible>
    where
        M: ManagedTensorBase,
    {
        Ok(unsafe { self.build() })
    }
}

impl<C> Builder<C, BorrowedSlice<'_>>
where
    C: OpaqueContext,
{
    /// Tries to build the tensor and transfer ownership to a raw DLPack
    /// pointer.
    ///
    /// # Safety
    ///
    /// The borrowed slices must outlive the returned managed tensor and must
    /// not be mutated through the DLPack `shape`/`strides` pointers while it
    /// is alive.
    #[inline]
    pub unsafe fn try_build_raw<M>(self) -> Result<*mut M, Error>
    where
        M: ManagedTensorBase,
    {
        let Self {
            ctx,
            metadata,
            fields,
        } = self;
        let managed = unsafe { metadata.allocate::<C, M>(ctx)? };
        Ok(unsafe { finish(managed, fields) }.as_ptr())
    }

    /// Builds a tensor that points to caller-owned shape and strides slices.
    ///
    /// # Safety
    ///
    /// The borrowed slices must outlive the returned managed tensor and must
    /// not be mutated through the DLPack `shape`/`strides` pointers while it
    /// is alive.
    #[inline]
    pub unsafe fn try_build<M>(self) -> Result<ManagedBox<M>, Error>
    where
        M: ManagedTensorBase,
    {
        unsafe { self.try_build_raw() }.map(|raw| unsafe { ManagedBox::new_unchecked(raw) })
    }

    /// Builds the tensor without checking runtime metadata invariants.
    ///
    /// # Safety
    ///
    /// The borrowed slices must outlive the returned managed tensor, and shape
    /// and strides must have the same length with `ndim` fitting in `i32`.
    /// They must not be mutated through the DLPack `shape`/`strides` pointers
    /// while the managed tensor is alive.
    #[inline]
    pub unsafe fn build_raw_unchecked<M>(self) -> *mut M
    where
        M: ManagedTensorBase,
    {
        let Self {
            ctx,
            metadata,
            fields,
        } = self;
        let managed = unsafe { metadata.allocate_unchecked::<C, M>(ctx) };
        unsafe { finish(managed, fields) }.as_ptr()
    }

    /// Builds a tensor that points to caller-owned shape and strides slices
    /// without checking runtime metadata invariants.
    ///
    /// # Safety
    ///
    /// The borrowed slices must outlive the returned managed tensor, and shape
    /// and strides must have the same length with `ndim` fitting in `i32`.
    /// They must not be mutated through the DLPack `shape`/`strides` pointers
    /// while the managed tensor is alive.
    #[inline]
    pub unsafe fn build_unchecked<M>(self) -> ManagedBox<M>
    where
        M: ManagedTensorBase,
    {
        unsafe { ManagedBox::new_unchecked(self.build_raw_unchecked()) }
    }
}

#[inline]
unsafe fn finish<M>(mut managed: NonNull<M>, fields: TensorFields) -> NonNull<M>
where
    M: ManagedTensorBase,
{
    unsafe {
        let managed_ref = managed.as_mut();
        {
            let tensor = managed_ref.tensor_mut();
            tensor.data = fields.data;
            tensor.device = fields.device;
            tensor.dtype = fields.dtype;
            tensor.byte_offset = fields.byte_offset;
        }
        managed_ref.set_flags_unchecked(fields.flags);
    }
    managed
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        ffi::{DLDeviceType, DLManagedTensor, DLManagedTensorVersioned},
        metadata,
    };
    use std::sync::{
        Arc,
        atomic::{AtomicUsize, Ordering},
    };

    #[derive(Clone)]
    struct TestContext {
        drop_count: Arc<AtomicUsize>,
    }

    unsafe impl OpaqueContext for TestContext {
        fn into_raw(self) -> *mut c_void {
            Box::into_raw(Box::new(self)).cast()
        }

        unsafe fn drop_raw(raw: *mut c_void) {
            if !raw.is_null() {
                let boxed = unsafe { Box::from_raw(raw.cast::<TestContext>()) };
                boxed.drop_count.fetch_add(1, Ordering::SeqCst);
            }
        }
    }

    fn context() -> (TestContext, Arc<AtomicUsize>) {
        let drop_count = Arc::new(AtomicUsize::new(0));
        (
            TestContext {
                drop_count: drop_count.clone(),
            },
            drop_count,
        )
    }

    #[test]
    fn copied_array_build_is_infallible() {
        let (ctx, drop_count) = context();
        let shape = [1, 2, 3];
        let strides = [6, 3, 1];

        let tensor: ManagedBox<DLManagedTensor> =
            Builder::new(ctx, metadata::CopiedArray::new(&shape, &strides)).build();

        assert_eq!(tensor.tensor().ndim, 3);
        assert_eq!(tensor.shape().unwrap(), shape);
        assert_eq!(tensor.strides().unwrap().unwrap(), strides);
        assert_eq!(tensor.tensor().device.device_type, DLDeviceType::CPU);
        drop(tensor);
        assert_eq!(drop_count.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn copied_array_build_raw_transfers_ownership() {
        let (ctx, drop_count) = context();
        let shape = [2, 3];
        let strides = [3, 1];

        let raw = Builder::new(ctx, metadata::CopiedArray::new(&shape, &strides))
            .build_raw::<DLManagedTensor>();

        assert_eq!(drop_count.load(Ordering::SeqCst), 0);
        let tensor = unsafe { ManagedBox::new_unchecked(raw) };
        assert_eq!(tensor.shape().unwrap(), shape);
        drop(tensor);
        assert_eq!(drop_count.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn copied_slice_build_validates_lengths() {
        let (ctx, _) = context();
        let result: Result<ManagedBox<DLManagedTensor>, Error> =
            Builder::new(ctx, metadata::CopiedSlice::new(&[1, 2], &[2, 1, 1])).try_build();

        assert!(matches!(
            result,
            Err(Error::MismatchedLength {
                shape_len: 2,
                strides_len: 3
            })
        ));
    }

    #[test]
    fn copied_slice_try_build_raw_transfers_ownership() {
        let (ctx, drop_count) = context();
        let shape = [2, 3];
        let strides = [3, 1];

        let raw = Builder::new(ctx, metadata::CopiedSlice::new(&shape, &strides))
            .try_build_raw::<DLManagedTensor>()
            .unwrap();

        let tensor = unsafe { ManagedBox::new_unchecked(raw) };
        assert_eq!(tensor.strides().unwrap().unwrap(), strides);
        drop(tensor);
        assert_eq!(drop_count.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn generic_array_converts_metadata_without_temporary_i64_arrays() {
        let (ctx, _) = context();
        let shape = [2u32, 3];
        let strides = [3isize, 1];

        let tensor: ManagedBox<DLManagedTensor> =
            Builder::new(ctx, metadata::GenericArray::new(&shape, &strides))
                .try_build()
                .unwrap();

        assert_eq!(tensor.shape().unwrap(), &[2, 3]);
        assert_eq!(tensor.strides().unwrap().unwrap(), &[3, 1]);
    }

    #[test]
    fn generic_slice_converts_metadata_and_validates_lengths() {
        let (ctx, _) = context();
        let shape = vec![2u32, 3];
        let strides = vec![3isize, 1];

        let tensor: ManagedBox<DLManagedTensor> =
            Builder::new(ctx, metadata::GenericSlice::new(&shape, &strides))
                .try_build()
                .unwrap();
        assert_eq!(tensor.shape().unwrap(), &[2, 3]);
        assert_eq!(tensor.strides().unwrap().unwrap(), &[3, 1]);

        let (ctx, _) = context();
        let result: Result<ManagedBox<DLManagedTensor>, Error> =
            Builder::new(ctx, metadata::GenericSlice::new(&[1usize, 2], &[1isize])).try_build();
        assert!(matches!(result, Err(Error::MismatchedLength { .. })));
    }

    #[test]
    fn context_metadata_is_derived_during_build() {
        struct Context {
            shape: Vec<usize>,
            strides: Vec<isize>,
        }

        let builder = Builder::from_context(
            Box::new(Context {
                shape: vec![2, 3],
                strides: vec![3, 1],
            }),
            |ctx| (ctx.shape.as_slice(), ctx.strides.as_slice()),
        );
        let tensor = builder.try_build::<DLManagedTensor>().unwrap();

        assert_eq!(tensor.shape().unwrap(), &[2, 3]);
        assert_eq!(tensor.strides().unwrap().unwrap(), &[3, 1]);
    }

    #[test]
    fn generic_metadata_reports_conversion_axis() {
        let (ctx, drop_count) = context();
        let result: Result<ManagedBox<DLManagedTensor>, Error> = Builder::new(
            ctx,
            metadata::GenericArray::new(&[1u64, i64::MAX as u64 + 1], &[1u64, 1]),
        )
        .try_build();

        assert!(matches!(result, Err(Error::ShapeValueOverflow { axis: 1 })));
        assert_eq!(Arc::strong_count(&drop_count), 1);
    }

    #[test]
    fn borrowed_array_reuses_metadata() {
        let (ctx, _) = context();
        let shape = [2, 4];
        let strides = [4, 1];

        let tensor: ManagedBox<DLManagedTensor> =
            unsafe { Builder::new(ctx, metadata::BorrowedArray::new(&shape, &strides)).build() };

        assert_eq!(tensor.tensor().shape, shape.as_ptr().cast_mut());
        assert_eq!(tensor.tensor().strides, strides.as_ptr().cast_mut());
    }

    #[test]
    fn borrowed_slice_build_validates_lengths() {
        let (ctx, _) = context();
        let result: Result<ManagedBox<DLManagedTensor>, Error> = unsafe {
            Builder::new(ctx, metadata::BorrowedSlice::new(&[1, 2], &[2, 1, 1])).try_build()
        };

        assert!(matches!(
            result,
            Err(Error::MismatchedLength {
                shape_len: 2,
                strides_len: 3
            })
        ));
    }

    #[test]
    fn scalar_fields_and_versioned_flags_are_applied() {
        let (ctx, _) = context();
        let shape = [3];
        let strides = [1];
        let data = NonNull::<u8>::dangling().as_ptr().cast();

        let tensor: ManagedBox<DLManagedTensorVersioned> =
            Builder::new(ctx, metadata::CopiedArray::new(&shape, &strides))
                .data(data)
                .byte_offset(4)
                .flags(DlpackFlags::READ_ONLY)
                .unwrap()
                .build();

        assert_eq!(tensor.tensor().data, data);
        assert_eq!(tensor.tensor().byte_offset, 4);
        assert_eq!(tensor.flags(), DlpackFlags::READ_ONLY);
    }

    #[test]
    fn flags_rejects_newly_asserting_is_copied() {
        let (ctx, _) = context();

        let error = match Builder::new(ctx, metadata::CopiedArray::new(&[3], &[1]))
            .flags(DlpackFlags::READ_ONLY | DlpackFlags::IS_COPIED)
        {
            Ok(_) => panic!("newly asserting IS_COPIED through the safe setter should fail"),
            Err(error) => error,
        };

        assert!(matches!(error, crate::tensor::Error::CannotAssertIsCopied));
    }

    #[test]
    fn insert_flags_rejects_newly_asserting_is_copied() {
        let (ctx, _) = context();

        let error = match Builder::new(ctx, metadata::CopiedArray::new(&[3], &[1]))
            .insert_flags(DlpackFlags::IS_COPIED)
        {
            Ok(_) => panic!("newly inserting IS_COPIED through the safe setter should fail"),
            Err(error) => error,
        };

        assert!(matches!(error, crate::tensor::Error::CannotAssertIsCopied));
    }

    #[test]
    fn insert_flags_preserves_existing_flags() {
        let (ctx, _) = context();
        let builder = unsafe {
            Builder::new(ctx, metadata::CopiedArray::new(&[3], &[1]))
                .flags_unchecked(DlpackFlags::IS_COPIED)
        };
        let tensor: ManagedBox<DLManagedTensorVersioned> = builder
            .insert_flags(DlpackFlags::READ_ONLY)
            .unwrap()
            .build();

        assert_eq!(
            tensor.flags(),
            DlpackFlags::IS_COPIED | DlpackFlags::READ_ONLY
        );
    }

    #[test]
    fn flags_unchecked_keeps_is_copied() {
        let (ctx, _) = context();

        let tensor: ManagedBox<DLManagedTensorVersioned> = unsafe {
            Builder::new(ctx, metadata::CopiedArray::new(&[3], &[1]))
                .flags_unchecked(DlpackFlags::READ_ONLY | DlpackFlags::IS_COPIED)
        }
        .build();

        assert_eq!(
            tensor.flags(),
            DlpackFlags::READ_ONLY | DlpackFlags::IS_COPIED
        );
    }

    #[test]
    fn metadata_replaces_layout_and_keeps_scalar_fields() {
        let (ctx, _) = context();
        let old_shape = [1];
        let old_strides = [1];
        let new_shape = [2, 3];
        let new_strides = [3, 1];
        let data = NonNull::<u8>::dangling().as_ptr().cast();

        let tensor: ManagedBox<DLManagedTensor> =
            Builder::new(ctx, metadata::CopiedArray::new(&old_shape, &old_strides))
                .data(data)
                .metadata(metadata::CopiedArray::new(&new_shape, &new_strides))
                .build();

        assert_eq!(tensor.tensor().data, data);
        assert_eq!(tensor.tensor().ndim, 2);
        assert_eq!(tensor.shape().unwrap(), new_shape);
        assert_eq!(tensor.strides().unwrap().unwrap(), new_strides);
    }
}