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,
}
Purpose:
BoolSerializeris a transparent wrapper around a raw pointer to a Python object (PyObject). It encapsulates a Python boolean object pointer and provides a way to serialize it as a Rust boolean.Fields:
ptr: *mut pyo3_ffi::PyObject
A raw mutable pointer to a PythonPyObject. This pointer is expected to reference a Python boolean object (TrueorFalse).
Visibility:
The struct ispub(crate), meaning it is public within the current crate but not exposed externally.
Implementation: BoolSerializer
Constructor: new
pub fn new(ptr: *mut pyo3_ffi::PyObject) -> Self
Parameters:
ptr: A raw pointer to a PythonPyObjectwhich should be a boolean object.
Returns:
A new instance ofBoolSerializerwrapping the given pointer.Usage Example:
// Assume `py_bool_ptr` is a *mut PyObject pointing to a Python bool
let bool_serializer = BoolSerializer::new(py_bool_ptr);
Notes:
The constructor does not perform any safety checks on the pointer; it assumes the pointer is valid and points to a Python boolean object.
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) })
}
}
Purpose:
Implements theserde::Serializetrait forBoolSerializerallowing it to be serialized by any Serde serializer.Method:
serialize
Serializes the wrapped Python boolean pointer as a Rust boolean.Parameters:
serializer: An instance of a type implementing theSerializertrait from Serde.
Returns:
Result<S::Ok, S::Error>: The result of serialization, either success or an error from the serializer.
Implementation Details:
Uses
core::ptr::eqin anunsafeblock to compare the stored pointerself.ptrto a known static pointercrate::typeref::TRUEthat represents Python'sTruesingleton object.If the pointers are equal, the Python object is
True; otherwise, it isFalse.This pointer equality check is a zero-cost way to determine the boolean value without inspecting the object more deeply.
The boolean value is passed to
serializer.serialize_bool()to complete serialization.
Safety Considerations:
The pointer comparison is unsafe because it dereferences raw pointers.
It assumes that
crate::typeref::TRUEis a valid static pointer to Python'sTrueobject.The correctness depends on the pointer being a valid Python boolean object pointer.
Usage Example:
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
The file relies on the Python C API (accessed through
pyo3_ffi) to work with Python objects at a low level.The design uses pointer comparison (
core::ptr::eq) to quickly determine the boolean value, leveraging the fact that Python'sTrueandFalseare singleton objects.The
#[repr(transparent)]attribute ensures thatBoolSerializerhas the same memory layout as its single field, enabling zero-cost abstraction and safe FFI interoperability.The file depends on an external symbol
crate::typeref::TRUE, which must be a static pointer to the PythonTrueobject. This linkage is critical for correctness.
Interactions with Other Parts of the System
pyo3_ffi::PyObject: The raw pointer type comes from thepyo3crate's FFI module, which provides raw bindings to the Python C API.crate::typeref::TRUE: This file relies on a static reference to the PythonTrueobject defined elsewhere in the crate. This symbol is essential for pointer comparison to detectTrue.Serde (
serde::Serialize): Implements Serde'sSerializetrait, allowing Python boolean objects to be serialized into any Serde-compatible format.Integration Context:
Typically used in modules that convert or wrap Python objects for serialization, especially when bridging Python and Rust codebases.
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