Skip to content

Conversation

@youknowone
Copy link
Member

@youknowone youknowone commented Dec 29, 2025

Summary by CodeRabbit

Release Notes

  • New Features
    • Array objects now support proper element initialization during instantiation.
    • Simple ctypes objects can accept values during initialization.
    • Optimized memory efficiency in buffer management for ctypes operations.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 29, 2025

Warning

Rate limit exceeded

@youknowone has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 1 minutes and 9 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between d415a83 and c1cd643.

📒 Files selected for processing (3)
  • crates/vm/src/stdlib/ctypes/array.rs
  • crates/vm/src/stdlib/ctypes/simple.rs
  • crates/vm/src/stdlib/ctypes/structure.rs
📝 Walkthrough

Walkthrough

This PR introduces Initializer trait implementations for PyCArray and PyCSimple ctypes, enabling reinitialization through __init__ calls with memory-aware buffer handling using Cow-based writes that update in-place for borrowed memory or fallback to owned copies.

Changes

Cohort / File(s) Summary
Array Initialization
crates/vm/src/stdlib/ctypes/array.rs
Added Initializer implementation for PyCArray to reinitialize elements from provided args by iterating and calling setitem_by_index. Modified setitem_by_index to use Cow-based memory-aware writes: direct mutable slice updates for borrowed memory, or owned buffer copy for non-borrowed cases. Registered Initializer in pyclass declaration. Added public use std::borrow::Cow import.
Simple Type Initialization
crates/vm/src/stdlib/ctypes/simple.rs
Added Initializer implementation for PyCSimple to process OptionalArg during initialization. Reworked buffer updating to perform in-place writes when buffer is borrowed (shared memory), falling back to owned buffer copy when needed. Registered Initializer in pyclass declaration.

Sequence Diagram

sequenceDiagram
    participant Python as Python Caller
    participant Init as Initializer::init()
    participant CType as PyCArray/PyCSimple
    participant Buffer as Memory Buffer
    participant Cow as Cow Handler
    
    Python->>Init: __init__(args)
    Init->>Init: Extract args from OptionalArg/tuple
    loop For each element/value
        Init->>CType: Process item
        CType->>Cow: Check buffer type (Borrowed vs Owned)
        alt Borrowed Memory
            Cow->>Buffer: Convert to mutable slice
            Buffer->>Buffer: Write in-place
        else Owned Memory
            Cow->>Buffer: Create new Owned copy
            Buffer->>Buffer: Copy and update
        end
    end
    CType-->>Python: Initialization complete
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • small fixes #6444: Modifies the Initializer slot binding and __init__ signature requirements that these trait implementations must conform to.
  • ctypes overhaul #6450: Introduces parallel Initializer-based lifecycle and buffer/write changes for the same ctypes types with overlapping modifications.
  • Init copyslot #6515: Changes Initializer slot codegen and registration plumbing that enables slot registration in pyclass declarations as introduced here.

Suggested reviewers

  • arihant2math

Poem

🐰 hops with glee
Init blooms anew with memory's care,
Borrowed or owned buffers dance fair,
Cow rewrites what Python did call,
Arrays and simples reinit them all! ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.22% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Initializer for PyCSimple, PyCArray' accurately and directly describes the main change: adding Initializer implementations to both PyCSimple and PyCArray classes.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@youknowone youknowone marked this pull request as ready for review December 29, 2025 14:56
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
crates/vm/src/stdlib/ctypes/array.rs (1)

434-444: Consider adding bounds check for consistent error messaging.

The Constructor::slot_new (lines 412-414) checks args.args.len() > length and returns a "too many initializers" error. This Initializer relies on setitem_by_index which returns a less descriptive "invalid index" error. While functionally correct, adding the same check would improve consistency.

🔎 Suggested improvement
 impl Initializer for PyCArray {
     type Args = FuncArgs;
 
     fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
+        let length = zelf.class().stg_info_opt().map_or(0, |i| i.length);
+        if args.args.len() > length {
+            return Err(vm.new_index_error("too many initializers"));
+        }
         // Re-initialize array elements when __init__ is called
         for (i, value) in args.args.iter().enumerate() {
             PyCArray::setitem_by_index(&zelf, i as isize, value.clone(), vm)?;
         }
         Ok(())
     }
 }
crates/vm/src/stdlib/ctypes/simple.rs (1)

1300-1313: Inconsistent length handling between Cow::Borrowed and Cow::Owned branches.

The Cow::Borrowed branch uses .min() which silently truncates if buffer lengths differ (line 1305), while Cow::Owned uses copy_from_slice which panics on length mismatch (line 1311).

For simple types the sizes should always match, but this inconsistency could mask bugs. Consider using consistent handling in both branches.

🔎 Suggested fix for consistent behavior
             Cow::Owned(vec) => {
-                vec.copy_from_slice(&buffer_bytes);
+                let len = vec.len().min(buffer_bytes.len());
+                vec[..len].copy_from_slice(&buffer_bytes[..len]);
             }

Or alternatively, add the .min() check to both branches and add an assertion/debug check if sizes unexpectedly differ.

📜 Review details

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8059960 and d415a83.

📒 Files selected for processing (2)
  • crates/vm/src/stdlib/ctypes/array.rs
  • crates/vm/src/stdlib/ctypes/simple.rs
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.rs: Follow the default rustfmt code style by running cargo fmt to format Rust code
Always run clippy to lint code (cargo clippy) before completing tasks and fix any warnings or lints introduced by changes
Follow Rust best practices for error handling and memory management
Use the macro system (pyclass, pymodule, pyfunction, etc.) when implementing Python functionality in Rust

Files:

  • crates/vm/src/stdlib/ctypes/simple.rs
  • crates/vm/src/stdlib/ctypes/array.rs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Run snippets and cpython tests (windows-latest)
🔇 Additional comments (5)
crates/vm/src/stdlib/ctypes/array.rs (3)

16-16: LGTM!

The Cow import is correctly added to support the memory-aware buffer handling in setitem_by_index.


471-474: LGTM!

Adding Initializer to the with(...) clause correctly enables the __init__ slot implementation for PyCArray.


887-904: The writable buffer invariant is enforced through runtime validation in from_buffer_impl. The code at lines 887-904 is safe because Cow::Borrowed buffers from external sources are only created after from_buffer_impl validates that buffer.desc.readonly is false (base.rs:608-610). The unsafe cast is protected by this prior validation, making the SAFETY comment accurate. No additional verification is needed.

crates/vm/src/stdlib/ctypes/simple.rs (2)

1088-1098: LGTM!

The Initializer implementation correctly delegates to set_value when an argument is provided, enabling proper reinitialization through __init__ calls.


1126-1129: LGTM!

Adding Initializer to the with(...) clause correctly enables the __init__ slot for PyCSimple instances.

@youknowone youknowone force-pushed the ctypes branch 2 times, most recently from c1cd643 to 9fe87f7 Compare December 29, 2025 15:58
@youknowone youknowone merged commit 2f4ca50 into RustPython:main Dec 29, 2025
1 check passed
@youknowone youknowone deleted the ctypes branch December 29, 2025 15:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant