From 5b3c2c8666b841a981114602ddcb39b05e2f0e2e Mon Sep 17 00:00:00 2001
From: Martin Larralde <martin.larralde@embl.de>
Date: Mon, 2 Sep 2024 14:59:08 +0200
Subject: [PATCH] Avoid use of unsafe `OsStr::from_encoded_bytes_unchecked` in
 `lightmotif-py`

---
 lightmotif-py/lightmotif/io.rs | 9 ++++-----
 1 file changed, 4 insertions(+), 5 deletions(-)

diff --git a/lightmotif-py/lightmotif/io.rs b/lightmotif-py/lightmotif/io.rs
index fd32a8c..4e256ca 100644
--- a/lightmotif-py/lightmotif/io.rs
+++ b/lightmotif-py/lightmotif/io.rs
@@ -9,7 +9,7 @@ use lightmotif_io::error::Error;
 use pyo3::exceptions::PyOSError;
 use pyo3::exceptions::PyValueError;
 use pyo3::prelude::*;
-use pyo3::types::PyBytes;
+use pyo3::types::PyString;
 
 use super::pyfile::PyFileRead;
 use super::CountMatrixData;
@@ -163,15 +163,14 @@ pub fn load(file: Bound<PyAny>, format: &str, protein: bool) -> PyResult<Loader>
     let py = file.py();
     let pathlike = py
         .import_bound(pyo3::intern!(py, "os"))?
-        .call_method1("fsencode", (&file,));
+        .call_method1(pyo3::intern!(py, "fsdecode"), (&file,));
     let b: Box<dyn BufRead + Send> = if let Ok(path) = pathlike {
         // NOTE(@althonos): In theory this is safe because `os.fsencode` encodes
         //                  the PathLike object into the OS prefered encoding,
         //                  which is was OsStr wants. In practice, there may be
         //                  some weird bugs if that encoding is incorrect, idk...
-        let encoded = path.downcast::<PyBytes>()?;
-        let s = unsafe { std::ffi::OsStr::from_encoded_bytes_unchecked(encoded.as_bytes()) };
-        std::fs::File::open(s)
+        let decoded = path.downcast::<PyString>()?;
+        std::fs::File::open(decoded.to_str()?)
             .map(std::io::BufReader::new)
             .map(Box::new)?
     } else {
-- 
GitLab