Patchwork [5,of,9] rust-cpython: remove useless Option<$leaked> from py_shared_iterator

login
register
mail settings
Submitter Yuya Nishihara
Date Oct. 19, 2019, 10:07 a.m.
Message ID <06542ced4e50bd5a5a09.1571479642@mimosa>
Download mbox | patch
Permalink /patch/42498/
State New
Headers show

Comments

Yuya Nishihara - Oct. 19, 2019, 10:07 a.m.
# HG changeset patch
# User Yuya Nishihara <yuya@tcha.org>
# Date 1570880910 -32400
#      Sat Oct 12 20:48:30 2019 +0900
# Node ID 06542ced4e50bd5a5a09ef235fbc33596a47aaac
# Parent  edff1318e27ba262a44f7f8d7fcf6c44cee43429
rust-cpython: remove useless Option<$leaked> from py_shared_iterator

We no longer need to carefully drop the iterator when it's consumed. Mutation
is allowed even if the iterator exists.

There's a minor behavior change: next(iter) may return/raise something other
than StopIteration if it's called after the iterator has been fully consumed,
and if the Rust object isn't a FusedIterator.

Patch

diff --git a/rust/hg-cpython/src/ref_sharing.rs b/rust/hg-cpython/src/ref_sharing.rs
--- a/rust/hg-cpython/src/ref_sharing.rs
+++ b/rust/hg-cpython/src/ref_sharing.rs
@@ -570,25 +570,14 @@  macro_rules! py_shared_iterator {
         $success_type: ty
     ) => {
         py_class!(pub class $name |py| {
-            data inner: RefCell<Option<$leaked>>;
+            data inner: RefCell<$leaked>;
 
             def __next__(&self) -> PyResult<$success_type> {
-                let mut inner_opt = self.inner(py).borrow_mut();
-                if let Some(leaked) = inner_opt.as_mut() {
-                    let mut iter = leaked.try_borrow_mut(py)?;
-                    match iter.next() {
-                        None => {
-                            drop(iter);
-                            // replace Some(inner) by None, drop $leaked
-                            inner_opt.take();
-                            Ok(None)
-                        }
-                        Some(res) => {
-                            $success_func(py, res)
-                        }
-                    }
-                } else {
-                    Ok(None)
+                let mut leaked = self.inner(py).borrow_mut();
+                let mut iter = leaked.try_borrow_mut(py)?;
+                match iter.next() {
+                    None => Ok(None),
+                    Some(res) => $success_func(py, res),
                 }
             }
 
@@ -604,7 +593,7 @@  macro_rules! py_shared_iterator {
             ) -> PyResult<Self> {
                 Self::create_instance(
                     py,
-                    RefCell::new(Some(leaked)),
+                    RefCell::new(leaked),
                 )
             }
         }