Rust -> Python bindings

This guide explains how to add new Python bindings for Rust functions in the garaga_rs crate.

Overview

The Python bindings are implemented using PyO3, which provides a safe and ergonomic way to create Python extensions in Rust. The bindings are located in the tools/garaga_rs/src/python_bindings directory.

Adding a new binding

  1. Create a new file in tools/garaga_rs/src/python_bindings/ for your binding

  2. Add the module to mod.rs

  3. Implement your binding function

  4. Register the function in the garaga_rs module

Type Conversions

Common Type Conversions

  1. Python Int -> Rust BigUint

let py_int: &Bound<'_, PyInt> = ...;
let biguint: BigUint = py_int.extract()?;
  1. Rust BigUint -> Python Int

  1. Python List -> Rust Vec

  1. Python Bytes -> Rust Bytes

  1. Field Elements

Error Handling

  1. Converting Rust Errors to Python

  1. Enum Conversion

Common Patterns

  1. Function Declaration

  1. Returning Results

Example Implementation

Here's a complete example showing common patterns:

Registering Your Function

Add your function to the garaga_rs module in mod.rs:

Using the Bindings

After implementing and registering your binding, you can use it in Python like this:

Testing

  1. Add Python tests in tests/hydra/

  2. Test both successful and error cases

  3. Test edge cases (empty lists, zero values)

Common Pitfalls

  1. Always use PyResult for error handling

  2. Remember to propagate errors with ?

  3. Handle edge cases (e.g., zero values, maximum values)

  4. Be careful with memory management for large data structures

Available Utilities

The following utilities are available in the codebase:

  • element_from_biguint: Convert BigUint to Field Element

  • element_to_biguint: Convert Field Element to BigUint

  • biguint_to_u256: Convert BigUint to u256

Building and Testing

  1. Build/Update the Rust extension:

  1. Run tests:

Best Practices

  1. Keep bindings simple and focused

  2. Use appropriate error handling

  3. Test edge cases thoroughly

  4. Follow existing patterns in the codebase

Last updated

Was this helpful?