(&self, args: CastArgs, vm: &VirtualMachine)
| 831 | |
| 832 | #[pymethod] |
| 833 | fn cast(&self, args: CastArgs, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { |
| 834 | self.try_not_released(vm)?; |
| 835 | if !self.desc.is_contiguous() { |
| 836 | return Err(vm.new_type_error("memoryview: casts are restricted to C-contiguous views")); |
| 837 | } |
| 838 | |
| 839 | let CastArgs { format, shape } = args; |
| 840 | |
| 841 | if let OptionalArg::Present(shape) = shape { |
| 842 | if self.desc.is_zero_in_shape() { |
| 843 | return Err(vm.new_type_error( |
| 844 | "memoryview: cannot cast view with zeros in shape or strides", |
| 845 | )); |
| 846 | } |
| 847 | |
| 848 | let tup; |
| 849 | let list; |
| 850 | let list_borrow; |
| 851 | let shape = match shape { |
| 852 | Either::A(shape) => { |
| 853 | tup = shape; |
| 854 | tup.as_slice() |
| 855 | } |
| 856 | Either::B(shape) => { |
| 857 | list = shape; |
| 858 | list_borrow = list.borrow_vec(); |
| 859 | &list_borrow |
| 860 | } |
| 861 | }; |
| 862 | |
| 863 | let shape_ndim = shape.len(); |
| 864 | // TODO: MAX_NDIM |
| 865 | if self.desc.ndim() != 1 && shape_ndim != 1 { |
| 866 | return Err(vm.new_type_error("memoryview: cast must be 1D -> ND or ND -> 1D")); |
| 867 | } |
| 868 | |
| 869 | let mut other = self.cast_to_1d(format, vm)?; |
| 870 | let itemsize = other.desc.itemsize; |
| 871 | |
| 872 | // 0 ndim is single item |
| 873 | if shape_ndim == 0 { |
| 874 | other.desc.dim_desc = vec![]; |
| 875 | other.desc.len = itemsize; |
| 876 | return Ok(other.into_ref(&vm.ctx)); |
| 877 | } |
| 878 | |
| 879 | let mut product_shape = itemsize; |
| 880 | let mut dim_descriptor = Vec::with_capacity(shape_ndim); |
| 881 | |
| 882 | for x in shape { |
| 883 | let x = usize::try_from_borrowed_object(vm, x)?; |
| 884 | |
| 885 | if x > isize::MAX as usize / product_shape { |
| 886 | return Err(vm.new_value_error("memoryview.cast(): product(shape) > SSIZE_MAX")); |
| 887 | } |
| 888 | product_shape *= x; |
| 889 | dim_descriptor.push((x, 0, 0)); |
| 890 | } |
no test coverage detected