pyo3_pytests/
buf_and_str.rs

1#![cfg(not(Py_LIMITED_API))]
2
3//! Objects related to PyBuffer and PyStr
4use pyo3::buffer::PyBuffer;
5use pyo3::prelude::*;
6use pyo3::types::{PyBytes, PyMemoryView, PyString};
7
8/// This is for confirming that PyBuffer does not cause memory leak
9#[pyclass]
10struct BytesExtractor {}
11
12#[pymethods]
13impl BytesExtractor {
14    #[new]
15    pub fn __new__() -> Self {
16        BytesExtractor {}
17    }
18
19    #[staticmethod]
20    pub fn from_bytes(bytes: &Bound<'_, PyBytes>) -> PyResult<usize> {
21        let byte_vec: Vec<u8> = bytes.extract()?;
22        Ok(byte_vec.len())
23    }
24
25    #[staticmethod]
26    pub fn from_str(string: &Bound<'_, PyString>) -> PyResult<usize> {
27        let rust_string: String = string.extract()?;
28        Ok(rust_string.len())
29    }
30
31    #[staticmethod]
32    pub fn from_str_lossy(string: &Bound<'_, PyString>) -> usize {
33        let rust_string_lossy: String = string.to_string_lossy().to_string();
34        rust_string_lossy.len()
35    }
36
37    #[staticmethod]
38    pub fn from_buffer(buf: &Bound<'_, PyAny>) -> PyResult<usize> {
39        let buf = PyBuffer::<u8>::get(buf)?;
40        Ok(buf.item_count())
41    }
42}
43
44#[pyfunction]
45fn return_memoryview(py: Python<'_>) -> PyResult<Bound<'_, PyMemoryView>> {
46    let bytes = PyBytes::new(py, b"hello world");
47    PyMemoryView::from(&bytes)
48}
49
50#[pymodule(gil_used = false)]
51pub fn buf_and_str(m: &Bound<'_, PyModule>) -> PyResult<()> {
52    m.add_class::<BytesExtractor>()?;
53    m.add_function(wrap_pyfunction!(return_memoryview, m)?)?;
54    Ok(())
55}
⚠️ Internal Docs ⚠️ Not Public API 👉 Official Docs Here