util.rs


Overview

`util.rs` is a utility module in Rust designed to provide low-level macros and helper functions that facilitate safer and more ergonomic interaction with Python's C API via the `pyo3_ffi` bindings. The file primarily defines macros to simplify common operations such as type checking, reference counting, dictionary manipulation, and string handling in the context of Python objects. It also includes small utility functions for integer conversions with debug assertions.

This file serves as a foundational layer that abstracts and encapsulates unsafe operations and repetitive boilerplate patterns, ensuring consistency and reducing errors across the larger PyO3 codebase or any Rust code interfacing with Python internals.


Detailed Descriptions

Macros

Macros in this file are designed to encapsulate unsafe or complex operations on Python objects and types.


is_type!


ob_type!


is_class_by_type!


tp_flags!


is_subclass_by_flag!


is_subclass_by_type!


err!


opt_enabled! and opt_disabled!


unlikely! and likely!


nonnull!


str_from_slice!


Reference Counting Macros (reverse_pydict_incref!, ffi!, call_method!, etc.)


str_hash!


Dictionary Macros (pydict_contains!, pydict_next!, pydict_setitem!)


reserve_minimum! and reserve_pretty!


assume!


unreachable_unchecked!


Functions


usize_to_isize


isize_to_usize


Important Implementation Details


Interaction with Other Parts of the System


Visual Diagram

The following flowchart illustrates the relationships and workflow between the main macro categories and functions in `util.rs`. It shows how the macros abstract core Python C API operations and utility conversions, which are then used by higher-level Rust code.

flowchart TD
    A[Python C API (pyo3_ffi)] --> B[ffi! macro]
    B --> C[Reference Counting Macros]
    B --> D[Dictionary Macros]
    B --> E[Method Call Macros]
    B --> F[Type & Flag Macros]

    F --> G[is_type!]
    F --> H[ob_type!]
    F --> I[tp_flags!]
    F --> J[is_subclass_by_flag!]
    F --> K[is_subclass_by_type!]

    C --> L[reverse_pydict_incref!]
    C --> M[str_hash!]

    D --> N[pydict_contains!]
    D --> O[pydict_next!]
    D --> P[pydict_setitem!]

    E --> Q[call_method!]

    R[Utility Macros] --> S[opt_enabled! / opt_disabled!]
    R --> T[likely! / unlikely!]
    R --> U[nonnull!]
    R --> V[str_from_slice!]
    R --> W[assume! / unreachable_unchecked!]

    X[Helper Functions] --> Y[usize_to_isize()]
    X --> Z[isize_to_usize()]

    style A fill:#f9f,stroke:#333,stroke-width:2px
    style B fill:#bbf,stroke:#333
    style C fill:#bfb,stroke:#333
    style D fill:#fbf,stroke:#333
    style E fill:#ffb,stroke:#333
    style F fill:#fbb,stroke:#333
    style R fill:#aff,stroke:#333
    style X fill:#ffa,stroke:#333

Summary


**End of documentation for `util.rs`**