pybool.rs


Overview

The `pybool.rs` file provides a specialized serialization utility for boolean values represented by Python objects in Rust. Specifically, it defines a wrapper type `BoolSerializer` that enables serializing a Python boolean (`PyObject`) into Rust's serialization framework (Serde). The core functionality hinges on safely comparing the internal pointer of a Python boolean object to a known static Python `True` object pointer to determine the boolean value during serialization.

This file is typically used in contexts where Python boolean objects need to be serialized into formats supported by Serde serializers (e.g., JSON, YAML) within Rust programs that interface with Python objects via the `pyo3` FFI (Foreign Function Interface).


Detailed Explanation

Struct: BoolSerializer

#[repr(transparent)]
pub(crate) struct BoolSerializer {
    ptr: *mut pyo3_ffi::PyObject,
}

Implementation: BoolSerializer

Constructor: new

pub fn new(ptr: *mut pyo3_ffi::PyObject) -> Self
// Assume `py_bool_ptr` is a *mut PyObject pointing to a Python bool
let bool_serializer = BoolSerializer::new(py_bool_ptr);

Trait Implementation: Serialize for BoolSerializer

impl Serialize for BoolSerializer {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_bool(unsafe { core::ptr::eq(self.ptr, crate::typeref::TRUE) })
    }
}
use serde_json;

let bool_serializer = BoolSerializer::new(py_bool_ptr);
let json = serde_json::to_string(&bool_serializer).unwrap();
// `json` will be "true" or "false" depending on the pointer comparison

Important Implementation Details


Interactions with Other Parts of the System


Summary

`pybool.rs` provides a lightweight and efficient mechanism to serialize Python boolean objects by wrapping their raw pointers and using pointer comparison against Python's singleton `True` object. It facilitates seamless integration between Python's boolean semantics and Rust's serialization ecosystem.


Visual Diagram

classDiagram
    class BoolSerializer {
        - ptr: *mut PyObject
        + new(ptr: *mut PyObject) BoolSerializer
        + serialize<S: Serializer>(serializer: S) -> Result<S::Ok, S::Error>
    }
    BoolSerializer ..|> Serialize
    PyObject : Python object pointer (from pyo3_ffi)
    BoolSerializer --> PyObject : wraps pointer
    BoolSerializer ..> typeref::TRUE : uses for pointer comparison

End of Documentation for pybool.rs