MCPcopy Index your code
hub / github.com/RustPython/RustPython / cast

Method cast

crates/vm/src/builtins/memory.rs:833–909  ·  view source on GitHub ↗
(&self, args: CastArgs, vm: &VirtualMachine)

Source from the content-addressed store, hash-verified

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 }

Callers 15

vec_into_f64Method · 0.45
strftime_asciiFunction · 0.45
mbcs_encodeFunction · 0.45
mbcs_decodeFunction · 0.45
oem_encodeFunction · 0.45
oem_decodeFunction · 0.45
encode_code_page_errorsFunction · 0.45
decode_code_page_errorsFunction · 0.45
stw_traceFunction · 0.45
dropMethod · 0.45

Calls 13

try_not_releasedMethod · 0.80
is_contiguousMethod · 0.80
is_zero_in_shapeMethod · 0.80
borrow_vecMethod · 0.80
cast_to_1dMethod · 0.80
ErrClass · 0.50
as_sliceMethod · 0.45
lenMethod · 0.45
ndimMethod · 0.45
into_refMethod · 0.45
pushMethod · 0.45
unwrapMethod · 0.45

Tested by

no test coverage detected