@@ -6,7 +6,6 @@ use std::str::Utf8Error;
66#[ cfg( any( Py_3_10 , not( Py_LIMITED_API ) ) ) ]
77use {
88 crate :: { exceptions:: PyValueError , ffi} ,
9- std:: ffi:: FromBytesWithNulError ,
109 std:: slice,
1110} ;
1211
@@ -79,12 +78,21 @@ impl<'a> FromPyObject<'a, '_> for &'a CStr {
7978 // SAFETY: PyUnicode_AsUTF8AndSize always returns a NUL-terminated string
8079 let slice = unsafe { slice:: from_raw_parts ( ptr. cast ( ) , size as usize + 1 ) } ;
8180
82- CStr :: from_bytes_with_nul ( slice) . map_err ( |err| match err {
83- FromBytesWithNulError :: InteriorNul { .. } => PyValueError :: new_err ( err. to_string ( ) ) ,
84- FromBytesWithNulError :: NotNulTerminated => {
85- unreachable ! ( "PyUnicode_AsUTF8AndSize always returns a NUL-terminated string" )
86- }
87- } )
81+ #[ cfg( from_bytes_with_nul_error) ]
82+ {
83+ use std:: ffi:: FromBytesWithNulError ;
84+ CStr :: from_bytes_with_nul ( slice) . map_err ( |err| match err {
85+ FromBytesWithNulError :: InteriorNul { .. } => PyValueError :: new_err ( err. to_string ( ) ) ,
86+ FromBytesWithNulError :: NotNulTerminated => {
87+ unreachable ! ( "PyUnicode_AsUTF8AndSize always returns a NUL-terminated string" )
88+ }
89+ } )
90+ }
91+
92+ #[ cfg( not( from_bytes_with_nul_error) ) ]
93+ {
94+ CStr :: from_bytes_with_nul ( slice) . map_err ( |err| PyValueError :: new_err ( err. to_string ( ) ) )
95+ }
8896 }
8997}
9098
@@ -186,7 +194,7 @@ mod tests {
186194 assert_eq ! ( py_string. to_cow( ) . unwrap( ) , s) ;
187195
188196 let roundtripped: Cow < ' _ , CStr > = py_string. extract ( ) . unwrap ( ) ;
189- assert_eq ! ( roundtripped, cstr) ;
197+ assert_eq ! ( roundtripped. as_ref ( ) , cstr. as_c_str ( ) ) ;
190198 } )
191199 }
192200}
0 commit comments