byteswriter.rs


Overview

`byteswriter.rs` defines a specialized utility for efficiently constructing and manipulating Python byte string objects (`PyBytesObject`) from Rust. At its core is the `BytesWriter` struct, which provides a mutable buffer interface tailored to grow a Python bytes object dynamically, supporting incremental writes with minimal overhead.

This file acts as a bridge between Rust's performant memory operations and Python's byte string API, leveraging unsafe Rust code and Python C API functions through FFI to allocate, resize, and finalize Python bytes buffers. It implements the `BufMut` trait from the `bytes` crate, allowing seamless writing of bytes and slices with direct memory access.

The utility is designed for internal use (`pub(crate)`) within a larger system that likely involves serialization, JSON processing, or Python interop where mutable, dynamically sized byte buffers are required.


Detailed Documentation

Constants


Struct: BytesWriter

A mutable writer for Python bytes objects (`PyBytesObject`) that supports efficient byte appending and resizing.

Fields

Field

Type

Description

`cap`

`usize`

Total capacity of the allocated Python bytes buffer.

`len`

`usize`

Current length (number of bytes used) in the buffer.

`bytes`

`*mut PyBytesObject`

Raw pointer to the Python bytes object buffer.

Associated Functions and Methods


default() -> Self

Creates a new `BytesWriter` with an initial capacity of `BUFFER_LENGTH`.

**Usage example:**

let mut writer = BytesWriter::default();

bytes_ptr(&mut self) -> NonNull<PyObject>

Returns a non-null raw pointer to the underlying Python object (`PyObject`).

**Usage example:**

let py_obj_ptr = writer.bytes_ptr();
// Pass py_obj_ptr to Python API or other code

finish(&mut self, append: bool) -> NonNull<PyObject>

Finalizes the bytes buffer and returns the Python bytes object pointer.

**Parameters:**

**Returns:**

**Usage example:**

let py_bytes = writer.finish(true);
// py_bytes now contains the bytes with a trailing newline

buffer_ptr(&self) -> *mut u8

Returns a raw mutable pointer to the next writable location in the internal buffer.


resize(&mut self, len: usize)

Resizes the Python bytes object buffer to the specified length.

**Parameters:**


grow(&mut self, len: usize)

Grows the buffer capacity to accommodate at least `len` bytes.


Trait Implementations


unsafe impl BufMut for BytesWriter

Implements the `BufMut` trait from the `bytes` crate, enabling writing bytes into the buffer.

Methods:

**Note:** All methods assume that there is sufficient capacity in the buffer; otherwise, buffer growth must be managed externally.


Trait: WriteExt

A helper trait to extend writing capabilities with buffer pointer access and reservation.


Implementation: WriteExt for &mut BytesWriter

Extends `BytesWriter` with:


Important Implementation Details


Interaction with Other System Components


Visual Diagram

classDiagram
    class BytesWriter {
        - cap: usize
        - len: usize
        - bytes: *mut PyBytesObject
        + default() BytesWriter
        + bytes_ptr() NonNull<PyObject>
        + finish(append: bool) NonNull<PyObject>
        - buffer_ptr() *mut u8
        + resize(len: usize)
        - grow(len: usize)
    }

    class WriteExt {
        <<trait>>
        + as_mut_buffer_ptr() *mut u8
        + reserve(len: usize)
    }

    WriteExt <|.. "&mut BytesWriter"
    BytesWriter ..> PyBytesObject : raw pointer

Summary

`byteswriter.rs` provides a performant, low-level Rust abstraction for building Python `bytes` objects incrementally. It combines direct memory manipulation, Python C API interaction, and Rust `BufMut` trait compatibility to enable efficient byte buffer writing in Python interop scenarios. Its design emphasizes minimal allocations, dynamic growth, and safe exposure of Python bytes objects to the rest of the system.