Skip to main content

tvm_ffi/collections/
shape.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 *   http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied.  See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19//! [`Shape`], the immutable dimensions of a tensor.
20
21use crate::derive::{Object, ObjectRef};
22use crate::object::ObjectRefAnyCompatible;
23use crate::object::{Object, ObjectArc, ObjectCoreWithExtraItems, PlainObjectRef};
24use crate::{AnyView, Array};
25use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd};
26use std::ops::Deref;
27use tvm_ffi_sys::TVMFFIShapeCell;
28use tvm_ffi_sys::TVMFFITypeIndex as TypeIndex;
29
30//-----------------------------------------------------
31// Shape
32//-----------------------------------------------------
33/// The object behind a [`Shape`].
34#[repr(C)]
35#[derive(Object)]
36#[object(type_key = "ffi.Shape", unsafe type_index = TypeIndex::kTVMFFIShape)]
37pub struct ShapeObj {
38    object: Object,
39    data: TVMFFIShapeCell,
40}
41
42/// An immutable sequence of `i64` dimensions, passed across languages as
43/// `ffi.Shape`. A converting cast, such as a typed function argument, also
44/// takes an `Array` or `List` of integers, as C++ does.
45///
46/// # Examples
47///
48/// ```
49/// use tvm_ffi::Shape;
50///
51/// let shape = Shape::from([2_i64, 3]);
52/// assert_eq!(shape.as_slice(), &[2, 3]);
53/// assert_eq!(shape.len(), 2);
54/// ```
55#[repr(C)]
56#[derive(ObjectRef, Clone)]
57#[object_ref(skip_deref, skip_any_compatible)]
58pub struct Shape {
59    data: ObjectArc<ShapeObj>,
60}
61
62// SAFETY: every `ShapeObj` is a `Shape`; the fallback only builds new shapes.
63unsafe impl ObjectRefAnyCompatible for Shape {
64    #[cold]
65    fn convert_fallback(value: AnyView<'_>) -> Option<Self> {
66        let dims = Array::<i64>::try_from(value).ok()?;
67        Some(Self::from(dims.iter().copied().collect::<Vec<_>>()))
68    }
69}
70
71// SAFETY: as for `ObjectRefAnyCompatible`, every `ShapeObj` is a `Shape`.
72unsafe impl PlainObjectRef for Shape {}
73
74// SAFETY: a `Shape` is immutable.
75unsafe impl Send for Shape {}
76unsafe impl Sync for Shape {}
77
78impl Default for Shape {
79    /// The empty shape, like [`Shape::new`].
80    #[inline]
81    fn default() -> Self {
82        Self::new()
83    }
84}
85
86impl Shape {
87    /// An empty shape.
88    pub fn new() -> Self {
89        let shape_obj = ShapeObj {
90            object: Object::new(),
91            data: TVMFFIShapeCell {
92                data: std::ptr::null(),
93                size: 0,
94            },
95        };
96        Self {
97            data: ObjectArc::new(shape_obj),
98        }
99    }
100
101    /// The dimensions as a slice.
102    pub fn as_slice(&self) -> &[i64] {
103        unsafe {
104            crate::util::slice_from_nullable_raw_parts(self.data.data.data, self.data.data.size)
105        }
106    }
107
108    /// Fill `strides` with the row-major strides of `shape`, wrapping on
109    /// overflow as C++ does: only a zero-element tensor gets that far.
110    pub(crate) fn fill_strides_from_shape<T>(shape: T, strides: &mut [i64])
111    where
112        T: AsRef<[i64]>,
113    {
114        let shape = shape.as_ref();
115        let mut stride = 1;
116        for i in (0..shape.len()).rev() {
117            strides[i] = stride;
118            stride = stride.wrapping_mul(shape[i]);
119        }
120    }
121}
122
123unsafe impl ObjectCoreWithExtraItems for ShapeObj {
124    type ExtraItem = i64;
125    fn extra_items_count(this: &Self) -> usize {
126        this.data.size
127    }
128}
129
130impl<T> From<T> for Shape
131where
132    T: AsRef<[i64]>,
133{
134    fn from(value: T) -> Self {
135        unsafe {
136            let value_slice: &[i64] = value.as_ref();
137            let mut obj_arc = ObjectArc::new_with_extra_items(ShapeObj {
138                object: Object::new(),
139                data: TVMFFIShapeCell {
140                    data: std::ptr::null(),
141                    size: value_slice.len(),
142                },
143            });
144            // The fresh allocation is unique and has not been exposed.
145            let object = ObjectArc::as_mut_ptr(&mut obj_arc);
146            let items = ShapeObj::extra_items_ptr(object);
147            std::ptr::copy_nonoverlapping(value_slice.as_ptr(), items, value_slice.len());
148            (*object).data.data = items;
149            Self { data: obj_arc }
150        }
151    }
152}
153
154impl Deref for Shape {
155    type Target = [i64];
156    #[inline]
157    fn deref(&self) -> &[i64] {
158        self.as_slice()
159    }
160}
161
162impl PartialEq for Shape {
163    #[inline]
164    fn eq(&self, other: &Self) -> bool {
165        self.as_slice() == other.as_slice()
166    }
167}
168
169impl Eq for Shape {}
170
171impl PartialOrd for Shape {
172    #[inline]
173    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
174        Some(self.cmp(other))
175    }
176}
177
178impl Ord for Shape {
179    #[inline]
180    fn cmp(&self, other: &Self) -> Ordering {
181        self.as_slice().cmp(other.as_slice())
182    }
183}