PyOS_FSPath
(
obj: PyObjectRef,
check_for_nul: bool,
msg: &'static str,
vm: &VirtualMachine,
)
| 31 | |
| 32 | // PyOS_FSPath |
| 33 | pub fn try_from( |
| 34 | obj: PyObjectRef, |
| 35 | check_for_nul: bool, |
| 36 | msg: &'static str, |
| 37 | vm: &VirtualMachine, |
| 38 | ) -> PyResult<Self> { |
| 39 | let check_nul = |b: &[u8]| { |
| 40 | if !check_for_nul || memchr::memchr(b'\0', b).is_none() { |
| 41 | Ok(()) |
| 42 | } else { |
| 43 | Err(crate::exceptions::cstring_error(vm)) |
| 44 | } |
| 45 | }; |
| 46 | let match1 = |obj: PyObjectRef| { |
| 47 | let pathlike = match_class!(match obj { |
| 48 | s @ PyStr => { |
| 49 | check_nul(s.as_bytes())?; |
| 50 | Self::Str(s) |
| 51 | } |
| 52 | b @ PyBytes => { |
| 53 | check_nul(&b)?; |
| 54 | Self::Bytes(b) |
| 55 | } |
| 56 | obj => return Ok(Err(obj)), |
| 57 | }); |
| 58 | Ok(Ok(pathlike)) |
| 59 | }; |
| 60 | let obj = match match1(obj)? { |
| 61 | Ok(pathlike) => return Ok(pathlike), |
| 62 | Err(obj) => obj, |
| 63 | }; |
| 64 | let not_pathlike_error = || format!("{msg}, not {}", obj.class().name()); |
| 65 | let method = vm.get_method_or_type_error( |
| 66 | obj.clone(), |
| 67 | identifier!(vm, __fspath__), |
| 68 | not_pathlike_error, |
| 69 | )?; |
| 70 | // If __fspath__ is explicitly set to None, treat it as if it doesn't have __fspath__ |
| 71 | if vm.is_none(&method) { |
| 72 | return Err(vm.new_type_error(not_pathlike_error())); |
| 73 | } |
| 74 | let result = method.call((), vm)?; |
| 75 | match1(result)?.map_err(|result| { |
| 76 | vm.new_type_error(format!( |
| 77 | "expected {}.__fspath__() to return str or bytes, not {}", |
| 78 | obj.class().name(), |
| 79 | result.class().name(), |
| 80 | )) |
| 81 | }) |
| 82 | } |
| 83 | |
| 84 | pub fn as_os_str(&self, vm: &VirtualMachine) -> PyResult<Cow<'_, OsStr>> { |
| 85 | // TODO: FS encodings |
nothing calls this directly
no test coverage detected