$ show oconnor663/blake3-py
This repository provides Python bindings for the BLAKE3 cryptographic hash function, using the official Rust implementation via PyO3. It exposes a single `blake3` class that mimics the Python `hashlib` API, supporting incremental hashing, keyed hashing, key derivation, extendable output (XOF), multithreading via Rayon, and memory-mapped file hashing. The core implementation is in `src/lib.rs`, which demonstrates careful handling of Python buffer protocol types (signed/unsigned bytes), GIL release for long operations, and interior mutability with `Mutex` for thread safety. An experimental C implementation in `c_impl/` provides a fallback for platforms without Rust support. The package is published on PyPI as `blake3` and includes comprehensive test vectors, type stubs, and CI for multiple platforms and Python versions (3.8 to 3.14, including free-threaded).
The LLM identified 3 files worth highlighting for reuse:
The `BytesPyBuffer` enum and `bytes_from_pybuffer` function provide a safe, reusable pattern for accepting both signed (`i8`) and unsigned (`u8`) byte buffers from Python in PyO3 extensions. This solves a common pain point in PyO3 development where buffer protocol types can vary. The code also demonstrates proper GIL release for long-running operations and use of `frozen` pyclass with `Mutex` to avoid interior mutability issues in multi-threaded contexts. These patterns can be extracted into a utility crate for other PyO3 projects.
A complete CPython extension implementing the same BLAKE3 API in C. It showcases thread-safe hasher state management using `PyThread_type_lock`, GIL release/acquire patterns for long operations, and fallback file reading for `update_mmap`. The code is well-structured with clear error handling and could serve as a reference for implementing other hash functions as CPython extensions.
A comprehensive test suite covering all BLAKE3 features: test vectors for multiple input lengths, various buffer types (bytes, bytearray, memoryview, array.array, numpy), key types, invalid key lengths, multithreading, copy/reset, mmap, reentrancy deadlock, and parameter validation. The tests are well-organized and could be adapted for testing other hash implementations.