Skip to content

Commit ffdf7c6

Browse files
committed
Add PyBytes_AS_STRING, seen in ormsgpack
1 parent dc24203 commit ffdf7c6

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

newsfragments/5121.added.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
Added `_PyLong_Sign`
2+
Add `PyBytes_AS_STRING`

pyo3-ffi/src/cpython/bytesobject.rs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use crate::object::*;
22
use crate::Py_ssize_t;
3-
#[cfg(not(any(PyPy, GraalPy, Py_LIMITED_API)))]
3+
#[cfg(not(Py_LIMITED_API))]
44
use std::os::raw::c_char;
55
use std::os::raw::c_int;
66

@@ -23,3 +23,12 @@ extern "C" {
2323
#[cfg_attr(PyPy, link_name = "_PyPyBytes_Resize")]
2424
pub fn _PyBytes_Resize(bytes: *mut *mut PyObject, newsize: Py_ssize_t) -> c_int;
2525
}
26+
27+
#[cfg(not(Py_LIMITED_API))]
28+
#[inline]
29+
pub unsafe fn PyBytes_AS_STRING(op: *mut PyObject) -> *const c_char {
30+
#[cfg(not(any(PyPy, GraalPy)))]
31+
return &(*op.cast::<PyBytesObject>()).ob_sval as *const c_char;
32+
#[cfg(any(PyPy, GraalPy, Py_LIMITED_API))]
33+
return crate::PyBytes_AsString(op);
34+
}

src/types/bytes.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -365,4 +365,19 @@ mod tests {
365365
assert_eq!(*b, py_string);
366366
})
367367
}
368+
369+
#[test]
370+
#[cfg(not(Py_LIMITED_API))]
371+
fn test_as_string() {
372+
Python::with_gil(|py| {
373+
let b = b"hello, world".as_slice();
374+
let py_bytes = PyBytes::new(py, b);
375+
unsafe {
376+
assert_eq!(
377+
ffi::PyBytes_AsString(py_bytes.as_ptr()) as *const std::os::raw::c_char,
378+
ffi::PyBytes_AS_STRING(py_bytes.as_ptr()) as *const std::os::raw::c_char
379+
);
380+
}
381+
})
382+
}
368383
}

0 commit comments

Comments
 (0)