Skip to main content

PYCONV_RS

Constant PYCONV_RS 

Source
pub const PYCONV_RS: &str = r#"//! Python objects to `serde_json::Value` and back, in Rust. Generated by rust-anything.

#![forbid(unsafe_code)]

use pyo3::prelude::*;
use pyo3::types::{
    PyBool, PyByteArray, PyBytes, PyDict, PyFloat, PyFrozenSet, PyInt, PyList, PyMemoryView,
    PySet, PyString, PyTuple,
};
use serde_json::{Map, Value, json};

fn type_error(obj: &Bound<'_, PyAny>) -> String {
    let name = obj.get_type().name().map(|n| n.to_string()).unwrap_or_default();
    format!("TypeError: unsupported argument type {name}")
}

fn float(x: f64) -> Value {
    if x.is_nan() {
        json!({"$num": "NaN"})
    } else if x.is_infinite() {
        json!({"$num": if x > 0.0 { "Infinity" } else { "-Infinity" }})
    } else if x == 0.0 && x.is_sign_negative() {
        json!({"$num": "-0"})
    } else {
        json!(x)
    }
}

fn items(obj: &Bound<'_, PyAny>) -> Result<Vec<Value>, String> {
    let mut out = Vec::new();
    for item in obj.try_iter().map_err(|e| e.to_string())? {
        out.push(from_py(&item.map_err(|e| e.to_string())?)?);
    }
    Ok(out)
}

fn extract_bytes(obj: &Bound<'_, PyAny>) -> Option<Result<Vec<u8>, String>> {
    if obj.is_instance_of::<PyBytes>() {
        return Some(
            obj.cast::<PyBytes>()
                .map(|b| b.as_bytes().to_vec())
                .map_err(|e| e.to_string()),
        );
    }
    if obj.is_instance_of::<PyByteArray>() {
        return Some(
            obj.cast::<PyByteArray>()
                .map(|b| b.to_vec())
                .map_err(|e| e.to_string()),
        );
    }
    if obj.is_instance_of::<PyMemoryView>() {
        return Some(
            obj.call_method0("tobytes")
                .and_then(|b| {
                    b.cast::<PyBytes>()
                        .map(|b| b.as_bytes().to_vec())
                        .map_err(Into::into)
                })
                .map_err(|e| e.to_string()),
        );
    }
    None
}

/// A Python object as a JSON value.
pub fn from_py(obj: &Bound<'_, PyAny>) -> Result<Value, String> {
    if obj.is_none() {
        return Ok(Value::Null);
    }
    if obj.is_instance_of::<PyBool>() {
        return Ok(Value::Bool(obj.extract::<bool>().map_err(|e| e.to_string())?));
    }
    if obj.is_instance_of::<PyInt>() {
        return Ok(match obj.extract::<i64>() {
            Ok(i) => json!(i),
            Err(_) => json!({"$int": obj.str().map_err(|e| e.to_string())?.to_string()}),
        });
    }
    if obj.is_instance_of::<PyFloat>() {
        return Ok(float(obj.extract::<f64>().map_err(|e| e.to_string())?));
    }
    if obj.is_instance_of::<PyString>() {
        return Ok(Value::String(obj.extract::<String>().map_err(|e| e.to_string())?));
    }
    if obj.is_instance_of::<PyList>() {
        return Ok(Value::Array(items(obj)?));
    }
    if obj.is_instance_of::<PyTuple>() {
        return Ok(json!({"$tuple": items(obj)?}));
    }
    if obj.is_instance_of::<PyDict>() {
        let dict = obj.cast::<PyDict>().map_err(|e| e.to_string())?;
        let mut map = Map::new();
        let mut pairs = Vec::new();
        let mut string_keys = true;
        for (k, v) in dict.iter() {
            let value = from_py(&v)?;
            if let Ok(key) = k.extract::<String>() {
                map.insert(key.clone(), value.clone());
                pairs.push(json!([key, value]));
            } else {
                string_keys = false;
                pairs.push(json!([from_py(&k)?, value]));
            }
        }
        return Ok(if string_keys { Value::Object(map) } else { json!({"$dict": pairs}) });
    }
    if obj.is_instance_of::<PySet>() || obj.is_instance_of::<PyFrozenSet>() {
        return Ok(json!({"$set": items(obj)?}));
    }
    if let Some(bytes) = extract_bytes(obj) {
        return Ok(json!({"$bytes": bytes?}));
    }
    Err(type_error(obj))
}

/// A structured argument, converted to the port's parameter type.
pub fn arg<T: serde::de::DeserializeOwned>(obj: &Bound<'_, PyAny>) -> Result<T, String> {
    serde_json::from_value(from_py(obj)?).map_err(|e| format!("TypeError: {e}"))
}

/// A Python argument as a Rust value, without going through JSON.
pub trait FromPy: Sized {
    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String>;
}

/// A Rust result as a Python object, without going through JSON.
pub trait ToPy {
    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>>;
}

macro_rules! extract {
    ($($t:ty),*) => {$(
        impl FromPy for $t {
            fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
                obj.extract::<$t>().map_err(|_| type_error(obj))
            }
        }
        impl ToPy for $t {
            fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
                Ok(self.clone().into_pyobject(py)?.to_owned().into_any().unbind())
            }
        }
    )*};
}
extract!(i64, bool, String);

impl FromPy for f64 {
    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
        if obj.is_instance_of::<PyFloat>() || obj.is_instance_of::<PyInt>() {
            obj.extract::<f64>().map_err(|_| type_error(obj))
        } else {
            Err(type_error(obj))
        }
    }
}

impl ToPy for f64 {
    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        Ok(PyFloat::new(py, *self).into_any().unbind())
    }
}

impl FromPy for crate::pynum::Num {
    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
        use crate::pynum::Num;
        if obj.is_instance_of::<PyFloat>() {
            return obj.extract::<f64>().map(Num::Float).map_err(|_| type_error(obj));
        }
        if obj.is_instance_of::<PyInt>() {
            return obj
                .extract::<i64>()
                .map(Num::Int)
                .map_err(|_| "OverflowError: int too large for the port".to_string());
        }
        Err(type_error(obj))
    }
}

impl ToPy for crate::pynum::Num {
    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        match *self {
            crate::pynum::Num::Int(i) => i.to_py(py),
            crate::pynum::Num::Float(x) => x.to_py(py),
        }
    }
}

impl FromPy for Value {
    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
        from_py(obj)
    }
}

impl ToPy for Value {
    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        to_py(py, self)
    }
}

impl<T: FromPy> FromPy for Option<T> {
    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
        if obj.is_none() { Ok(None) } else { T::from_py(obj).map(Some) }
    }
}

impl<T: ToPy> ToPy for Option<T> {
    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        match self {
            Some(v) => v.to_py(py),
            None => Ok(py.None()),
        }
    }
}

impl FromPy for Vec<u8> {
    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
        extract_bytes(obj).unwrap_or_else(|| Err(type_error(obj)))
    }
}

impl ToPy for Vec<u8> {
    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        Ok(PyBytes::new(py, self).into_any().unbind())
    }
}

impl<T: FromPy> FromPy for Vec<T> {
    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
        if !obj.is_instance_of::<PyList>() && !obj.is_instance_of::<PyTuple>() {
            return Err(type_error(obj));
        }
        let mut out = Vec::new();
        for item in obj.try_iter().map_err(|e| e.to_string())? {
            out.push(T::from_py(&item.map_err(|e| e.to_string())?)?);
        }
        Ok(out)
    }
}

impl<T: ToPy> ToPy for Vec<T> {
    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        let items: PyResult<Vec<Py<PyAny>>> = self.iter().map(|x| x.to_py(py)).collect();
        Ok(PyList::new(py, items?)?.into_any().unbind())
    }
}

impl<T: FromPy> FromPy for std::collections::HashMap<String, T> {
    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
        let dict = obj.cast::<PyDict>().map_err(|_| type_error(obj))?;
        let mut out = Self::new();
        for (k, v) in dict.iter() {
            out.insert(k.extract::<String>().map_err(|_| type_error(&k))?, T::from_py(&v)?);
        }
        Ok(out)
    }
}

impl<T: ToPy> ToPy for std::collections::HashMap<String, T> {
    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        let dict = PyDict::new(py);
        for (k, v) in self {
            dict.set_item(k, v.to_py(py)?)?;
        }
        Ok(dict.into_any().unbind())
    }
}

macro_rules! tuples {
    ($(($($t:ident $i:tt),+)),*) => {$(
        impl<$($t: FromPy),+> FromPy for ($($t,)+) {
            fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
                let t = obj.cast::<PyTuple>().map_err(|_| type_error(obj))?;
                Ok(($($t::from_py(&t.get_item($i).map_err(|e| e.to_string())?)?,)+))
            }
        }
        impl<$($t: ToPy),+> ToPy for ($($t,)+) {
            fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
                Ok(PyTuple::new(py, [$(self.$i.to_py(py)?),+])?.into_any().unbind())
            }
        }
    )*};
}
tuples!((A 0, B 1), (A 0, B 1, C 2), (A 0, B 1, C 2, D 3));

/// A JSON value as a Python object; markers become the Python types they stand for.
pub fn to_py(py: Python<'_>, v: &Value) -> PyResult<Py<PyAny>> {
    let list = |items: &[Value]| -> PyResult<Vec<Py<PyAny>>> { items.iter().map(|x| to_py(py, x)).collect() };
    Ok(match v {
        Value::Null => py.None(),
        Value::Bool(b) => PyBool::new(py, *b).to_owned().into_any().unbind(),
        Value::Number(n) => match n.as_i64() {
            Some(i) if !n.is_f64() => i.into_pyobject(py)?.into_any().unbind(),
            _ => match n.as_u64() {
                Some(u) if !n.is_f64() => u.into_pyobject(py)?.into_any().unbind(),
                _ => PyFloat::new(py, n.as_f64().unwrap_or(f64::NAN)).into_any().unbind(),
            },
        },
        Value::String(s) => PyString::new(py, s).into_any().unbind(),
        Value::Array(items) => PyList::new(py, list(items)?)?.into_any().unbind(),
        Value::Object(o) if o.len() == 1 => {
            let (key, inner) = o.iter().next().expect("one entry");
            let items = || inner.as_array().map(Vec::as_slice).unwrap_or_default();
            match key.as_str() {
                "$tuple" => PyTuple::new(py, list(items())?)?.into_any().unbind(),
                "$set" => PySet::new(py, list(items())?)?.into_any().unbind(),
                "$bytes" => {
                    let bytes: Vec<u8> = items().iter().filter_map(|b| b.as_u64()).map(|b| b as u8).collect();
                    PyBytes::new(py, &bytes).into_any().unbind()
                }
                "$int" => py
                    .import("builtins")?
                    .getattr("int")?
                    .call1((inner.as_str().unwrap_or("0"),))?
                    .unbind(),
                "$float" => PyFloat::new(py, inner.as_str().and_then(|s| s.parse().ok()).unwrap_or(f64::NAN)).into_any().unbind(),
                "$num" => PyFloat::new(
                    py,
                    match inner.as_str() {
                        Some("Infinity") => f64::INFINITY,
                        Some("-Infinity") => f64::NEG_INFINITY,
                        Some("-0") => -0.0,
                        _ => f64::NAN,
                    },
                )
                .into_any()
                .unbind(),
                "$dict" => {
                    let dict = PyDict::new(py);
                    for pair in items() {
                        if let Some([k, v]) = pair.as_array().map(Vec::as_slice) {
                            dict.set_item(to_py(py, k)?, to_py(py, v)?)?;
                        }
                    }
                    dict.into_any().unbind()
                }
                _ => {
                    let dict = PyDict::new(py);
                    dict.set_item(key, to_py(py, inner)?)?;
                    dict.into_any().unbind()
                }
            }
        }
        Value::Object(o) => {
            let dict = PyDict::new(py);
            for (k, x) in o {
                dict.set_item(k, to_py(py, x)?)?;
            }
            dict.into_any().unbind()
        }
    })
}
"#;
Expand description

src/pyconv.rs: Python objects to serde_json::Value and back, in Rust, without JSON text. Values the JSON model lacks use the same markers as recorded cases: $tuple, $set, $bytes, $int (beyond i64), $dict (non-string keys), $num (NaN, infinities, -0).