pyo3_pytests/
buf_and_str.rs

1#![cfg(any(not(Py_LIMITED_API), Py_3_11))]
2
3use pyo3::prelude::*;
4
5/// Objects related to PyBuffer and PyStr
6#[pymodule]
7pub mod buf_and_str {
8    use pyo3::buffer::PyBuffer;
9    use pyo3::prelude::*;
10    use pyo3::types::{PyBytes, PyMemoryView, PyString};
11    use std::borrow::Cow;
12
13    /// This is for confirming that PyBuffer does not cause memory leak
14    #[pyclass]
15    struct BytesExtractor {}
16
17    #[pymethods]
18    impl BytesExtractor {
19        #[new]
20        pub fn __new__() -> Self {
21            BytesExtractor {}
22        }
23
24        #[staticmethod]
25        pub fn from_bytes(bytes: &Bound<'_, PyBytes>) -> PyResult<usize> {
26            let byte_vec: Vec<u8> = bytes.extract()?;
27            Ok(byte_vec.len())
28        }
29
30        #[staticmethod]
31        pub fn from_str(string: &Bound<'_, PyString>) -> PyResult<usize> {
32            let rust_string: String = string.extract()?;
33            Ok(rust_string.len())
34        }
35
36        #[staticmethod]
37        pub fn from_str_lossy(string: &Bound<'_, PyString>) -> usize {
38            let rust_string_lossy: String = string.to_string_lossy().to_string();
39            rust_string_lossy.len()
40        }
41
42        #[staticmethod]
43        pub fn from_buffer(buf: &Bound<'_, PyAny>) -> PyResult<usize> {
44            let buf = PyBuffer::<u8>::get(buf)?;
45            Ok(buf.item_count())
46        }
47    }
48
49    #[pyfunction]
50    fn return_memoryview(py: Python<'_>) -> PyResult<Bound<'_, PyMemoryView>> {
51        let bytes = PyBytes::new(py, b"hello world");
52        PyMemoryView::from(&bytes)
53    }
54
55    #[pyfunction]
56    fn map_byte_slice(bytes: &[u8]) -> &[u8] {
57        bytes
58    }
59
60    #[pyfunction]
61    fn map_byte_cow(bytes: Cow<'_, [u8]>) -> Cow<'_, [u8]> {
62        bytes
63    }
64
65    #[pyfunction]
66    fn map_byte_vec(bytes: Vec<u8>) -> Vec<u8> {
67        bytes
68    }
69}