diff --git a/common/src/os.rs b/common/src/os.rs index d04d2b807..40f403971 100644 --- a/common/src/os.rs +++ b/common/src/os.rs @@ -1,6 +1,6 @@ // TODO: we can move more os-specific bindings/interfaces from stdlib::{os, posix, nt} to here -use std::io; +use std::{io, str::Utf8Error}; #[cfg(windows)] pub fn errno() -> io::Error { @@ -21,3 +21,14 @@ pub fn errno() -> io::Error { pub fn errno() -> io::Error { io::Error::last_os_error() } + +#[cfg(unix)] +pub fn bytes_as_osstr(b: &[u8]) -> Result<&std::ffi::OsStr, Utf8Error> { + use std::os::unix::ffi::OsStrExt; + Ok(std::ffi::OsStr::from_bytes(b)) +} + +#[cfg(not(unix))] +pub fn bytes_as_osstr(b: &[u8]) -> Result<&std::ffi::OsStr, Utf8Error> { + Ok(std::str::from_utf8(b)?.as_ref()) +} diff --git a/vm/src/stdlib/os.rs b/vm/src/stdlib/os.rs index 6140ea408..c0c8af32d 100644 --- a/vm/src/stdlib/os.rs +++ b/vm/src/stdlib/os.rs @@ -378,13 +378,8 @@ pub(super) struct FollowSymlinks( #[pyarg(named, name = "follow_symlinks", default = "true")] pub bool, ); -#[cfg(unix)] -use platform::bytes_as_osstr; - -#[cfg(not(unix))] fn bytes_as_osstr<'a>(b: &'a [u8], vm: &VirtualMachine) -> PyResult<&'a ffi::OsStr> { - std::str::from_utf8(b) - .map(|s| s.as_ref()) + rustpython_common::os::bytes_as_osstr(b) .map_err(|_| vm.new_unicode_decode_error("can't decode path for utf-8".to_owned())) } diff --git a/vm/src/stdlib/posix.rs b/vm/src/stdlib/posix.rs index 49d1fedda..52cb3402a 100644 --- a/vm/src/stdlib/posix.rs +++ b/vm/src/stdlib/posix.rs @@ -1,4 +1,4 @@ -use crate::{PyObjectRef, PyResult, VirtualMachine}; +use crate::{PyObjectRef, VirtualMachine}; use std::os::unix::io::RawFd; pub fn raw_set_inheritable(fd: RawFd, inheritable: bool) -> nix::Result<()> { @@ -12,14 +12,6 @@ pub fn raw_set_inheritable(fd: RawFd, inheritable: bool) -> nix::Result<()> { Ok(()) } -pub(super) fn bytes_as_osstr<'a>( - b: &'a [u8], - _vm: &VirtualMachine, -) -> PyResult<&'a std::ffi::OsStr> { - use std::os::unix::ffi::OsStrExt; - Ok(std::ffi::OsStr::from_bytes(b)) -} - pub(crate) fn make_module(vm: &VirtualMachine) -> PyObjectRef { let module = module::make_module(vm); super::os::extend_module(vm, &module);