-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Initializer for PyCSimple, PyCArray #6581
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
|
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 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. 📒 Files selected for processing (3)
📝 WalkthroughWalkthroughThis PR introduces Changes
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
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. Comment |
There was a problem hiding this 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) checksargs.args.len() > lengthand returns a "too many initializers" error. ThisInitializerrelies onsetitem_by_indexwhich 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 betweenCow::BorrowedandCow::Ownedbranches.The
Cow::Borrowedbranch uses.min()which silently truncates if buffer lengths differ (line 1305), whileCow::Ownedusescopy_from_slicewhich 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
📒 Files selected for processing (2)
crates/vm/src/stdlib/ctypes/array.rscrates/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 runningcargo fmtto 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.rscrates/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
Cowimport is correctly added to support the memory-aware buffer handling insetitem_by_index.
471-474: LGTM!Adding
Initializerto thewith(...)clause correctly enables the__init__slot implementation forPyCArray.
887-904: The writable buffer invariant is enforced through runtime validation infrom_buffer_impl. The code at lines 887-904 is safe becauseCow::Borrowedbuffers from external sources are only created afterfrom_buffer_implvalidates thatbuffer.desc.readonlyis 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
Initializerimplementation correctly delegates toset_valuewhen an argument is provided, enabling proper reinitialization through__init__calls.
1126-1129: LGTM!Adding
Initializerto thewith(...)clause correctly enables the__init__slot forPyCSimpleinstances.
c1cd643 to
9fe87f7
Compare
Summary by CodeRabbit
Release Notes
✏️ Tip: You can customize this high-level summary in your review settings.