Mercurial > touhou
changeset 770:f6c287745a67
Rust: Add a libtouhou Python wrapper using pyo3
author | Emmanuel Gil Peyrot <linkmauve@linkmauve.fr> |
---|---|
date | Tue, 30 Aug 2022 18:23:55 +0200 |
parents | cae5f15ca5ed |
children | 79c3f782dd41 |
files | Cargo.toml python/Cargo.toml python/src/lib.rs |
diffstat | 3 files changed, 60 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- a/Cargo.toml +++ b/Cargo.toml @@ -3,6 +3,7 @@ members = [ "formats", "interpreters", + "python", "runners", "utils", ] @@ -10,5 +11,6 @@ members = [ [patch.crates-io] touhou-formats = { path = "formats" } touhou-interpreters = { path = "interpreters" } +touhou-python = { path = "python" } touhou-runners = { path = "runners" } touhou-utils = { path = "utils" }
new file mode 100644 --- /dev/null +++ b/python/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "touhou-python" +version = "0.1.0" +edition = "2021" +authors = [ + "Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>", +] + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[lib] +crate-type = ["cdylib"] +name = "touhou" + +[dependencies] +touhou-formats = "*" +pyo3 = "0.17"
new file mode 100644 --- /dev/null +++ b/python/src/lib.rs @@ -0,0 +1,41 @@ +use pyo3::prelude::*; +use pyo3::types::PyBytes; +use touhou_formats::th06::pbg3; +use std::fs::File; +use std::io::BufReader; + +#[pyclass] +struct PBG3 { + inner: pbg3::PBG3<BufReader<File>>, +} + +#[pymethods] +impl PBG3 { + #[staticmethod] + fn from_filename(filename: &str) -> PyResult<PBG3> { + let inner = pbg3::from_path_buffered(filename)?; + Ok(PBG3 { + inner + }) + } + + #[getter] + fn file_list(&self) -> Vec<String> { + self.inner.list_files().cloned().collect() + } + + fn list_files(&self) -> Vec<String> { + self.inner.list_files().cloned().collect() + } + + fn get_file(&mut self, py: Python, name: &str) -> PyObject { + let data = self.inner.get_file(name, true).unwrap(); + PyBytes::new(py, &data).into_py(py) + } +} + +#[pymodule] +fn libtouhou(_py: Python, m: &PyModule) -> PyResult<()> { + m.add_class::<PBG3>()?; + Ok(()) +}