-
Notifications
You must be signed in to change notification settings - Fork 904
Add conversion for &Cstr, Cstring and Cow<Cstr>
#5482
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
cb00978
Add conversion for `&Cstr`, `Cstring` and `Cow<Cstr>`
bschoenmaeckers de0d073
Add `Cow<Cstr>` roundtrip test
bschoenmaeckers d01a934
fix test
bschoenmaeckers 60a8e04
Cast to pystring before converting
bschoenmaeckers 63ca95a
fix MSRV
bschoenmaeckers 633536a
Safety comment
bschoenmaeckers File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Add conversion for `&Cstr`, `Cstring` and `Cow<Cstr>` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,188 @@ | ||
| use crate::types::PyString; | ||
| use crate::{Borrowed, Bound, FromPyObject, IntoPyObject, PyAny, PyErr, Python}; | ||
| use std::borrow::Cow; | ||
| use std::ffi::{CStr, CString}; | ||
| use std::str::Utf8Error; | ||
| #[cfg(any(Py_3_10, not(Py_LIMITED_API)))] | ||
| use { | ||
| crate::{exceptions::PyValueError, ffi}, | ||
| std::slice, | ||
| }; | ||
|
|
||
| impl<'py> IntoPyObject<'py> for &CStr { | ||
| type Target = PyString; | ||
| type Output = Bound<'py, Self::Target>; | ||
| type Error = Utf8Error; | ||
|
|
||
| #[inline] | ||
| fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { | ||
| self.to_str()?.into_pyobject(py).map_err(|err| match err {}) | ||
| } | ||
| } | ||
|
|
||
| impl<'py> IntoPyObject<'py> for CString { | ||
| type Target = PyString; | ||
| type Output = Bound<'py, Self::Target>; | ||
| type Error = Utf8Error; | ||
|
|
||
| #[inline] | ||
| fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { | ||
| (&*self).into_pyobject(py) | ||
| } | ||
| } | ||
|
|
||
| impl<'py> IntoPyObject<'py> for &CString { | ||
| type Target = PyString; | ||
| type Output = Bound<'py, Self::Target>; | ||
| type Error = Utf8Error; | ||
|
|
||
| #[inline] | ||
| fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { | ||
| (&**self).into_pyobject(py) | ||
| } | ||
| } | ||
|
|
||
| impl<'py> IntoPyObject<'py> for Cow<'_, CStr> { | ||
| type Target = PyString; | ||
| type Output = Bound<'py, Self::Target>; | ||
| type Error = Utf8Error; | ||
|
|
||
| fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { | ||
| (*self).into_pyobject(py) | ||
| } | ||
| } | ||
|
|
||
| impl<'py> IntoPyObject<'py> for &Cow<'_, CStr> { | ||
| type Target = PyString; | ||
| type Output = Bound<'py, Self::Target>; | ||
| type Error = Utf8Error; | ||
|
|
||
| fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { | ||
| (&**self).into_pyobject(py) | ||
| } | ||
| } | ||
|
|
||
| #[cfg(any(Py_3_10, not(Py_LIMITED_API)))] | ||
| impl<'a> FromPyObject<'a, '_> for &'a CStr { | ||
| type Error = PyErr; | ||
|
|
||
| fn extract(obj: Borrowed<'a, '_, PyAny>) -> Result<Self, Self::Error> { | ||
| let obj = obj.cast::<PyString>()?; | ||
| let mut size = 0; | ||
| // SAFETY: obj is a PyString so we can safely call PyUnicode_AsUTF8AndSize | ||
| let ptr = unsafe { ffi::PyUnicode_AsUTF8AndSize(obj.as_ptr(), &mut size) }; | ||
|
|
||
| if ptr.is_null() { | ||
| return Err(PyErr::fetch(obj.py())); | ||
| } | ||
|
|
||
| // SAFETY: PyUnicode_AsUTF8AndSize always returns a NUL-terminated string but size does not | ||
| // include the NUL terminator. So we add 1 to the size to include it. | ||
| let slice = unsafe { slice::from_raw_parts(ptr.cast(), size as usize + 1) }; | ||
|
|
||
| CStr::from_bytes_with_nul(slice).map_err(|err| PyValueError::new_err(err.to_string())) | ||
| } | ||
| } | ||
|
|
||
| impl<'a> FromPyObject<'a, '_> for Cow<'a, CStr> { | ||
| type Error = PyErr; | ||
|
|
||
| fn extract(obj: Borrowed<'a, '_, PyAny>) -> Result<Self, Self::Error> { | ||
| #[cfg(any(Py_3_10, not(Py_LIMITED_API)))] | ||
| { | ||
| Ok(Cow::Borrowed(obj.extract::<&CStr>()?)) | ||
| } | ||
|
|
||
| #[cfg(not(any(Py_3_10, not(Py_LIMITED_API))))] | ||
| { | ||
| Ok(Cow::Owned(obj.extract::<CString>()?)) | ||
| } | ||
| } | ||
| } | ||
| impl FromPyObject<'_, '_> for CString { | ||
| type Error = PyErr; | ||
|
|
||
| fn extract(obj: Borrowed<'_, '_, PyAny>) -> Result<Self, Self::Error> { | ||
| #[cfg(any(Py_3_10, not(Py_LIMITED_API)))] | ||
| { | ||
| Ok(obj.extract::<&CStr>()?.to_owned()) | ||
| } | ||
|
|
||
| #[cfg(not(any(Py_3_10, not(Py_LIMITED_API))))] | ||
| { | ||
| CString::new(&*obj.cast::<PyString>()?.to_cow()?).map_err(Into::into) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| use crate::types::string::PyStringMethods; | ||
| use crate::types::PyAnyMethods; | ||
| use crate::Python; | ||
|
|
||
| #[test] | ||
| fn test_into_pyobject() { | ||
| Python::attach(|py| { | ||
| let s = "Hello, Python!"; | ||
| let cstr = CString::new(s).unwrap(); | ||
|
|
||
| let py_string = cstr.as_c_str().into_pyobject(py).unwrap(); | ||
| assert_eq!(py_string.to_cow().unwrap(), s); | ||
|
|
||
| let py_string = cstr.into_pyobject(py).unwrap(); | ||
| assert_eq!(py_string.to_cow().unwrap(), s); | ||
| }) | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_extract_with_nul_error() { | ||
| Python::attach(|py| { | ||
| let s = "Hello\0Python"; | ||
| let py_string = s.into_pyobject(py).unwrap(); | ||
|
|
||
| #[cfg(any(Py_3_10, not(Py_LIMITED_API)))] | ||
| { | ||
| let err = py_string.extract::<&CStr>(); | ||
| assert!(err.is_err()); | ||
| } | ||
|
|
||
| let err = py_string.extract::<CString>(); | ||
| assert!(err.is_err()); | ||
| }) | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_extract_cstr_and_cstring() { | ||
| Python::attach(|py| { | ||
| let s = "Hello, world!"; | ||
| let cstr = CString::new(s).unwrap(); | ||
| let py_string = cstr.as_c_str().into_pyobject(py).unwrap(); | ||
|
|
||
| #[cfg(any(Py_3_10, not(Py_LIMITED_API)))] | ||
| { | ||
| let extracted_cstr: &CStr = py_string.extract().unwrap(); | ||
| assert_eq!(extracted_cstr.to_str().unwrap(), s); | ||
| } | ||
|
|
||
| let extracted_cstring: CString = py_string.extract().unwrap(); | ||
| assert_eq!(extracted_cstring.to_str().unwrap(), s); | ||
| }) | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_cow_roundtrip() { | ||
| Python::attach(|py| { | ||
| let s = "Hello, world!"; | ||
| let cstr = CString::new(s).unwrap(); | ||
| let cow: Cow<'_, CStr> = Cow::Borrowed(cstr.as_c_str()); | ||
|
|
||
| let py_string = cow.into_pyobject(py).unwrap(); | ||
| assert_eq!(py_string.to_cow().unwrap(), s); | ||
|
|
||
| let roundtripped: Cow<'_, CStr> = py_string.extract().unwrap(); | ||
| assert_eq!(roundtripped.as_ref(), cstr.as_c_str()); | ||
| }) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,6 @@ | ||
| mod array; | ||
| mod cell; | ||
| mod cstring; | ||
| mod ipaddr; | ||
| mod map; | ||
| mod num; | ||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.