float.rs


Overview

The `float.rs` file provides a specialized serialization utility for Python floating-point objects (`PyFloat`) within a Rust context, particularly for use with the [serde](https://serde.rs/) serialization framework. It defines a transparent wrapper struct, `FloatSerializer`, that holds a raw pointer to a Python float object and implements the `Serialize` trait to convert the Python float into a Rust `f64` for serialization.

This file is part of a Rust-Python interoperability layer, likely within a project that bridges Rust and Python objects using [PyO3](https://pyo3.rs/), enabling efficient serialization of Python floats into formats supported by serde serializers (e.g., JSON, MessagePack).


Detailed Documentation

Struct: FloatSerializer

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

Impl: FloatSerializer

new

pub fn new(ptr: *mut pyo3_ffi::PyObject) -> Self
let py_float_ptr: *mut pyo3_ffi::PyObject = /* obtained from Python/C API */;
let serializer = FloatSerializer::new(py_float_ptr);

Trait Impl: Serialize for FloatSerializer

impl Serialize for FloatSerializer {
    #[inline(always)]
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_f64(ffi!(PyFloat_AS_DOUBLE(self.ptr)))
    }
}
use serde_json;

let py_float_ptr: *mut pyo3_ffi::PyObject = /* pointer from Python */;
let float_serializer = FloatSerializer::new(py_float_ptr);

let json_string = serde_json::to_string(&float_serializer).unwrap();
println!("{}", json_string); // Outputs the float as JSON number, e.g., "3.14"

Important Implementation Details


Interaction With Other Parts of the System


Visual Diagram

classDiagram
    class FloatSerializer {
        - ptr: *mut PyObject
        + new(ptr: *mut PyObject) FloatSerializer
        + serialize<S: Serializer>(serializer: S) Result<S::Ok, S::Error>
    }
    FloatSerializer ..|> Serialize

Summary

`float.rs` is a concise utility file that wraps a raw pointer to a Python float object and provides an efficient serialization implementation by exposing its inner floating-point value to Rust's serde framework. It is a low-level bridge component facilitating data interchange between Python and Rust, especially in contexts requiring serialization of Python floats into Rust-supported formats.

This file's design prioritizes performance and interoperability but assumes upstream safety guarantees regarding pointer validity and object type correctness.