forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbytesobject.rs
More file actions
73 lines (64 loc) · 1.94 KB
/
Copy pathbytesobject.rs
File metadata and controls
73 lines (64 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use crate::PyObject;
use crate::object::define_py_check;
use crate::pystate::with_vm;
use core::ffi::c_char;
use rustpython_vm::builtins::PyBytes;
define_py_check!(fn PyBytes_Check, types.bytes_type);
define_py_check!(exact fn PyBytes_CheckExact, types.bytes_type);
#[unsafe(no_mangle)]
#[allow(clippy::uninit_vec)]
pub unsafe extern "C" fn PyBytes_FromStringAndSize(
bytes: *mut c_char,
len: isize,
) -> *mut PyObject {
with_vm(|vm| {
let len = len.try_into().map_err(|_| {
vm.new_system_error("Negative size passed to PyBytes_FromStringAndSize")
})?;
let data = if bytes.is_null() {
let mut data = Vec::with_capacity(len);
unsafe { data.set_len(len) };
data
} else {
unsafe { core::slice::from_raw_parts(bytes as *const u8, len) }.to_vec()
};
Ok(vm.ctx.new_bytes(data))
})
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyBytes_Size(bytes: *mut PyObject) -> isize {
with_vm(|vm| {
let bytes = unsafe { &*bytes }.try_downcast_ref::<PyBytes>(vm)?;
Ok(bytes.as_bytes().len())
})
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyBytes_AsString(bytes: *mut PyObject) -> *mut c_char {
with_vm(|vm| {
let bytes = unsafe { &*bytes }.try_downcast_ref::<PyBytes>(vm)?;
Ok(bytes.as_bytes().as_ptr())
})
}
#[cfg(false)]
mod tests {
use pyo3::prelude::*;
use pyo3::types::PyBytes;
#[test]
fn test_bytes() {
Python::attach(|py| {
let bytes = PyBytes::new(py, b"Hello, World!");
assert_eq!(bytes.as_bytes(), b"Hello, World!");
})
}
#[test]
fn test_bytes_uninit() {
Python::attach(|py| {
let bytes = PyBytes::new_with(py, 13, |data| {
data.copy_from_slice(b"Hello, World!");
Ok(())
})
.unwrap();
assert_eq!(bytes.as_bytes(), b"Hello, World!");
})
}
}