##// END OF EJS Templates
rust-cpython: replace dyn Iterator<..> of sequence with concrete type...
Yuya Nishihara -
r43157:706104dc default
parent child Browse files
Show More
@@ -1,127 +1,130 b''
1 // dirs_multiset.rs
1 // dirs_multiset.rs
2 //
2 //
3 // Copyright 2019 Raphaël Gomès <rgomes@octobus.net>
3 // Copyright 2019 Raphaël Gomès <rgomes@octobus.net>
4 //
4 //
5 // This software may be used and distributed according to the terms of the
5 // This software may be used and distributed according to the terms of the
6 // GNU General Public License version 2 or any later version.
6 // GNU General Public License version 2 or any later version.
7
7
8 //! Bindings for the `hg::dirstate::dirs_multiset` file provided by the
8 //! Bindings for the `hg::dirstate::dirs_multiset` file provided by the
9 //! `hg-core` package.
9 //! `hg-core` package.
10
10
11 use std::cell::RefCell;
11 use std::cell::RefCell;
12 use std::convert::TryInto;
12 use std::convert::TryInto;
13
13
14 use cpython::{
14 use cpython::{
15 exc, ObjectProtocol, PyBytes, PyClone, PyDict, PyErr, PyObject, PyResult,
15 exc, ObjectProtocol, PyBytes, PyClone, PyDict, PyErr, PyObject, PyResult,
16 Python,
16 Python,
17 };
17 };
18
18
19 use crate::dirstate::extract_dirstate;
19 use crate::dirstate::extract_dirstate;
20 use crate::ref_sharing::{PySharedRefCell, PySharedState};
20 use crate::ref_sharing::{PySharedRefCell, PySharedState};
21 use hg::{DirsMultiset, DirstateMapError, DirstateParseError, EntryState};
21 use hg::{
22 DirsMultiset, DirsMultisetIter, DirstateMapError, DirstateParseError,
23 EntryState,
24 };
22
25
23 py_class!(pub class Dirs |py| {
26 py_class!(pub class Dirs |py| {
24 data inner: PySharedRefCell<DirsMultiset>;
27 data inner: PySharedRefCell<DirsMultiset>;
25 data py_shared_state: PySharedState;
28 data py_shared_state: PySharedState;
26
29
27 // `map` is either a `dict` or a flat iterator (usually a `set`, sometimes
30 // `map` is either a `dict` or a flat iterator (usually a `set`, sometimes
28 // a `list`)
31 // a `list`)
29 def __new__(
32 def __new__(
30 _cls,
33 _cls,
31 map: PyObject,
34 map: PyObject,
32 skip: Option<PyObject> = None
35 skip: Option<PyObject> = None
33 ) -> PyResult<Self> {
36 ) -> PyResult<Self> {
34 let mut skip_state: Option<EntryState> = None;
37 let mut skip_state: Option<EntryState> = None;
35 if let Some(skip) = skip {
38 if let Some(skip) = skip {
36 skip_state = Some(
39 skip_state = Some(
37 skip.extract::<PyBytes>(py)?.data(py)[0]
40 skip.extract::<PyBytes>(py)?.data(py)[0]
38 .try_into()
41 .try_into()
39 .map_err(|e: DirstateParseError| {
42 .map_err(|e: DirstateParseError| {
40 PyErr::new::<exc::ValueError, _>(py, e.to_string())
43 PyErr::new::<exc::ValueError, _>(py, e.to_string())
41 })?,
44 })?,
42 );
45 );
43 }
46 }
44 let inner = if let Ok(map) = map.cast_as::<PyDict>(py) {
47 let inner = if let Ok(map) = map.cast_as::<PyDict>(py) {
45 let dirstate = extract_dirstate(py, &map)?;
48 let dirstate = extract_dirstate(py, &map)?;
46 DirsMultiset::from_dirstate(&dirstate, skip_state)
49 DirsMultiset::from_dirstate(&dirstate, skip_state)
47 } else {
50 } else {
48 let map: Result<Vec<Vec<u8>>, PyErr> = map
51 let map: Result<Vec<Vec<u8>>, PyErr> = map
49 .iter(py)?
52 .iter(py)?
50 .map(|o| Ok(o?.extract::<PyBytes>(py)?.data(py).to_owned()))
53 .map(|o| Ok(o?.extract::<PyBytes>(py)?.data(py).to_owned()))
51 .collect();
54 .collect();
52 DirsMultiset::from_manifest(&map?)
55 DirsMultiset::from_manifest(&map?)
53 };
56 };
54
57
55 Self::create_instance(
58 Self::create_instance(
56 py,
59 py,
57 PySharedRefCell::new(inner),
60 PySharedRefCell::new(inner),
58 PySharedState::default()
61 PySharedState::default()
59 )
62 )
60 }
63 }
61
64
62 def addpath(&self, path: PyObject) -> PyResult<PyObject> {
65 def addpath(&self, path: PyObject) -> PyResult<PyObject> {
63 self.borrow_mut(py)?.add_path(
66 self.borrow_mut(py)?.add_path(
64 path.extract::<PyBytes>(py)?.data(py),
67 path.extract::<PyBytes>(py)?.data(py),
65 );
68 );
66 Ok(py.None())
69 Ok(py.None())
67 }
70 }
68
71
69 def delpath(&self, path: PyObject) -> PyResult<PyObject> {
72 def delpath(&self, path: PyObject) -> PyResult<PyObject> {
70 self.borrow_mut(py)?.delete_path(
73 self.borrow_mut(py)?.delete_path(
71 path.extract::<PyBytes>(py)?.data(py),
74 path.extract::<PyBytes>(py)?.data(py),
72 )
75 )
73 .and(Ok(py.None()))
76 .and(Ok(py.None()))
74 .or_else(|e| {
77 .or_else(|e| {
75 match e {
78 match e {
76 DirstateMapError::PathNotFound(_p) => {
79 DirstateMapError::PathNotFound(_p) => {
77 Err(PyErr::new::<exc::ValueError, _>(
80 Err(PyErr::new::<exc::ValueError, _>(
78 py,
81 py,
79 "expected a value, found none".to_string(),
82 "expected a value, found none".to_string(),
80 ))
83 ))
81 }
84 }
82 DirstateMapError::EmptyPath => {
85 DirstateMapError::EmptyPath => {
83 Ok(py.None())
86 Ok(py.None())
84 }
87 }
85 }
88 }
86 })
89 })
87 }
90 }
88 def __iter__(&self) -> PyResult<DirsMultisetKeysIterator> {
91 def __iter__(&self) -> PyResult<DirsMultisetKeysIterator> {
89 let (leak_handle, leaked_ref) = unsafe { self.leak_immutable(py)? };
92 let (leak_handle, leaked_ref) = unsafe { self.leak_immutable(py)? };
90 DirsMultisetKeysIterator::create_instance(
93 DirsMultisetKeysIterator::create_instance(
91 py,
94 py,
92 RefCell::new(Some(leak_handle)),
95 RefCell::new(Some(leak_handle)),
93 RefCell::new(Box::new(leaked_ref.iter())),
96 RefCell::new(leaked_ref.iter()),
94 )
97 )
95 }
98 }
96
99
97 def __contains__(&self, item: PyObject) -> PyResult<bool> {
100 def __contains__(&self, item: PyObject) -> PyResult<bool> {
98 Ok(self
101 Ok(self
99 .inner(py)
102 .inner(py)
100 .borrow()
103 .borrow()
101 .contains(item.extract::<PyBytes>(py)?.data(py).as_ref()))
104 .contains(item.extract::<PyBytes>(py)?.data(py).as_ref()))
102 }
105 }
103 });
106 });
104
107
105 py_shared_ref!(Dirs, DirsMultiset, inner, DirsMultisetLeakedRef,);
108 py_shared_ref!(Dirs, DirsMultiset, inner, DirsMultisetLeakedRef,);
106
109
107 impl Dirs {
110 impl Dirs {
108 pub fn from_inner(py: Python, d: DirsMultiset) -> PyResult<Self> {
111 pub fn from_inner(py: Python, d: DirsMultiset) -> PyResult<Self> {
109 Self::create_instance(
112 Self::create_instance(
110 py,
113 py,
111 PySharedRefCell::new(d),
114 PySharedRefCell::new(d),
112 PySharedState::default(),
115 PySharedState::default(),
113 )
116 )
114 }
117 }
115
118
116 fn translate_key(py: Python, res: &Vec<u8>) -> PyResult<Option<PyBytes>> {
119 fn translate_key(py: Python, res: &Vec<u8>) -> PyResult<Option<PyBytes>> {
117 Ok(Some(PyBytes::new(py, res)))
120 Ok(Some(PyBytes::new(py, res)))
118 }
121 }
119 }
122 }
120
123
121 py_shared_sequence_iterator!(
124 py_shared_iterator_impl!(
122 DirsMultisetKeysIterator,
125 DirsMultisetKeysIterator,
123 DirsMultisetLeakedRef,
126 DirsMultisetLeakedRef,
124 Vec<u8>,
127 DirsMultisetIter<'static>,
125 Dirs::translate_key,
128 Dirs::translate_key,
126 Option<PyBytes>
129 Option<PyBytes>
127 );
130 );
@@ -1,439 +1,419 b''
1 // macros.rs
1 // macros.rs
2 //
2 //
3 // Copyright 2019 Raphaël Gomès <rgomes@octobus.net>
3 // Copyright 2019 Raphaël Gomès <rgomes@octobus.net>
4 //
4 //
5 // This software may be used and distributed according to the terms of the
5 // This software may be used and distributed according to the terms of the
6 // GNU General Public License version 2 or any later version.
6 // GNU General Public License version 2 or any later version.
7
7
8 //! Macros for use in the `hg-cpython` bridge library.
8 //! Macros for use in the `hg-cpython` bridge library.
9
9
10 use crate::exceptions::AlreadyBorrowed;
10 use crate::exceptions::AlreadyBorrowed;
11 use cpython::{PyResult, Python};
11 use cpython::{PyResult, Python};
12 use std::cell::{Cell, Ref, RefCell, RefMut};
12 use std::cell::{Cell, Ref, RefCell, RefMut};
13
13
14 /// Manages the shared state between Python and Rust
14 /// Manages the shared state between Python and Rust
15 #[derive(Default)]
15 #[derive(Default)]
16 pub struct PySharedState {
16 pub struct PySharedState {
17 leak_count: Cell<usize>,
17 leak_count: Cell<usize>,
18 mutably_borrowed: Cell<bool>,
18 mutably_borrowed: Cell<bool>,
19 }
19 }
20
20
21 impl PySharedState {
21 impl PySharedState {
22 pub fn borrow_mut<'a, T>(
22 pub fn borrow_mut<'a, T>(
23 &'a self,
23 &'a self,
24 py: Python<'a>,
24 py: Python<'a>,
25 pyrefmut: RefMut<'a, T>,
25 pyrefmut: RefMut<'a, T>,
26 ) -> PyResult<PyRefMut<'a, T>> {
26 ) -> PyResult<PyRefMut<'a, T>> {
27 if self.mutably_borrowed.get() {
27 if self.mutably_borrowed.get() {
28 return Err(AlreadyBorrowed::new(
28 return Err(AlreadyBorrowed::new(
29 py,
29 py,
30 "Cannot borrow mutably while there exists another \
30 "Cannot borrow mutably while there exists another \
31 mutable reference in a Python object",
31 mutable reference in a Python object",
32 ));
32 ));
33 }
33 }
34 match self.leak_count.get() {
34 match self.leak_count.get() {
35 0 => {
35 0 => {
36 self.mutably_borrowed.replace(true);
36 self.mutably_borrowed.replace(true);
37 Ok(PyRefMut::new(py, pyrefmut, self))
37 Ok(PyRefMut::new(py, pyrefmut, self))
38 }
38 }
39 // TODO
39 // TODO
40 // For now, this works differently than Python references
40 // For now, this works differently than Python references
41 // in the case of iterators.
41 // in the case of iterators.
42 // Python does not complain when the data an iterator
42 // Python does not complain when the data an iterator
43 // points to is modified if the iterator is never used
43 // points to is modified if the iterator is never used
44 // afterwards.
44 // afterwards.
45 // Here, we are stricter than this by refusing to give a
45 // Here, we are stricter than this by refusing to give a
46 // mutable reference if it is already borrowed.
46 // mutable reference if it is already borrowed.
47 // While the additional safety might be argued for, it
47 // While the additional safety might be argued for, it
48 // breaks valid programming patterns in Python and we need
48 // breaks valid programming patterns in Python and we need
49 // to fix this issue down the line.
49 // to fix this issue down the line.
50 _ => Err(AlreadyBorrowed::new(
50 _ => Err(AlreadyBorrowed::new(
51 py,
51 py,
52 "Cannot borrow mutably while there are \
52 "Cannot borrow mutably while there are \
53 immutable references in Python objects",
53 immutable references in Python objects",
54 )),
54 )),
55 }
55 }
56 }
56 }
57
57
58 /// Return a reference to the wrapped data with an artificial static
58 /// Return a reference to the wrapped data with an artificial static
59 /// lifetime.
59 /// lifetime.
60 /// We need to be protected by the GIL for thread-safety.
60 /// We need to be protected by the GIL for thread-safety.
61 ///
61 ///
62 /// # Safety
62 /// # Safety
63 ///
63 ///
64 /// This is highly unsafe since the lifetime of the given data can be
64 /// This is highly unsafe since the lifetime of the given data can be
65 /// extended. Do not call this function directly.
65 /// extended. Do not call this function directly.
66 pub unsafe fn leak_immutable<T>(
66 pub unsafe fn leak_immutable<T>(
67 &self,
67 &self,
68 py: Python,
68 py: Python,
69 data: &PySharedRefCell<T>,
69 data: &PySharedRefCell<T>,
70 ) -> PyResult<&'static T> {
70 ) -> PyResult<&'static T> {
71 if self.mutably_borrowed.get() {
71 if self.mutably_borrowed.get() {
72 return Err(AlreadyBorrowed::new(
72 return Err(AlreadyBorrowed::new(
73 py,
73 py,
74 "Cannot borrow immutably while there is a \
74 "Cannot borrow immutably while there is a \
75 mutable reference in Python objects",
75 mutable reference in Python objects",
76 ));
76 ));
77 }
77 }
78 let ptr = data.as_ptr();
78 let ptr = data.as_ptr();
79 self.leak_count.replace(self.leak_count.get() + 1);
79 self.leak_count.replace(self.leak_count.get() + 1);
80 Ok(&*ptr)
80 Ok(&*ptr)
81 }
81 }
82
82
83 /// # Safety
83 /// # Safety
84 ///
84 ///
85 /// It's unsafe to update the reference count without knowing the
85 /// It's unsafe to update the reference count without knowing the
86 /// reference is deleted. Do not call this function directly.
86 /// reference is deleted. Do not call this function directly.
87 pub unsafe fn decrease_leak_count(&self, _py: Python, mutable: bool) {
87 pub unsafe fn decrease_leak_count(&self, _py: Python, mutable: bool) {
88 self.leak_count
88 self.leak_count
89 .replace(self.leak_count.get().saturating_sub(1));
89 .replace(self.leak_count.get().saturating_sub(1));
90 if mutable {
90 if mutable {
91 self.mutably_borrowed.replace(false);
91 self.mutably_borrowed.replace(false);
92 }
92 }
93 }
93 }
94 }
94 }
95
95
96 /// `RefCell` wrapper to be safely used in conjunction with `PySharedState`.
96 /// `RefCell` wrapper to be safely used in conjunction with `PySharedState`.
97 ///
97 ///
98 /// Only immutable operation is allowed through this interface.
98 /// Only immutable operation is allowed through this interface.
99 #[derive(Debug)]
99 #[derive(Debug)]
100 pub struct PySharedRefCell<T> {
100 pub struct PySharedRefCell<T> {
101 inner: RefCell<T>,
101 inner: RefCell<T>,
102 }
102 }
103
103
104 impl<T> PySharedRefCell<T> {
104 impl<T> PySharedRefCell<T> {
105 pub const fn new(value: T) -> PySharedRefCell<T> {
105 pub const fn new(value: T) -> PySharedRefCell<T> {
106 Self {
106 Self {
107 inner: RefCell::new(value),
107 inner: RefCell::new(value),
108 }
108 }
109 }
109 }
110
110
111 pub fn borrow(&self) -> Ref<T> {
111 pub fn borrow(&self) -> Ref<T> {
112 // py_shared_state isn't involved since
112 // py_shared_state isn't involved since
113 // - inner.borrow() would fail if self is mutably borrowed,
113 // - inner.borrow() would fail if self is mutably borrowed,
114 // - and inner.borrow_mut() would fail while self is borrowed.
114 // - and inner.borrow_mut() would fail while self is borrowed.
115 self.inner.borrow()
115 self.inner.borrow()
116 }
116 }
117
117
118 pub fn as_ptr(&self) -> *mut T {
118 pub fn as_ptr(&self) -> *mut T {
119 self.inner.as_ptr()
119 self.inner.as_ptr()
120 }
120 }
121
121
122 pub unsafe fn borrow_mut(&self) -> RefMut<T> {
122 pub unsafe fn borrow_mut(&self) -> RefMut<T> {
123 // must be borrowed by self.py_shared_state(py).borrow_mut().
123 // must be borrowed by self.py_shared_state(py).borrow_mut().
124 self.inner.borrow_mut()
124 self.inner.borrow_mut()
125 }
125 }
126 }
126 }
127
127
128 /// Holds a mutable reference to data shared between Python and Rust.
128 /// Holds a mutable reference to data shared between Python and Rust.
129 pub struct PyRefMut<'a, T> {
129 pub struct PyRefMut<'a, T> {
130 inner: RefMut<'a, T>,
130 inner: RefMut<'a, T>,
131 py_shared_state: &'a PySharedState,
131 py_shared_state: &'a PySharedState,
132 }
132 }
133
133
134 impl<'a, T> PyRefMut<'a, T> {
134 impl<'a, T> PyRefMut<'a, T> {
135 // Must be constructed by PySharedState after checking its leak_count.
135 // Must be constructed by PySharedState after checking its leak_count.
136 // Otherwise, drop() would incorrectly update the state.
136 // Otherwise, drop() would incorrectly update the state.
137 fn new(
137 fn new(
138 _py: Python<'a>,
138 _py: Python<'a>,
139 inner: RefMut<'a, T>,
139 inner: RefMut<'a, T>,
140 py_shared_state: &'a PySharedState,
140 py_shared_state: &'a PySharedState,
141 ) -> Self {
141 ) -> Self {
142 Self {
142 Self {
143 inner,
143 inner,
144 py_shared_state,
144 py_shared_state,
145 }
145 }
146 }
146 }
147 }
147 }
148
148
149 impl<'a, T> std::ops::Deref for PyRefMut<'a, T> {
149 impl<'a, T> std::ops::Deref for PyRefMut<'a, T> {
150 type Target = RefMut<'a, T>;
150 type Target = RefMut<'a, T>;
151
151
152 fn deref(&self) -> &Self::Target {
152 fn deref(&self) -> &Self::Target {
153 &self.inner
153 &self.inner
154 }
154 }
155 }
155 }
156 impl<'a, T> std::ops::DerefMut for PyRefMut<'a, T> {
156 impl<'a, T> std::ops::DerefMut for PyRefMut<'a, T> {
157 fn deref_mut(&mut self) -> &mut Self::Target {
157 fn deref_mut(&mut self) -> &mut Self::Target {
158 &mut self.inner
158 &mut self.inner
159 }
159 }
160 }
160 }
161
161
162 impl<'a, T> Drop for PyRefMut<'a, T> {
162 impl<'a, T> Drop for PyRefMut<'a, T> {
163 fn drop(&mut self) {
163 fn drop(&mut self) {
164 let gil = Python::acquire_gil();
164 let gil = Python::acquire_gil();
165 let py = gil.python();
165 let py = gil.python();
166 unsafe {
166 unsafe {
167 self.py_shared_state.decrease_leak_count(py, true);
167 self.py_shared_state.decrease_leak_count(py, true);
168 }
168 }
169 }
169 }
170 }
170 }
171
171
172 /// Allows a `py_class!` generated struct to share references to one of its
172 /// Allows a `py_class!` generated struct to share references to one of its
173 /// data members with Python.
173 /// data members with Python.
174 ///
174 ///
175 /// # Warning
175 /// # Warning
176 ///
176 ///
177 /// The targeted `py_class!` needs to have the
177 /// The targeted `py_class!` needs to have the
178 /// `data py_shared_state: PySharedState;` data attribute to compile.
178 /// `data py_shared_state: PySharedState;` data attribute to compile.
179 /// A better, more complicated macro is needed to automatically insert it,
179 /// A better, more complicated macro is needed to automatically insert it,
180 /// but this one is not yet really battle tested (what happens when
180 /// but this one is not yet really battle tested (what happens when
181 /// multiple references are needed?). See the example below.
181 /// multiple references are needed?). See the example below.
182 ///
182 ///
183 /// TODO allow Python container types: for now, integration with the garbage
183 /// TODO allow Python container types: for now, integration with the garbage
184 /// collector does not extend to Rust structs holding references to Python
184 /// collector does not extend to Rust structs holding references to Python
185 /// objects. Should the need surface, `__traverse__` and `__clear__` will
185 /// objects. Should the need surface, `__traverse__` and `__clear__` will
186 /// need to be written as per the `rust-cpython` docs on GC integration.
186 /// need to be written as per the `rust-cpython` docs on GC integration.
187 ///
187 ///
188 /// # Parameters
188 /// # Parameters
189 ///
189 ///
190 /// * `$name` is the same identifier used in for `py_class!` macro call.
190 /// * `$name` is the same identifier used in for `py_class!` macro call.
191 /// * `$inner_struct` is the identifier of the underlying Rust struct
191 /// * `$inner_struct` is the identifier of the underlying Rust struct
192 /// * `$data_member` is the identifier of the data member of `$inner_struct`
192 /// * `$data_member` is the identifier of the data member of `$inner_struct`
193 /// that will be shared.
193 /// that will be shared.
194 /// * `$leaked` is the identifier to give to the struct that will manage
194 /// * `$leaked` is the identifier to give to the struct that will manage
195 /// references to `$name`, to be used for example in other macros like
195 /// references to `$name`, to be used for example in other macros like
196 /// `py_shared_mapping_iterator`.
196 /// `py_shared_mapping_iterator`.
197 ///
197 ///
198 /// # Example
198 /// # Example
199 ///
199 ///
200 /// ```
200 /// ```
201 /// struct MyStruct {
201 /// struct MyStruct {
202 /// inner: Vec<u32>;
202 /// inner: Vec<u32>;
203 /// }
203 /// }
204 ///
204 ///
205 /// py_class!(pub class MyType |py| {
205 /// py_class!(pub class MyType |py| {
206 /// data inner: PySharedRefCell<MyStruct>;
206 /// data inner: PySharedRefCell<MyStruct>;
207 /// data py_shared_state: PySharedState;
207 /// data py_shared_state: PySharedState;
208 /// });
208 /// });
209 ///
209 ///
210 /// py_shared_ref!(MyType, MyStruct, inner, MyTypeLeakedRef);
210 /// py_shared_ref!(MyType, MyStruct, inner, MyTypeLeakedRef);
211 /// ```
211 /// ```
212 macro_rules! py_shared_ref {
212 macro_rules! py_shared_ref {
213 (
213 (
214 $name: ident,
214 $name: ident,
215 $inner_struct: ident,
215 $inner_struct: ident,
216 $data_member: ident,
216 $data_member: ident,
217 $leaked: ident,
217 $leaked: ident,
218 ) => {
218 ) => {
219 impl $name {
219 impl $name {
220 fn borrow_mut<'a>(
220 fn borrow_mut<'a>(
221 &'a self,
221 &'a self,
222 py: Python<'a>,
222 py: Python<'a>,
223 ) -> PyResult<crate::ref_sharing::PyRefMut<'a, $inner_struct>>
223 ) -> PyResult<crate::ref_sharing::PyRefMut<'a, $inner_struct>>
224 {
224 {
225 // assert $data_member type
225 // assert $data_member type
226 use crate::ref_sharing::PySharedRefCell;
226 use crate::ref_sharing::PySharedRefCell;
227 let data: &PySharedRefCell<_> = self.$data_member(py);
227 let data: &PySharedRefCell<_> = self.$data_member(py);
228 self.py_shared_state(py)
228 self.py_shared_state(py)
229 .borrow_mut(py, unsafe { data.borrow_mut() })
229 .borrow_mut(py, unsafe { data.borrow_mut() })
230 }
230 }
231
231
232 /// Returns a leaked reference and its management object.
232 /// Returns a leaked reference and its management object.
233 ///
233 ///
234 /// # Safety
234 /// # Safety
235 ///
235 ///
236 /// It's up to you to make sure that the management object lives
236 /// It's up to you to make sure that the management object lives
237 /// longer than the leaked reference. Otherwise, you'll get a
237 /// longer than the leaked reference. Otherwise, you'll get a
238 /// dangling reference.
238 /// dangling reference.
239 unsafe fn leak_immutable<'a>(
239 unsafe fn leak_immutable<'a>(
240 &'a self,
240 &'a self,
241 py: Python<'a>,
241 py: Python<'a>,
242 ) -> PyResult<($leaked, &'static $inner_struct)> {
242 ) -> PyResult<($leaked, &'static $inner_struct)> {
243 // assert $data_member type
243 // assert $data_member type
244 use crate::ref_sharing::PySharedRefCell;
244 use crate::ref_sharing::PySharedRefCell;
245 let data: &PySharedRefCell<_> = self.$data_member(py);
245 let data: &PySharedRefCell<_> = self.$data_member(py);
246 let static_ref =
246 let static_ref =
247 self.py_shared_state(py).leak_immutable(py, data)?;
247 self.py_shared_state(py).leak_immutable(py, data)?;
248 let leak_handle = $leaked::new(py, self);
248 let leak_handle = $leaked::new(py, self);
249 Ok((leak_handle, static_ref))
249 Ok((leak_handle, static_ref))
250 }
250 }
251 }
251 }
252
252
253 /// Manage immutable references to `$name` leaked into Python
253 /// Manage immutable references to `$name` leaked into Python
254 /// iterators.
254 /// iterators.
255 ///
255 ///
256 /// In truth, this does not represent leaked references themselves;
256 /// In truth, this does not represent leaked references themselves;
257 /// it is instead useful alongside them to manage them.
257 /// it is instead useful alongside them to manage them.
258 pub struct $leaked {
258 pub struct $leaked {
259 inner: $name,
259 inner: $name,
260 }
260 }
261
261
262 impl $leaked {
262 impl $leaked {
263 // Marked as unsafe so client code wouldn't construct $leaked
263 // Marked as unsafe so client code wouldn't construct $leaked
264 // struct by mistake. Its drop() is unsafe.
264 // struct by mistake. Its drop() is unsafe.
265 unsafe fn new(py: Python, inner: &$name) -> Self {
265 unsafe fn new(py: Python, inner: &$name) -> Self {
266 Self {
266 Self {
267 inner: inner.clone_ref(py),
267 inner: inner.clone_ref(py),
268 }
268 }
269 }
269 }
270 }
270 }
271
271
272 impl Drop for $leaked {
272 impl Drop for $leaked {
273 fn drop(&mut self) {
273 fn drop(&mut self) {
274 let gil = Python::acquire_gil();
274 let gil = Python::acquire_gil();
275 let py = gil.python();
275 let py = gil.python();
276 let state = self.inner.py_shared_state(py);
276 let state = self.inner.py_shared_state(py);
277 unsafe {
277 unsafe {
278 state.decrease_leak_count(py, false);
278 state.decrease_leak_count(py, false);
279 }
279 }
280 }
280 }
281 }
281 }
282 };
282 };
283 }
283 }
284
284
285 /// Defines a `py_class!` that acts as a Python iterator over a Rust iterator.
285 /// Defines a `py_class!` that acts as a Python iterator over a Rust iterator.
286 macro_rules! py_shared_iterator_impl {
286 macro_rules! py_shared_iterator_impl {
287 (
287 (
288 $name: ident,
288 $name: ident,
289 $leaked: ident,
289 $leaked: ident,
290 $iterator_type: ty,
290 $iterator_type: ty,
291 $success_func: expr,
291 $success_func: expr,
292 $success_type: ty
292 $success_type: ty
293 ) => {
293 ) => {
294 py_class!(pub class $name |py| {
294 py_class!(pub class $name |py| {
295 data inner: RefCell<Option<$leaked>>;
295 data inner: RefCell<Option<$leaked>>;
296 data it: RefCell<$iterator_type>;
296 data it: RefCell<$iterator_type>;
297
297
298 def __next__(&self) -> PyResult<$success_type> {
298 def __next__(&self) -> PyResult<$success_type> {
299 let mut inner_opt = self.inner(py).borrow_mut();
299 let mut inner_opt = self.inner(py).borrow_mut();
300 if inner_opt.is_some() {
300 if inner_opt.is_some() {
301 match self.it(py).borrow_mut().next() {
301 match self.it(py).borrow_mut().next() {
302 None => {
302 None => {
303 // replace Some(inner) by None, drop $leaked
303 // replace Some(inner) by None, drop $leaked
304 inner_opt.take();
304 inner_opt.take();
305 Ok(None)
305 Ok(None)
306 }
306 }
307 Some(res) => {
307 Some(res) => {
308 $success_func(py, res)
308 $success_func(py, res)
309 }
309 }
310 }
310 }
311 } else {
311 } else {
312 Ok(None)
312 Ok(None)
313 }
313 }
314 }
314 }
315
315
316 def __iter__(&self) -> PyResult<Self> {
316 def __iter__(&self) -> PyResult<Self> {
317 Ok(self.clone_ref(py))
317 Ok(self.clone_ref(py))
318 }
318 }
319 });
319 });
320
320
321 impl $name {
321 impl $name {
322 pub fn from_inner(
322 pub fn from_inner(
323 py: Python,
323 py: Python,
324 leaked: Option<$leaked>,
324 leaked: Option<$leaked>,
325 it: $iterator_type
325 it: $iterator_type
326 ) -> PyResult<Self> {
326 ) -> PyResult<Self> {
327 Self::create_instance(
327 Self::create_instance(
328 py,
328 py,
329 RefCell::new(leaked),
329 RefCell::new(leaked),
330 RefCell::new(it)
330 RefCell::new(it)
331 )
331 )
332 }
332 }
333 }
333 }
334 };
334 };
335 }
335 }
336
336
337 /// Defines a `py_class!` that acts as a Python mapping iterator over a Rust
337 /// Defines a `py_class!` that acts as a Python mapping iterator over a Rust
338 /// iterator.
338 /// iterator.
339 ///
339 ///
340 /// TODO: this is a bit awkward to use, and a better (more complicated)
340 /// TODO: this is a bit awkward to use, and a better (more complicated)
341 /// procedural macro would simplify the interface a lot.
341 /// procedural macro would simplify the interface a lot.
342 ///
342 ///
343 /// # Parameters
343 /// # Parameters
344 ///
344 ///
345 /// * `$name` is the identifier to give to the resulting Rust struct.
345 /// * `$name` is the identifier to give to the resulting Rust struct.
346 /// * `$leaked` corresponds to `$leaked` in the matching `py_shared_ref!` call.
346 /// * `$leaked` corresponds to `$leaked` in the matching `py_shared_ref!` call.
347 /// * `$key_type` is the type of the key in the mapping
347 /// * `$key_type` is the type of the key in the mapping
348 /// * `$value_type` is the type of the value in the mapping
348 /// * `$value_type` is the type of the value in the mapping
349 /// * `$success_func` is a function for processing the Rust `(key, value)`
349 /// * `$success_func` is a function for processing the Rust `(key, value)`
350 /// tuple on iteration success, turning it into something Python understands.
350 /// tuple on iteration success, turning it into something Python understands.
351 /// * `$success_func` is the return type of `$success_func`
351 /// * `$success_func` is the return type of `$success_func`
352 ///
352 ///
353 /// # Example
353 /// # Example
354 ///
354 ///
355 /// ```
355 /// ```
356 /// struct MyStruct {
356 /// struct MyStruct {
357 /// inner: HashMap<Vec<u8>, Vec<u8>>;
357 /// inner: HashMap<Vec<u8>, Vec<u8>>;
358 /// }
358 /// }
359 ///
359 ///
360 /// py_class!(pub class MyType |py| {
360 /// py_class!(pub class MyType |py| {
361 /// data inner: PySharedRefCell<MyStruct>;
361 /// data inner: PySharedRefCell<MyStruct>;
362 /// data py_shared_state: PySharedState;
362 /// data py_shared_state: PySharedState;
363 ///
363 ///
364 /// def __iter__(&self) -> PyResult<MyTypeItemsIterator> {
364 /// def __iter__(&self) -> PyResult<MyTypeItemsIterator> {
365 /// let (leak_handle, leaked_ref) = unsafe { self.leak_immutable(py)? };
365 /// let (leak_handle, leaked_ref) = unsafe { self.leak_immutable(py)? };
366 /// MyTypeItemsIterator::create_instance(
366 /// MyTypeItemsIterator::create_instance(
367 /// py,
367 /// py,
368 /// RefCell::new(Some(leak_handle)),
368 /// RefCell::new(Some(leak_handle)),
369 /// RefCell::new(leaked_ref.iter()),
369 /// RefCell::new(leaked_ref.iter()),
370 /// )
370 /// )
371 /// }
371 /// }
372 /// });
372 /// });
373 ///
373 ///
374 /// impl MyType {
374 /// impl MyType {
375 /// fn translate_key_value(
375 /// fn translate_key_value(
376 /// py: Python,
376 /// py: Python,
377 /// res: (&Vec<u8>, &Vec<u8>),
377 /// res: (&Vec<u8>, &Vec<u8>),
378 /// ) -> PyResult<Option<(PyBytes, PyBytes)>> {
378 /// ) -> PyResult<Option<(PyBytes, PyBytes)>> {
379 /// let (f, entry) = res;
379 /// let (f, entry) = res;
380 /// Ok(Some((
380 /// Ok(Some((
381 /// PyBytes::new(py, f),
381 /// PyBytes::new(py, f),
382 /// PyBytes::new(py, entry),
382 /// PyBytes::new(py, entry),
383 /// )))
383 /// )))
384 /// }
384 /// }
385 /// }
385 /// }
386 ///
386 ///
387 /// py_shared_ref!(MyType, MyStruct, inner, MyTypeLeakedRef);
387 /// py_shared_ref!(MyType, MyStruct, inner, MyTypeLeakedRef);
388 ///
388 ///
389 /// py_shared_mapping_iterator!(
389 /// py_shared_mapping_iterator!(
390 /// MyTypeItemsIterator,
390 /// MyTypeItemsIterator,
391 /// MyTypeLeakedRef,
391 /// MyTypeLeakedRef,
392 /// Vec<u8>,
392 /// Vec<u8>,
393 /// Vec<u8>,
393 /// Vec<u8>,
394 /// MyType::translate_key_value,
394 /// MyType::translate_key_value,
395 /// Option<(PyBytes, PyBytes)>
395 /// Option<(PyBytes, PyBytes)>
396 /// );
396 /// );
397 /// ```
397 /// ```
398 #[allow(unused)] // Removed in a future patch
398 #[allow(unused)] // Removed in a future patch
399 macro_rules! py_shared_mapping_iterator {
399 macro_rules! py_shared_mapping_iterator {
400 (
400 (
401 $name:ident,
401 $name:ident,
402 $leaked:ident,
402 $leaked:ident,
403 $key_type: ty,
403 $key_type: ty,
404 $value_type: ty,
404 $value_type: ty,
405 $success_func: path,
405 $success_func: path,
406 $success_type: ty
406 $success_type: ty
407 ) => {
407 ) => {
408 py_shared_iterator_impl!(
408 py_shared_iterator_impl!(
409 $name,
409 $name,
410 $leaked,
410 $leaked,
411 Box<
411 Box<
412 dyn Iterator<Item = (&'static $key_type, &'static $value_type)>
412 dyn Iterator<Item = (&'static $key_type, &'static $value_type)>
413 + Send,
413 + Send,
414 >,
414 >,
415 $success_func,
415 $success_func,
416 $success_type
416 $success_type
417 );
417 );
418 };
418 };
419 }
419 }
420
421 /// Works basically the same as `py_shared_mapping_iterator`, but with only a
422 /// key.
423 macro_rules! py_shared_sequence_iterator {
424 (
425 $name:ident,
426 $leaked:ident,
427 $key_type: ty,
428 $success_func: path,
429 $success_type: ty
430 ) => {
431 py_shared_iterator_impl!(
432 $name,
433 $leaked,
434 Box<dyn Iterator<Item = &'static $key_type> + Send>,
435 $success_func,
436 $success_type
437 );
438 };
439 }
General Comments 0
You need to be logged in to leave comments. Login now