Skip to main content

rustpython_capi/
bytesobject.rs

1use crate::object::define_py_check;
2use crate::util::FfiPtrExt;
3use crate::{PyObject, pystate::with_vm};
4use core::ffi::{CStr, c_char, c_int};
5use rustpython_vm::builtins::PyBytes;
6
7define_py_check!(fn PyBytes_Check, types.bytes_type);
8define_py_check!(exact fn PyBytes_CheckExact, types.bytes_type);
9
10#[unsafe(no_mangle)]
11#[allow(clippy::uninit_vec)]
12pub unsafe extern "C" fn PyBytes_FromStringAndSize(
13    bytes: *mut c_char,
14    len: isize,
15) -> *mut PyObject {
16    with_vm(|vm| {
17        let len = len.try_into().map_err(|_| {
18            vm.new_system_error("Negative size passed to PyBytes_FromStringAndSize")
19        })?;
20
21        let data = if bytes.is_null() {
22            let mut data = Vec::with_capacity(len);
23            unsafe { data.set_len(len) };
24            data
25        } else {
26            unsafe { core::slice::from_raw_parts(bytes as *const u8, len) }.to_vec()
27        };
28
29        Ok(vm.ctx.new_bytes(data))
30    })
31}
32
33#[unsafe(no_mangle)]
34pub unsafe extern "C" fn PyBytes_FromString(s: *const c_char) -> *mut PyObject {
35    with_vm(|vm| {
36        let data = unsafe { CStr::from_ptr(s) }.to_bytes().to_vec();
37        Ok(vm.ctx.new_bytes(data))
38    })
39}
40
41#[unsafe(no_mangle)]
42pub unsafe extern "C" fn PyBytes_FromObject(obj: *mut PyObject) -> *mut PyObject {
43    with_vm(|vm| {
44        let obj = unsafe { obj.assume_borrowed() };
45        if let Some(bytes) = obj.downcast_ref::<PyBytes>() {
46            Ok(bytes.to_owned())
47        } else {
48            obj.try_bytes_like(vm, |bytes| vm.ctx.new_bytes(bytes.to_vec()))
49        }
50    })
51}
52
53#[unsafe(no_mangle)]
54pub unsafe extern "C" fn PyBytes_Size(bytes: *mut PyObject) -> isize {
55    with_vm(|vm| {
56        let bytes = unsafe { bytes.assume_borrowed_and_cast::<PyBytes>(vm) }?;
57        Ok(bytes.as_bytes().len())
58    })
59}
60
61#[unsafe(no_mangle)]
62pub unsafe extern "C" fn PyBytes_AsString(bytes: *mut PyObject) -> *mut c_char {
63    with_vm(|vm| {
64        let bytes = unsafe { bytes.assume_borrowed_and_cast::<PyBytes>(vm) }?;
65        Ok(bytes.as_bytes().as_ptr())
66    })
67}
68
69#[unsafe(no_mangle)]
70pub unsafe extern "C" fn PyBytes_AsStringAndSize(
71    obj: *mut PyObject,
72    buffer: *mut *mut c_char,
73    length: *mut isize,
74) -> c_int {
75    with_vm(|vm| {
76        let data = unsafe { obj.assume_borrowed_and_cast::<PyBytes>(vm)? }.as_bytes();
77
78        if length.is_null() {
79            if data.contains(&0) {
80                return Err(vm.new_value_error("embedded null byte"));
81            }
82        } else {
83            unsafe { *length = data.len() as isize };
84        };
85
86        unsafe { *buffer = data.as_ptr().cast_mut().cast() };
87
88        Ok(())
89    })
90}
91
92#[cfg(test)]
93mod tests {
94    use pyo3::prelude::*;
95    use pyo3::types::PyBytes;
96
97    #[test]
98    fn bytes() {
99        Python::attach(|py| {
100            let bytes = PyBytes::new(py, b"Hello, World!");
101            assert_eq!(bytes.as_bytes(), b"Hello, World!");
102        })
103    }
104
105    #[test]
106    fn bytes_uninit() {
107        Python::attach(|py| {
108            let bytes = PyBytes::new_with(py, 13, |data| {
109                data.copy_from_slice(b"Hello, World!");
110                Ok(())
111            })
112            .unwrap();
113            assert_eq!(bytes.as_bytes(), b"Hello, World!");
114        })
115    }
116}