Skip to main content

_etoon/
lib.rs

1pub mod toon;
2
3#[cfg(feature = "python")]
4mod py_binding {
5    use crate::toon::{encode_with, Config};
6    use pyo3::prelude::*;
7    use pyo3::types::PyBytes;
8
9    #[pyfunction]
10    #[pyo3(signature = (json_bytes, delimiter=",", key_folding=false, flatten_depth=None))]
11    fn dumps_bytes<'py>(
12        py: Python<'py>,
13        json_bytes: &Bound<'py, PyBytes>,
14        delimiter: &str,
15        key_folding: bool,
16        flatten_depth: Option<usize>,
17    ) -> PyResult<String> {
18        let delim = delimiter.as_bytes().first().copied().unwrap_or(b',');
19        if !matches!(delim, b',' | b'\t' | b'|') {
20            return Err(pyo3::exceptions::PyValueError::new_err(
21                "delimiter must be ',', '\\t', or '|'",
22            ));
23        }
24        let cfg = Config {
25            delimiter: delim,
26            key_folding,
27            flatten_depth,
28        };
29        let bytes = json_bytes.as_bytes();
30        py.detach(|| encode_with(bytes, &cfg))
31            .map_err(pyo3::exceptions::PyValueError::new_err)
32    }
33
34    #[pymodule]
35    fn _etoon(m: &Bound<'_, PyModule>) -> PyResult<()> {
36        m.add_function(wrap_pyfunction!(dumps_bytes, m)?)?;
37        Ok(())
38    }
39}