##// END OF EJS Templates
rust-cpython: require GIL to borrow immutable reference from PySharedRefCell...
Yuya Nishihara -
r43580:f8c114f2 default
parent child Browse files
Show More
@@ -1,129 +1,129 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::{PyLeakedRef, PySharedRefCell};
20 use crate::ref_sharing::{PyLeakedRef, PySharedRefCell};
21 use hg::{
21 use hg::{
22 utils::hg_path::{HgPath, HgPathBuf},
22 utils::hg_path::{HgPath, HgPathBuf},
23 DirsMultiset, DirsMultisetIter, DirstateMapError, DirstateParseError,
23 DirsMultiset, DirsMultisetIter, DirstateMapError, DirstateParseError,
24 EntryState,
24 EntryState,
25 };
25 };
26
26
27 py_class!(pub class Dirs |py| {
27 py_class!(pub class Dirs |py| {
28 data inner: PySharedRefCell<DirsMultiset>;
28 data inner: PySharedRefCell<DirsMultiset>;
29
29
30 // `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
31 // a `list`)
31 // a `list`)
32 def __new__(
32 def __new__(
33 _cls,
33 _cls,
34 map: PyObject,
34 map: PyObject,
35 skip: Option<PyObject> = None
35 skip: Option<PyObject> = None
36 ) -> PyResult<Self> {
36 ) -> PyResult<Self> {
37 let mut skip_state: Option<EntryState> = None;
37 let mut skip_state: Option<EntryState> = None;
38 if let Some(skip) = skip {
38 if let Some(skip) = skip {
39 skip_state = Some(
39 skip_state = Some(
40 skip.extract::<PyBytes>(py)?.data(py)[0]
40 skip.extract::<PyBytes>(py)?.data(py)[0]
41 .try_into()
41 .try_into()
42 .map_err(|e: DirstateParseError| {
42 .map_err(|e: DirstateParseError| {
43 PyErr::new::<exc::ValueError, _>(py, e.to_string())
43 PyErr::new::<exc::ValueError, _>(py, e.to_string())
44 })?,
44 })?,
45 );
45 );
46 }
46 }
47 let inner = if let Ok(map) = map.cast_as::<PyDict>(py) {
47 let inner = if let Ok(map) = map.cast_as::<PyDict>(py) {
48 let dirstate = extract_dirstate(py, &map)?;
48 let dirstate = extract_dirstate(py, &map)?;
49 DirsMultiset::from_dirstate(&dirstate, skip_state)
49 DirsMultiset::from_dirstate(&dirstate, skip_state)
50 } else {
50 } else {
51 let map: Result<Vec<HgPathBuf>, PyErr> = map
51 let map: Result<Vec<HgPathBuf>, PyErr> = map
52 .iter(py)?
52 .iter(py)?
53 .map(|o| {
53 .map(|o| {
54 Ok(HgPathBuf::from_bytes(
54 Ok(HgPathBuf::from_bytes(
55 o?.extract::<PyBytes>(py)?.data(py),
55 o?.extract::<PyBytes>(py)?.data(py),
56 ))
56 ))
57 })
57 })
58 .collect();
58 .collect();
59 DirsMultiset::from_manifest(&map?)
59 DirsMultiset::from_manifest(&map?)
60 };
60 };
61
61
62 Self::create_instance(
62 Self::create_instance(
63 py,
63 py,
64 PySharedRefCell::new(inner),
64 PySharedRefCell::new(inner),
65 )
65 )
66 }
66 }
67
67
68 def addpath(&self, path: PyObject) -> PyResult<PyObject> {
68 def addpath(&self, path: PyObject) -> PyResult<PyObject> {
69 self.inner_shared(py).borrow_mut()?.add_path(
69 self.inner_shared(py).borrow_mut()?.add_path(
70 HgPath::new(path.extract::<PyBytes>(py)?.data(py)),
70 HgPath::new(path.extract::<PyBytes>(py)?.data(py)),
71 );
71 );
72 Ok(py.None())
72 Ok(py.None())
73 }
73 }
74
74
75 def delpath(&self, path: PyObject) -> PyResult<PyObject> {
75 def delpath(&self, path: PyObject) -> PyResult<PyObject> {
76 self.inner_shared(py).borrow_mut()?.delete_path(
76 self.inner_shared(py).borrow_mut()?.delete_path(
77 HgPath::new(path.extract::<PyBytes>(py)?.data(py)),
77 HgPath::new(path.extract::<PyBytes>(py)?.data(py)),
78 )
78 )
79 .and(Ok(py.None()))
79 .and(Ok(py.None()))
80 .or_else(|e| {
80 .or_else(|e| {
81 match e {
81 match e {
82 DirstateMapError::PathNotFound(_p) => {
82 DirstateMapError::PathNotFound(_p) => {
83 Err(PyErr::new::<exc::ValueError, _>(
83 Err(PyErr::new::<exc::ValueError, _>(
84 py,
84 py,
85 "expected a value, found none".to_string(),
85 "expected a value, found none".to_string(),
86 ))
86 ))
87 }
87 }
88 DirstateMapError::EmptyPath => {
88 DirstateMapError::EmptyPath => {
89 Ok(py.None())
89 Ok(py.None())
90 }
90 }
91 }
91 }
92 })
92 })
93 }
93 }
94 def __iter__(&self) -> PyResult<DirsMultisetKeysIterator> {
94 def __iter__(&self) -> PyResult<DirsMultisetKeysIterator> {
95 let leaked_ref = self.inner_shared(py).leak_immutable()?;
95 let leaked_ref = self.inner_shared(py).leak_immutable()?;
96 DirsMultisetKeysIterator::from_inner(
96 DirsMultisetKeysIterator::from_inner(
97 py,
97 py,
98 unsafe { leaked_ref.map(py, |o| o.iter()) },
98 unsafe { leaked_ref.map(py, |o| o.iter()) },
99 )
99 )
100 }
100 }
101
101
102 def __contains__(&self, item: PyObject) -> PyResult<bool> {
102 def __contains__(&self, item: PyObject) -> PyResult<bool> {
103 Ok(self.inner(py).borrow().contains(HgPath::new(
103 Ok(self.inner_shared(py).borrow().contains(HgPath::new(
104 item.extract::<PyBytes>(py)?.data(py).as_ref(),
104 item.extract::<PyBytes>(py)?.data(py).as_ref(),
105 )))
105 )))
106 }
106 }
107 });
107 });
108
108
109 py_shared_ref!(Dirs, DirsMultiset, inner, inner_shared);
109 py_shared_ref!(Dirs, DirsMultiset, inner, inner_shared);
110
110
111 impl Dirs {
111 impl Dirs {
112 pub fn from_inner(py: Python, d: DirsMultiset) -> PyResult<Self> {
112 pub fn from_inner(py: Python, d: DirsMultiset) -> PyResult<Self> {
113 Self::create_instance(py, PySharedRefCell::new(d))
113 Self::create_instance(py, PySharedRefCell::new(d))
114 }
114 }
115
115
116 fn translate_key(
116 fn translate_key(
117 py: Python,
117 py: Python,
118 res: &HgPathBuf,
118 res: &HgPathBuf,
119 ) -> PyResult<Option<PyBytes>> {
119 ) -> PyResult<Option<PyBytes>> {
120 Ok(Some(PyBytes::new(py, res.as_ref())))
120 Ok(Some(PyBytes::new(py, res.as_ref())))
121 }
121 }
122 }
122 }
123
123
124 py_shared_iterator!(
124 py_shared_iterator!(
125 DirsMultisetKeysIterator,
125 DirsMultisetKeysIterator,
126 PyLeakedRef<DirsMultisetIter<'static>>,
126 PyLeakedRef<DirsMultisetIter<'static>>,
127 Dirs::translate_key,
127 Dirs::translate_key,
128 Option<PyBytes>
128 Option<PyBytes>
129 );
129 );
@@ -1,504 +1,504 b''
1 // dirstate_map.rs
1 // dirstate_map.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::dirstate_map` file provided by the
8 //! Bindings for the `hg::dirstate::dirstate_map` file provided by the
9 //! `hg-core` package.
9 //! `hg-core` package.
10
10
11 use std::cell::{Ref, RefCell};
11 use std::cell::{Ref, RefCell};
12 use std::convert::TryInto;
12 use std::convert::TryInto;
13 use std::time::Duration;
13 use std::time::Duration;
14
14
15 use cpython::{
15 use cpython::{
16 exc, ObjectProtocol, PyBool, PyBytes, PyClone, PyDict, PyErr, PyObject,
16 exc, ObjectProtocol, PyBool, PyBytes, PyClone, PyDict, PyErr, PyObject,
17 PyResult, PyTuple, Python, PythonObject, ToPyObject,
17 PyResult, PyTuple, Python, PythonObject, ToPyObject,
18 };
18 };
19
19
20 use crate::{
20 use crate::{
21 dirstate::copymap::{CopyMap, CopyMapItemsIterator, CopyMapKeysIterator},
21 dirstate::copymap::{CopyMap, CopyMapItemsIterator, CopyMapKeysIterator},
22 dirstate::{dirs_multiset::Dirs, make_dirstate_tuple},
22 dirstate::{dirs_multiset::Dirs, make_dirstate_tuple},
23 ref_sharing::{PyLeakedRef, PySharedRefCell},
23 ref_sharing::{PyLeakedRef, PySharedRefCell},
24 };
24 };
25 use hg::{
25 use hg::{
26 utils::hg_path::{HgPath, HgPathBuf},
26 utils::hg_path::{HgPath, HgPathBuf},
27 DirsMultiset, DirstateEntry, DirstateMap as RustDirstateMap,
27 DirsMultiset, DirstateEntry, DirstateMap as RustDirstateMap,
28 DirstateParents, DirstateParseError, EntryState, StateMapIter,
28 DirstateParents, DirstateParseError, EntryState, StateMapIter,
29 PARENT_SIZE,
29 PARENT_SIZE,
30 };
30 };
31
31
32 // TODO
32 // TODO
33 // This object needs to share references to multiple members of its Rust
33 // This object needs to share references to multiple members of its Rust
34 // inner struct, namely `copy_map`, `dirs` and `all_dirs`.
34 // inner struct, namely `copy_map`, `dirs` and `all_dirs`.
35 // Right now `CopyMap` is done, but it needs to have an explicit reference
35 // Right now `CopyMap` is done, but it needs to have an explicit reference
36 // to `RustDirstateMap` which itself needs to have an encapsulation for
36 // to `RustDirstateMap` which itself needs to have an encapsulation for
37 // every method in `CopyMap` (copymapcopy, etc.).
37 // every method in `CopyMap` (copymapcopy, etc.).
38 // This is ugly and hard to maintain.
38 // This is ugly and hard to maintain.
39 // The same logic applies to `dirs` and `all_dirs`, however the `Dirs`
39 // The same logic applies to `dirs` and `all_dirs`, however the `Dirs`
40 // `py_class!` is already implemented and does not mention
40 // `py_class!` is already implemented and does not mention
41 // `RustDirstateMap`, rightfully so.
41 // `RustDirstateMap`, rightfully so.
42 // All attributes also have to have a separate refcount data attribute for
42 // All attributes also have to have a separate refcount data attribute for
43 // leaks, with all methods that go along for reference sharing.
43 // leaks, with all methods that go along for reference sharing.
44 py_class!(pub class DirstateMap |py| {
44 py_class!(pub class DirstateMap |py| {
45 data inner: PySharedRefCell<RustDirstateMap>;
45 data inner: PySharedRefCell<RustDirstateMap>;
46
46
47 def __new__(_cls, _root: PyObject) -> PyResult<Self> {
47 def __new__(_cls, _root: PyObject) -> PyResult<Self> {
48 let inner = RustDirstateMap::default();
48 let inner = RustDirstateMap::default();
49 Self::create_instance(
49 Self::create_instance(
50 py,
50 py,
51 PySharedRefCell::new(inner),
51 PySharedRefCell::new(inner),
52 )
52 )
53 }
53 }
54
54
55 def clear(&self) -> PyResult<PyObject> {
55 def clear(&self) -> PyResult<PyObject> {
56 self.inner_shared(py).borrow_mut()?.clear();
56 self.inner_shared(py).borrow_mut()?.clear();
57 Ok(py.None())
57 Ok(py.None())
58 }
58 }
59
59
60 def get(
60 def get(
61 &self,
61 &self,
62 key: PyObject,
62 key: PyObject,
63 default: Option<PyObject> = None
63 default: Option<PyObject> = None
64 ) -> PyResult<Option<PyObject>> {
64 ) -> PyResult<Option<PyObject>> {
65 let key = key.extract::<PyBytes>(py)?;
65 let key = key.extract::<PyBytes>(py)?;
66 match self.inner(py).borrow().get(HgPath::new(key.data(py))) {
66 match self.inner_shared(py).borrow().get(HgPath::new(key.data(py))) {
67 Some(entry) => {
67 Some(entry) => {
68 Ok(Some(make_dirstate_tuple(py, entry)?))
68 Ok(Some(make_dirstate_tuple(py, entry)?))
69 },
69 },
70 None => Ok(default)
70 None => Ok(default)
71 }
71 }
72 }
72 }
73
73
74 def addfile(
74 def addfile(
75 &self,
75 &self,
76 f: PyObject,
76 f: PyObject,
77 oldstate: PyObject,
77 oldstate: PyObject,
78 state: PyObject,
78 state: PyObject,
79 mode: PyObject,
79 mode: PyObject,
80 size: PyObject,
80 size: PyObject,
81 mtime: PyObject
81 mtime: PyObject
82 ) -> PyResult<PyObject> {
82 ) -> PyResult<PyObject> {
83 self.inner_shared(py).borrow_mut()?.add_file(
83 self.inner_shared(py).borrow_mut()?.add_file(
84 HgPath::new(f.extract::<PyBytes>(py)?.data(py)),
84 HgPath::new(f.extract::<PyBytes>(py)?.data(py)),
85 oldstate.extract::<PyBytes>(py)?.data(py)[0]
85 oldstate.extract::<PyBytes>(py)?.data(py)[0]
86 .try_into()
86 .try_into()
87 .map_err(|e: DirstateParseError| {
87 .map_err(|e: DirstateParseError| {
88 PyErr::new::<exc::ValueError, _>(py, e.to_string())
88 PyErr::new::<exc::ValueError, _>(py, e.to_string())
89 })?,
89 })?,
90 DirstateEntry {
90 DirstateEntry {
91 state: state.extract::<PyBytes>(py)?.data(py)[0]
91 state: state.extract::<PyBytes>(py)?.data(py)[0]
92 .try_into()
92 .try_into()
93 .map_err(|e: DirstateParseError| {
93 .map_err(|e: DirstateParseError| {
94 PyErr::new::<exc::ValueError, _>(py, e.to_string())
94 PyErr::new::<exc::ValueError, _>(py, e.to_string())
95 })?,
95 })?,
96 mode: mode.extract(py)?,
96 mode: mode.extract(py)?,
97 size: size.extract(py)?,
97 size: size.extract(py)?,
98 mtime: mtime.extract(py)?,
98 mtime: mtime.extract(py)?,
99 },
99 },
100 );
100 );
101 Ok(py.None())
101 Ok(py.None())
102 }
102 }
103
103
104 def removefile(
104 def removefile(
105 &self,
105 &self,
106 f: PyObject,
106 f: PyObject,
107 oldstate: PyObject,
107 oldstate: PyObject,
108 size: PyObject
108 size: PyObject
109 ) -> PyResult<PyObject> {
109 ) -> PyResult<PyObject> {
110 self.inner_shared(py).borrow_mut()?
110 self.inner_shared(py).borrow_mut()?
111 .remove_file(
111 .remove_file(
112 HgPath::new(f.extract::<PyBytes>(py)?.data(py)),
112 HgPath::new(f.extract::<PyBytes>(py)?.data(py)),
113 oldstate.extract::<PyBytes>(py)?.data(py)[0]
113 oldstate.extract::<PyBytes>(py)?.data(py)[0]
114 .try_into()
114 .try_into()
115 .map_err(|e: DirstateParseError| {
115 .map_err(|e: DirstateParseError| {
116 PyErr::new::<exc::ValueError, _>(py, e.to_string())
116 PyErr::new::<exc::ValueError, _>(py, e.to_string())
117 })?,
117 })?,
118 size.extract(py)?,
118 size.extract(py)?,
119 )
119 )
120 .or_else(|_| {
120 .or_else(|_| {
121 Err(PyErr::new::<exc::OSError, _>(
121 Err(PyErr::new::<exc::OSError, _>(
122 py,
122 py,
123 "Dirstate error".to_string(),
123 "Dirstate error".to_string(),
124 ))
124 ))
125 })?;
125 })?;
126 Ok(py.None())
126 Ok(py.None())
127 }
127 }
128
128
129 def dropfile(
129 def dropfile(
130 &self,
130 &self,
131 f: PyObject,
131 f: PyObject,
132 oldstate: PyObject
132 oldstate: PyObject
133 ) -> PyResult<PyBool> {
133 ) -> PyResult<PyBool> {
134 self.inner_shared(py).borrow_mut()?
134 self.inner_shared(py).borrow_mut()?
135 .drop_file(
135 .drop_file(
136 HgPath::new(f.extract::<PyBytes>(py)?.data(py)),
136 HgPath::new(f.extract::<PyBytes>(py)?.data(py)),
137 oldstate.extract::<PyBytes>(py)?.data(py)[0]
137 oldstate.extract::<PyBytes>(py)?.data(py)[0]
138 .try_into()
138 .try_into()
139 .map_err(|e: DirstateParseError| {
139 .map_err(|e: DirstateParseError| {
140 PyErr::new::<exc::ValueError, _>(py, e.to_string())
140 PyErr::new::<exc::ValueError, _>(py, e.to_string())
141 })?,
141 })?,
142 )
142 )
143 .and_then(|b| Ok(b.to_py_object(py)))
143 .and_then(|b| Ok(b.to_py_object(py)))
144 .or_else(|_| {
144 .or_else(|_| {
145 Err(PyErr::new::<exc::OSError, _>(
145 Err(PyErr::new::<exc::OSError, _>(
146 py,
146 py,
147 "Dirstate error".to_string(),
147 "Dirstate error".to_string(),
148 ))
148 ))
149 })
149 })
150 }
150 }
151
151
152 def clearambiguoustimes(
152 def clearambiguoustimes(
153 &self,
153 &self,
154 files: PyObject,
154 files: PyObject,
155 now: PyObject
155 now: PyObject
156 ) -> PyResult<PyObject> {
156 ) -> PyResult<PyObject> {
157 let files: PyResult<Vec<HgPathBuf>> = files
157 let files: PyResult<Vec<HgPathBuf>> = files
158 .iter(py)?
158 .iter(py)?
159 .map(|filename| {
159 .map(|filename| {
160 Ok(HgPathBuf::from_bytes(
160 Ok(HgPathBuf::from_bytes(
161 filename?.extract::<PyBytes>(py)?.data(py),
161 filename?.extract::<PyBytes>(py)?.data(py),
162 ))
162 ))
163 })
163 })
164 .collect();
164 .collect();
165 self.inner_shared(py).borrow_mut()?
165 self.inner_shared(py).borrow_mut()?
166 .clear_ambiguous_times(files?, now.extract(py)?);
166 .clear_ambiguous_times(files?, now.extract(py)?);
167 Ok(py.None())
167 Ok(py.None())
168 }
168 }
169
169
170 // TODO share the reference
170 // TODO share the reference
171 def nonnormalentries(&self) -> PyResult<PyObject> {
171 def nonnormalentries(&self) -> PyResult<PyObject> {
172 let (non_normal, other_parent) =
172 let (non_normal, other_parent) =
173 self.inner(py).borrow().non_normal_other_parent_entries();
173 self.inner_shared(py).borrow().non_normal_other_parent_entries();
174
174
175 let locals = PyDict::new(py);
175 let locals = PyDict::new(py);
176 locals.set_item(
176 locals.set_item(
177 py,
177 py,
178 "non_normal",
178 "non_normal",
179 non_normal
179 non_normal
180 .iter()
180 .iter()
181 .map(|v| PyBytes::new(py, v.as_ref()))
181 .map(|v| PyBytes::new(py, v.as_ref()))
182 .collect::<Vec<PyBytes>>()
182 .collect::<Vec<PyBytes>>()
183 .to_py_object(py),
183 .to_py_object(py),
184 )?;
184 )?;
185 locals.set_item(
185 locals.set_item(
186 py,
186 py,
187 "other_parent",
187 "other_parent",
188 other_parent
188 other_parent
189 .iter()
189 .iter()
190 .map(|v| PyBytes::new(py, v.as_ref()))
190 .map(|v| PyBytes::new(py, v.as_ref()))
191 .collect::<Vec<PyBytes>>()
191 .collect::<Vec<PyBytes>>()
192 .to_py_object(py),
192 .to_py_object(py),
193 )?;
193 )?;
194
194
195 py.eval("set(non_normal), set(other_parent)", None, Some(&locals))
195 py.eval("set(non_normal), set(other_parent)", None, Some(&locals))
196 }
196 }
197
197
198 def hastrackeddir(&self, d: PyObject) -> PyResult<PyBool> {
198 def hastrackeddir(&self, d: PyObject) -> PyResult<PyBool> {
199 let d = d.extract::<PyBytes>(py)?;
199 let d = d.extract::<PyBytes>(py)?;
200 Ok(self.inner_shared(py).borrow_mut()?
200 Ok(self.inner_shared(py).borrow_mut()?
201 .has_tracked_dir(HgPath::new(d.data(py)))
201 .has_tracked_dir(HgPath::new(d.data(py)))
202 .to_py_object(py))
202 .to_py_object(py))
203 }
203 }
204
204
205 def hasdir(&self, d: PyObject) -> PyResult<PyBool> {
205 def hasdir(&self, d: PyObject) -> PyResult<PyBool> {
206 let d = d.extract::<PyBytes>(py)?;
206 let d = d.extract::<PyBytes>(py)?;
207 Ok(self.inner_shared(py).borrow_mut()?
207 Ok(self.inner_shared(py).borrow_mut()?
208 .has_dir(HgPath::new(d.data(py)))
208 .has_dir(HgPath::new(d.data(py)))
209 .to_py_object(py))
209 .to_py_object(py))
210 }
210 }
211
211
212 def parents(&self, st: PyObject) -> PyResult<PyTuple> {
212 def parents(&self, st: PyObject) -> PyResult<PyTuple> {
213 self.inner_shared(py).borrow_mut()?
213 self.inner_shared(py).borrow_mut()?
214 .parents(st.extract::<PyBytes>(py)?.data(py))
214 .parents(st.extract::<PyBytes>(py)?.data(py))
215 .and_then(|d| {
215 .and_then(|d| {
216 Ok((PyBytes::new(py, &d.p1), PyBytes::new(py, &d.p2))
216 Ok((PyBytes::new(py, &d.p1), PyBytes::new(py, &d.p2))
217 .to_py_object(py))
217 .to_py_object(py))
218 })
218 })
219 .or_else(|_| {
219 .or_else(|_| {
220 Err(PyErr::new::<exc::OSError, _>(
220 Err(PyErr::new::<exc::OSError, _>(
221 py,
221 py,
222 "Dirstate error".to_string(),
222 "Dirstate error".to_string(),
223 ))
223 ))
224 })
224 })
225 }
225 }
226
226
227 def setparents(&self, p1: PyObject, p2: PyObject) -> PyResult<PyObject> {
227 def setparents(&self, p1: PyObject, p2: PyObject) -> PyResult<PyObject> {
228 let p1 = extract_node_id(py, &p1)?;
228 let p1 = extract_node_id(py, &p1)?;
229 let p2 = extract_node_id(py, &p2)?;
229 let p2 = extract_node_id(py, &p2)?;
230
230
231 self.inner_shared(py).borrow_mut()?
231 self.inner_shared(py).borrow_mut()?
232 .set_parents(&DirstateParents { p1, p2 });
232 .set_parents(&DirstateParents { p1, p2 });
233 Ok(py.None())
233 Ok(py.None())
234 }
234 }
235
235
236 def read(&self, st: PyObject) -> PyResult<Option<PyObject>> {
236 def read(&self, st: PyObject) -> PyResult<Option<PyObject>> {
237 match self.inner_shared(py).borrow_mut()?
237 match self.inner_shared(py).borrow_mut()?
238 .read(st.extract::<PyBytes>(py)?.data(py))
238 .read(st.extract::<PyBytes>(py)?.data(py))
239 {
239 {
240 Ok(Some(parents)) => Ok(Some(
240 Ok(Some(parents)) => Ok(Some(
241 (PyBytes::new(py, &parents.p1), PyBytes::new(py, &parents.p2))
241 (PyBytes::new(py, &parents.p1), PyBytes::new(py, &parents.p2))
242 .to_py_object(py)
242 .to_py_object(py)
243 .into_object(),
243 .into_object(),
244 )),
244 )),
245 Ok(None) => Ok(Some(py.None())),
245 Ok(None) => Ok(Some(py.None())),
246 Err(_) => Err(PyErr::new::<exc::OSError, _>(
246 Err(_) => Err(PyErr::new::<exc::OSError, _>(
247 py,
247 py,
248 "Dirstate error".to_string(),
248 "Dirstate error".to_string(),
249 )),
249 )),
250 }
250 }
251 }
251 }
252 def write(
252 def write(
253 &self,
253 &self,
254 p1: PyObject,
254 p1: PyObject,
255 p2: PyObject,
255 p2: PyObject,
256 now: PyObject
256 now: PyObject
257 ) -> PyResult<PyBytes> {
257 ) -> PyResult<PyBytes> {
258 let now = Duration::new(now.extract(py)?, 0);
258 let now = Duration::new(now.extract(py)?, 0);
259 let parents = DirstateParents {
259 let parents = DirstateParents {
260 p1: extract_node_id(py, &p1)?,
260 p1: extract_node_id(py, &p1)?,
261 p2: extract_node_id(py, &p2)?,
261 p2: extract_node_id(py, &p2)?,
262 };
262 };
263
263
264 match self.inner_shared(py).borrow_mut()?.pack(parents, now) {
264 match self.inner_shared(py).borrow_mut()?.pack(parents, now) {
265 Ok(packed) => Ok(PyBytes::new(py, &packed)),
265 Ok(packed) => Ok(PyBytes::new(py, &packed)),
266 Err(_) => Err(PyErr::new::<exc::OSError, _>(
266 Err(_) => Err(PyErr::new::<exc::OSError, _>(
267 py,
267 py,
268 "Dirstate error".to_string(),
268 "Dirstate error".to_string(),
269 )),
269 )),
270 }
270 }
271 }
271 }
272
272
273 def filefoldmapasdict(&self) -> PyResult<PyDict> {
273 def filefoldmapasdict(&self) -> PyResult<PyDict> {
274 let dict = PyDict::new(py);
274 let dict = PyDict::new(py);
275 for (key, value) in
275 for (key, value) in
276 self.inner_shared(py).borrow_mut()?.build_file_fold_map().iter()
276 self.inner_shared(py).borrow_mut()?.build_file_fold_map().iter()
277 {
277 {
278 dict.set_item(py, key.as_ref().to_vec(), value.as_ref().to_vec())?;
278 dict.set_item(py, key.as_ref().to_vec(), value.as_ref().to_vec())?;
279 }
279 }
280 Ok(dict)
280 Ok(dict)
281 }
281 }
282
282
283 def __len__(&self) -> PyResult<usize> {
283 def __len__(&self) -> PyResult<usize> {
284 Ok(self.inner(py).borrow().len())
284 Ok(self.inner_shared(py).borrow().len())
285 }
285 }
286
286
287 def __contains__(&self, key: PyObject) -> PyResult<bool> {
287 def __contains__(&self, key: PyObject) -> PyResult<bool> {
288 let key = key.extract::<PyBytes>(py)?;
288 let key = key.extract::<PyBytes>(py)?;
289 Ok(self.inner(py).borrow().contains_key(HgPath::new(key.data(py))))
289 Ok(self.inner_shared(py).borrow().contains_key(HgPath::new(key.data(py))))
290 }
290 }
291
291
292 def __getitem__(&self, key: PyObject) -> PyResult<PyObject> {
292 def __getitem__(&self, key: PyObject) -> PyResult<PyObject> {
293 let key = key.extract::<PyBytes>(py)?;
293 let key = key.extract::<PyBytes>(py)?;
294 let key = HgPath::new(key.data(py));
294 let key = HgPath::new(key.data(py));
295 match self.inner(py).borrow().get(key) {
295 match self.inner_shared(py).borrow().get(key) {
296 Some(entry) => {
296 Some(entry) => {
297 Ok(make_dirstate_tuple(py, entry)?)
297 Ok(make_dirstate_tuple(py, entry)?)
298 },
298 },
299 None => Err(PyErr::new::<exc::KeyError, _>(
299 None => Err(PyErr::new::<exc::KeyError, _>(
300 py,
300 py,
301 String::from_utf8_lossy(key.as_bytes()),
301 String::from_utf8_lossy(key.as_bytes()),
302 )),
302 )),
303 }
303 }
304 }
304 }
305
305
306 def keys(&self) -> PyResult<DirstateMapKeysIterator> {
306 def keys(&self) -> PyResult<DirstateMapKeysIterator> {
307 let leaked_ref = self.inner_shared(py).leak_immutable()?;
307 let leaked_ref = self.inner_shared(py).leak_immutable()?;
308 DirstateMapKeysIterator::from_inner(
308 DirstateMapKeysIterator::from_inner(
309 py,
309 py,
310 unsafe { leaked_ref.map(py, |o| o.iter()) },
310 unsafe { leaked_ref.map(py, |o| o.iter()) },
311 )
311 )
312 }
312 }
313
313
314 def items(&self) -> PyResult<DirstateMapItemsIterator> {
314 def items(&self) -> PyResult<DirstateMapItemsIterator> {
315 let leaked_ref = self.inner_shared(py).leak_immutable()?;
315 let leaked_ref = self.inner_shared(py).leak_immutable()?;
316 DirstateMapItemsIterator::from_inner(
316 DirstateMapItemsIterator::from_inner(
317 py,
317 py,
318 unsafe { leaked_ref.map(py, |o| o.iter()) },
318 unsafe { leaked_ref.map(py, |o| o.iter()) },
319 )
319 )
320 }
320 }
321
321
322 def __iter__(&self) -> PyResult<DirstateMapKeysIterator> {
322 def __iter__(&self) -> PyResult<DirstateMapKeysIterator> {
323 let leaked_ref = self.inner_shared(py).leak_immutable()?;
323 let leaked_ref = self.inner_shared(py).leak_immutable()?;
324 DirstateMapKeysIterator::from_inner(
324 DirstateMapKeysIterator::from_inner(
325 py,
325 py,
326 unsafe { leaked_ref.map(py, |o| o.iter()) },
326 unsafe { leaked_ref.map(py, |o| o.iter()) },
327 )
327 )
328 }
328 }
329
329
330 def getdirs(&self) -> PyResult<Dirs> {
330 def getdirs(&self) -> PyResult<Dirs> {
331 // TODO don't copy, share the reference
331 // TODO don't copy, share the reference
332 self.inner_shared(py).borrow_mut()?.set_dirs();
332 self.inner_shared(py).borrow_mut()?.set_dirs();
333 Dirs::from_inner(
333 Dirs::from_inner(
334 py,
334 py,
335 DirsMultiset::from_dirstate(
335 DirsMultiset::from_dirstate(
336 &self.inner(py).borrow(),
336 &self.inner_shared(py).borrow(),
337 Some(EntryState::Removed),
337 Some(EntryState::Removed),
338 ),
338 ),
339 )
339 )
340 }
340 }
341 def getalldirs(&self) -> PyResult<Dirs> {
341 def getalldirs(&self) -> PyResult<Dirs> {
342 // TODO don't copy, share the reference
342 // TODO don't copy, share the reference
343 self.inner_shared(py).borrow_mut()?.set_all_dirs();
343 self.inner_shared(py).borrow_mut()?.set_all_dirs();
344 Dirs::from_inner(
344 Dirs::from_inner(
345 py,
345 py,
346 DirsMultiset::from_dirstate(
346 DirsMultiset::from_dirstate(
347 &self.inner(py).borrow(),
347 &self.inner_shared(py).borrow(),
348 None,
348 None,
349 ),
349 ),
350 )
350 )
351 }
351 }
352
352
353 // TODO all copymap* methods, see docstring above
353 // TODO all copymap* methods, see docstring above
354 def copymapcopy(&self) -> PyResult<PyDict> {
354 def copymapcopy(&self) -> PyResult<PyDict> {
355 let dict = PyDict::new(py);
355 let dict = PyDict::new(py);
356 for (key, value) in self.inner(py).borrow().copy_map.iter() {
356 for (key, value) in self.inner_shared(py).borrow().copy_map.iter() {
357 dict.set_item(
357 dict.set_item(
358 py,
358 py,
359 PyBytes::new(py, key.as_ref()),
359 PyBytes::new(py, key.as_ref()),
360 PyBytes::new(py, value.as_ref()),
360 PyBytes::new(py, value.as_ref()),
361 )?;
361 )?;
362 }
362 }
363 Ok(dict)
363 Ok(dict)
364 }
364 }
365
365
366 def copymapgetitem(&self, key: PyObject) -> PyResult<PyBytes> {
366 def copymapgetitem(&self, key: PyObject) -> PyResult<PyBytes> {
367 let key = key.extract::<PyBytes>(py)?;
367 let key = key.extract::<PyBytes>(py)?;
368 match self.inner(py).borrow().copy_map.get(HgPath::new(key.data(py))) {
368 match self.inner_shared(py).borrow().copy_map.get(HgPath::new(key.data(py))) {
369 Some(copy) => Ok(PyBytes::new(py, copy.as_ref())),
369 Some(copy) => Ok(PyBytes::new(py, copy.as_ref())),
370 None => Err(PyErr::new::<exc::KeyError, _>(
370 None => Err(PyErr::new::<exc::KeyError, _>(
371 py,
371 py,
372 String::from_utf8_lossy(key.data(py)),
372 String::from_utf8_lossy(key.data(py)),
373 )),
373 )),
374 }
374 }
375 }
375 }
376 def copymap(&self) -> PyResult<CopyMap> {
376 def copymap(&self) -> PyResult<CopyMap> {
377 CopyMap::from_inner(py, self.clone_ref(py))
377 CopyMap::from_inner(py, self.clone_ref(py))
378 }
378 }
379
379
380 def copymaplen(&self) -> PyResult<usize> {
380 def copymaplen(&self) -> PyResult<usize> {
381 Ok(self.inner(py).borrow().copy_map.len())
381 Ok(self.inner_shared(py).borrow().copy_map.len())
382 }
382 }
383 def copymapcontains(&self, key: PyObject) -> PyResult<bool> {
383 def copymapcontains(&self, key: PyObject) -> PyResult<bool> {
384 let key = key.extract::<PyBytes>(py)?;
384 let key = key.extract::<PyBytes>(py)?;
385 Ok(self
385 Ok(self
386 .inner(py)
386 .inner_shared(py)
387 .borrow()
387 .borrow()
388 .copy_map
388 .copy_map
389 .contains_key(HgPath::new(key.data(py))))
389 .contains_key(HgPath::new(key.data(py))))
390 }
390 }
391 def copymapget(
391 def copymapget(
392 &self,
392 &self,
393 key: PyObject,
393 key: PyObject,
394 default: Option<PyObject>
394 default: Option<PyObject>
395 ) -> PyResult<Option<PyObject>> {
395 ) -> PyResult<Option<PyObject>> {
396 let key = key.extract::<PyBytes>(py)?;
396 let key = key.extract::<PyBytes>(py)?;
397 match self
397 match self
398 .inner(py)
398 .inner_shared(py)
399 .borrow()
399 .borrow()
400 .copy_map
400 .copy_map
401 .get(HgPath::new(key.data(py)))
401 .get(HgPath::new(key.data(py)))
402 {
402 {
403 Some(copy) => Ok(Some(
403 Some(copy) => Ok(Some(
404 PyBytes::new(py, copy.as_ref()).into_object(),
404 PyBytes::new(py, copy.as_ref()).into_object(),
405 )),
405 )),
406 None => Ok(default),
406 None => Ok(default),
407 }
407 }
408 }
408 }
409 def copymapsetitem(
409 def copymapsetitem(
410 &self,
410 &self,
411 key: PyObject,
411 key: PyObject,
412 value: PyObject
412 value: PyObject
413 ) -> PyResult<PyObject> {
413 ) -> PyResult<PyObject> {
414 let key = key.extract::<PyBytes>(py)?;
414 let key = key.extract::<PyBytes>(py)?;
415 let value = value.extract::<PyBytes>(py)?;
415 let value = value.extract::<PyBytes>(py)?;
416 self.inner_shared(py).borrow_mut()?.copy_map.insert(
416 self.inner_shared(py).borrow_mut()?.copy_map.insert(
417 HgPathBuf::from_bytes(key.data(py)),
417 HgPathBuf::from_bytes(key.data(py)),
418 HgPathBuf::from_bytes(value.data(py)),
418 HgPathBuf::from_bytes(value.data(py)),
419 );
419 );
420 Ok(py.None())
420 Ok(py.None())
421 }
421 }
422 def copymappop(
422 def copymappop(
423 &self,
423 &self,
424 key: PyObject,
424 key: PyObject,
425 default: Option<PyObject>
425 default: Option<PyObject>
426 ) -> PyResult<Option<PyObject>> {
426 ) -> PyResult<Option<PyObject>> {
427 let key = key.extract::<PyBytes>(py)?;
427 let key = key.extract::<PyBytes>(py)?;
428 match self
428 match self
429 .inner_shared(py)
429 .inner_shared(py)
430 .borrow_mut()?
430 .borrow_mut()?
431 .copy_map
431 .copy_map
432 .remove(HgPath::new(key.data(py)))
432 .remove(HgPath::new(key.data(py)))
433 {
433 {
434 Some(_) => Ok(None),
434 Some(_) => Ok(None),
435 None => Ok(default),
435 None => Ok(default),
436 }
436 }
437 }
437 }
438
438
439 def copymapiter(&self) -> PyResult<CopyMapKeysIterator> {
439 def copymapiter(&self) -> PyResult<CopyMapKeysIterator> {
440 let leaked_ref = self.inner_shared(py).leak_immutable()?;
440 let leaked_ref = self.inner_shared(py).leak_immutable()?;
441 CopyMapKeysIterator::from_inner(
441 CopyMapKeysIterator::from_inner(
442 py,
442 py,
443 unsafe { leaked_ref.map(py, |o| o.copy_map.iter()) },
443 unsafe { leaked_ref.map(py, |o| o.copy_map.iter()) },
444 )
444 )
445 }
445 }
446
446
447 def copymapitemsiter(&self) -> PyResult<CopyMapItemsIterator> {
447 def copymapitemsiter(&self) -> PyResult<CopyMapItemsIterator> {
448 let leaked_ref = self.inner_shared(py).leak_immutable()?;
448 let leaked_ref = self.inner_shared(py).leak_immutable()?;
449 CopyMapItemsIterator::from_inner(
449 CopyMapItemsIterator::from_inner(
450 py,
450 py,
451 unsafe { leaked_ref.map(py, |o| o.copy_map.iter()) },
451 unsafe { leaked_ref.map(py, |o| o.copy_map.iter()) },
452 )
452 )
453 }
453 }
454
454
455 });
455 });
456
456
457 impl DirstateMap {
457 impl DirstateMap {
458 pub fn get_inner<'a>(
458 pub fn get_inner<'a>(
459 &'a self,
459 &'a self,
460 py: Python<'a>,
460 py: Python<'a>,
461 ) -> Ref<'a, RustDirstateMap> {
461 ) -> Ref<'a, RustDirstateMap> {
462 self.inner_shared(py).borrow()
462 self.inner_shared(py).borrow()
463 }
463 }
464 fn translate_key(
464 fn translate_key(
465 py: Python,
465 py: Python,
466 res: (&HgPathBuf, &DirstateEntry),
466 res: (&HgPathBuf, &DirstateEntry),
467 ) -> PyResult<Option<PyBytes>> {
467 ) -> PyResult<Option<PyBytes>> {
468 Ok(Some(PyBytes::new(py, res.0.as_ref())))
468 Ok(Some(PyBytes::new(py, res.0.as_ref())))
469 }
469 }
470 fn translate_key_value(
470 fn translate_key_value(
471 py: Python,
471 py: Python,
472 res: (&HgPathBuf, &DirstateEntry),
472 res: (&HgPathBuf, &DirstateEntry),
473 ) -> PyResult<Option<(PyBytes, PyObject)>> {
473 ) -> PyResult<Option<(PyBytes, PyObject)>> {
474 let (f, entry) = res;
474 let (f, entry) = res;
475 Ok(Some((
475 Ok(Some((
476 PyBytes::new(py, f.as_ref()),
476 PyBytes::new(py, f.as_ref()),
477 make_dirstate_tuple(py, entry)?,
477 make_dirstate_tuple(py, entry)?,
478 )))
478 )))
479 }
479 }
480 }
480 }
481
481
482 py_shared_ref!(DirstateMap, RustDirstateMap, inner, inner_shared);
482 py_shared_ref!(DirstateMap, RustDirstateMap, inner, inner_shared);
483
483
484 py_shared_iterator!(
484 py_shared_iterator!(
485 DirstateMapKeysIterator,
485 DirstateMapKeysIterator,
486 PyLeakedRef<StateMapIter<'static>>,
486 PyLeakedRef<StateMapIter<'static>>,
487 DirstateMap::translate_key,
487 DirstateMap::translate_key,
488 Option<PyBytes>
488 Option<PyBytes>
489 );
489 );
490
490
491 py_shared_iterator!(
491 py_shared_iterator!(
492 DirstateMapItemsIterator,
492 DirstateMapItemsIterator,
493 PyLeakedRef<StateMapIter<'static>>,
493 PyLeakedRef<StateMapIter<'static>>,
494 DirstateMap::translate_key_value,
494 DirstateMap::translate_key_value,
495 Option<(PyBytes, PyObject)>
495 Option<(PyBytes, PyObject)>
496 );
496 );
497
497
498 fn extract_node_id(py: Python, obj: &PyObject) -> PyResult<[u8; PARENT_SIZE]> {
498 fn extract_node_id(py: Python, obj: &PyObject) -> PyResult<[u8; PARENT_SIZE]> {
499 let bytes = obj.extract::<PyBytes>(py)?;
499 let bytes = obj.extract::<PyBytes>(py)?;
500 match bytes.data(py).try_into() {
500 match bytes.data(py).try_into() {
501 Ok(s) => Ok(s),
501 Ok(s) => Ok(s),
502 Err(e) => Err(PyErr::new::<exc::ValueError, _>(py, e.to_string())),
502 Err(e) => Err(PyErr::new::<exc::ValueError, _>(py, e.to_string())),
503 }
503 }
504 }
504 }
@@ -1,500 +1,500 b''
1 // ref_sharing.rs
1 // ref_sharing.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 // Permission is hereby granted, free of charge, to any person obtaining a copy
5 // Permission is hereby granted, free of charge, to any person obtaining a copy
6 // of this software and associated documentation files (the "Software"), to
6 // of this software and associated documentation files (the "Software"), to
7 // deal in the Software without restriction, including without limitation the
7 // deal in the Software without restriction, including without limitation the
8 // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
8 // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
9 // sell copies of the Software, and to permit persons to whom the Software is
9 // sell copies of the Software, and to permit persons to whom the Software is
10 // furnished to do so, subject to the following conditions:
10 // furnished to do so, subject to the following conditions:
11 //
11 //
12 // The above copyright notice and this permission notice shall be included in
12 // The above copyright notice and this permission notice shall be included in
13 // all copies or substantial portions of the Software.
13 // all copies or substantial portions of the Software.
14 //
14 //
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
20 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 // IN THE SOFTWARE.
21 // IN THE SOFTWARE.
22
22
23 //! Macros for use in the `hg-cpython` bridge library.
23 //! Macros for use in the `hg-cpython` bridge library.
24
24
25 use crate::exceptions::AlreadyBorrowed;
25 use crate::exceptions::AlreadyBorrowed;
26 use cpython::{PyClone, PyObject, PyResult, Python};
26 use cpython::{PyClone, PyObject, PyResult, Python};
27 use std::cell::{Cell, Ref, RefCell, RefMut};
27 use std::cell::{Cell, Ref, RefCell, RefMut};
28
28
29 /// Manages the shared state between Python and Rust
29 /// Manages the shared state between Python and Rust
30 #[derive(Debug, Default)]
30 #[derive(Debug, Default)]
31 pub struct PySharedState {
31 pub struct PySharedState {
32 leak_count: Cell<usize>,
32 leak_count: Cell<usize>,
33 mutably_borrowed: Cell<bool>,
33 mutably_borrowed: Cell<bool>,
34 }
34 }
35
35
36 // &PySharedState can be Send because any access to inner cells is
36 // &PySharedState can be Send because any access to inner cells is
37 // synchronized by the GIL.
37 // synchronized by the GIL.
38 unsafe impl Sync for PySharedState {}
38 unsafe impl Sync for PySharedState {}
39
39
40 impl PySharedState {
40 impl PySharedState {
41 pub fn borrow_mut<'a, T>(
41 pub fn borrow_mut<'a, T>(
42 &'a self,
42 &'a self,
43 py: Python<'a>,
43 py: Python<'a>,
44 pyrefmut: RefMut<'a, T>,
44 pyrefmut: RefMut<'a, T>,
45 ) -> PyResult<PyRefMut<'a, T>> {
45 ) -> PyResult<PyRefMut<'a, T>> {
46 if self.mutably_borrowed.get() {
46 if self.mutably_borrowed.get() {
47 return Err(AlreadyBorrowed::new(
47 return Err(AlreadyBorrowed::new(
48 py,
48 py,
49 "Cannot borrow mutably while there exists another \
49 "Cannot borrow mutably while there exists another \
50 mutable reference in a Python object",
50 mutable reference in a Python object",
51 ));
51 ));
52 }
52 }
53 match self.leak_count.get() {
53 match self.leak_count.get() {
54 0 => {
54 0 => {
55 self.mutably_borrowed.replace(true);
55 self.mutably_borrowed.replace(true);
56 Ok(PyRefMut::new(py, pyrefmut, self))
56 Ok(PyRefMut::new(py, pyrefmut, self))
57 }
57 }
58 // TODO
58 // TODO
59 // For now, this works differently than Python references
59 // For now, this works differently than Python references
60 // in the case of iterators.
60 // in the case of iterators.
61 // Python does not complain when the data an iterator
61 // Python does not complain when the data an iterator
62 // points to is modified if the iterator is never used
62 // points to is modified if the iterator is never used
63 // afterwards.
63 // afterwards.
64 // Here, we are stricter than this by refusing to give a
64 // Here, we are stricter than this by refusing to give a
65 // mutable reference if it is already borrowed.
65 // mutable reference if it is already borrowed.
66 // While the additional safety might be argued for, it
66 // While the additional safety might be argued for, it
67 // breaks valid programming patterns in Python and we need
67 // breaks valid programming patterns in Python and we need
68 // to fix this issue down the line.
68 // to fix this issue down the line.
69 _ => Err(AlreadyBorrowed::new(
69 _ => Err(AlreadyBorrowed::new(
70 py,
70 py,
71 "Cannot borrow mutably while there are \
71 "Cannot borrow mutably while there are \
72 immutable references in Python objects",
72 immutable references in Python objects",
73 )),
73 )),
74 }
74 }
75 }
75 }
76
76
77 /// Return a reference to the wrapped data and its state with an
77 /// Return a reference to the wrapped data and its state with an
78 /// artificial static lifetime.
78 /// artificial static lifetime.
79 /// We need to be protected by the GIL for thread-safety.
79 /// We need to be protected by the GIL for thread-safety.
80 ///
80 ///
81 /// # Safety
81 /// # Safety
82 ///
82 ///
83 /// This is highly unsafe since the lifetime of the given data can be
83 /// This is highly unsafe since the lifetime of the given data can be
84 /// extended. Do not call this function directly.
84 /// extended. Do not call this function directly.
85 pub unsafe fn leak_immutable<T>(
85 pub unsafe fn leak_immutable<T>(
86 &self,
86 &self,
87 py: Python,
87 py: Python,
88 data: &PySharedRefCell<T>,
88 data: &PySharedRefCell<T>,
89 ) -> PyResult<(&'static T, &'static PySharedState)> {
89 ) -> PyResult<(&'static T, &'static PySharedState)> {
90 if self.mutably_borrowed.get() {
90 if self.mutably_borrowed.get() {
91 return Err(AlreadyBorrowed::new(
91 return Err(AlreadyBorrowed::new(
92 py,
92 py,
93 "Cannot borrow immutably while there is a \
93 "Cannot borrow immutably while there is a \
94 mutable reference in Python objects",
94 mutable reference in Python objects",
95 ));
95 ));
96 }
96 }
97 // TODO: it's weird that self is data.py_shared_state. Maybe we
97 // TODO: it's weird that self is data.py_shared_state. Maybe we
98 // can move stuff to PySharedRefCell?
98 // can move stuff to PySharedRefCell?
99 let ptr = data.as_ptr();
99 let ptr = data.as_ptr();
100 let state_ptr: *const PySharedState = &data.py_shared_state;
100 let state_ptr: *const PySharedState = &data.py_shared_state;
101 self.leak_count.replace(self.leak_count.get() + 1);
101 self.leak_count.replace(self.leak_count.get() + 1);
102 Ok((&*ptr, &*state_ptr))
102 Ok((&*ptr, &*state_ptr))
103 }
103 }
104
104
105 /// # Safety
105 /// # Safety
106 ///
106 ///
107 /// It's unsafe to update the reference count without knowing the
107 /// It's unsafe to update the reference count without knowing the
108 /// reference is deleted. Do not call this function directly.
108 /// reference is deleted. Do not call this function directly.
109 pub unsafe fn decrease_leak_count(&self, _py: Python, mutable: bool) {
109 pub unsafe fn decrease_leak_count(&self, _py: Python, mutable: bool) {
110 if mutable {
110 if mutable {
111 assert_eq!(self.leak_count.get(), 0);
111 assert_eq!(self.leak_count.get(), 0);
112 assert!(self.mutably_borrowed.get());
112 assert!(self.mutably_borrowed.get());
113 self.mutably_borrowed.replace(false);
113 self.mutably_borrowed.replace(false);
114 } else {
114 } else {
115 let count = self.leak_count.get();
115 let count = self.leak_count.get();
116 assert!(count > 0);
116 assert!(count > 0);
117 self.leak_count.replace(count - 1);
117 self.leak_count.replace(count - 1);
118 }
118 }
119 }
119 }
120 }
120 }
121
121
122 /// `RefCell` wrapper to be safely used in conjunction with `PySharedState`.
122 /// `RefCell` wrapper to be safely used in conjunction with `PySharedState`.
123 ///
123 ///
124 /// Only immutable operation is allowed through this interface.
124 /// Only immutable operation is allowed through this interface.
125 #[derive(Debug)]
125 #[derive(Debug)]
126 pub struct PySharedRefCell<T> {
126 pub struct PySharedRefCell<T> {
127 inner: RefCell<T>,
127 inner: RefCell<T>,
128 py_shared_state: PySharedState,
128 py_shared_state: PySharedState,
129 }
129 }
130
130
131 impl<T> PySharedRefCell<T> {
131 impl<T> PySharedRefCell<T> {
132 pub fn new(value: T) -> PySharedRefCell<T> {
132 pub fn new(value: T) -> PySharedRefCell<T> {
133 Self {
133 Self {
134 inner: RefCell::new(value),
134 inner: RefCell::new(value),
135 py_shared_state: PySharedState::default(),
135 py_shared_state: PySharedState::default(),
136 }
136 }
137 }
137 }
138
138
139 pub fn borrow(&self) -> Ref<T> {
139 pub fn borrow<'a>(&'a self, _py: Python<'a>) -> Ref<'a, T> {
140 // py_shared_state isn't involved since
140 // py_shared_state isn't involved since
141 // - inner.borrow() would fail if self is mutably borrowed,
141 // - inner.borrow() would fail if self is mutably borrowed,
142 // - and inner.borrow_mut() would fail while self is borrowed.
142 // - and inner.borrow_mut() would fail while self is borrowed.
143 self.inner.borrow()
143 self.inner.borrow()
144 }
144 }
145
145
146 pub fn as_ptr(&self) -> *mut T {
146 pub fn as_ptr(&self) -> *mut T {
147 self.inner.as_ptr()
147 self.inner.as_ptr()
148 }
148 }
149
149
150 // TODO: maybe this should be named as try_borrow_mut(), and use
150 // TODO: maybe this should be named as try_borrow_mut(), and use
151 // inner.try_borrow_mut(). The current implementation panics if
151 // inner.try_borrow_mut(). The current implementation panics if
152 // self.inner has been borrowed, but returns error if py_shared_state
152 // self.inner has been borrowed, but returns error if py_shared_state
153 // refuses to borrow.
153 // refuses to borrow.
154 pub fn borrow_mut<'a>(
154 pub fn borrow_mut<'a>(
155 &'a self,
155 &'a self,
156 py: Python<'a>,
156 py: Python<'a>,
157 ) -> PyResult<PyRefMut<'a, T>> {
157 ) -> PyResult<PyRefMut<'a, T>> {
158 self.py_shared_state.borrow_mut(py, self.inner.borrow_mut())
158 self.py_shared_state.borrow_mut(py, self.inner.borrow_mut())
159 }
159 }
160 }
160 }
161
161
162 /// Sharable data member of type `T` borrowed from the `PyObject`.
162 /// Sharable data member of type `T` borrowed from the `PyObject`.
163 pub struct PySharedRef<'a, T> {
163 pub struct PySharedRef<'a, T> {
164 py: Python<'a>,
164 py: Python<'a>,
165 owner: &'a PyObject,
165 owner: &'a PyObject,
166 data: &'a PySharedRefCell<T>,
166 data: &'a PySharedRefCell<T>,
167 }
167 }
168
168
169 impl<'a, T> PySharedRef<'a, T> {
169 impl<'a, T> PySharedRef<'a, T> {
170 /// # Safety
170 /// # Safety
171 ///
171 ///
172 /// The `data` must be owned by the `owner`. Otherwise, the leak count
172 /// The `data` must be owned by the `owner`. Otherwise, the leak count
173 /// would get wrong.
173 /// would get wrong.
174 pub unsafe fn new(
174 pub unsafe fn new(
175 py: Python<'a>,
175 py: Python<'a>,
176 owner: &'a PyObject,
176 owner: &'a PyObject,
177 data: &'a PySharedRefCell<T>,
177 data: &'a PySharedRefCell<T>,
178 ) -> Self {
178 ) -> Self {
179 Self { py, owner, data }
179 Self { py, owner, data }
180 }
180 }
181
181
182 pub fn borrow(&self) -> Ref<'a, T> {
182 pub fn borrow(&self) -> Ref<'a, T> {
183 self.data.borrow()
183 self.data.borrow(self.py)
184 }
184 }
185
185
186 pub fn borrow_mut(&self) -> PyResult<PyRefMut<'a, T>> {
186 pub fn borrow_mut(&self) -> PyResult<PyRefMut<'a, T>> {
187 self.data.borrow_mut(self.py)
187 self.data.borrow_mut(self.py)
188 }
188 }
189
189
190 /// Returns a leaked reference.
190 /// Returns a leaked reference.
191 pub fn leak_immutable(&self) -> PyResult<PyLeakedRef<&'static T>> {
191 pub fn leak_immutable(&self) -> PyResult<PyLeakedRef<&'static T>> {
192 let state = &self.data.py_shared_state;
192 let state = &self.data.py_shared_state;
193 unsafe {
193 unsafe {
194 let (static_ref, static_state_ref) =
194 let (static_ref, static_state_ref) =
195 state.leak_immutable(self.py, self.data)?;
195 state.leak_immutable(self.py, self.data)?;
196 Ok(PyLeakedRef::new(
196 Ok(PyLeakedRef::new(
197 self.py,
197 self.py,
198 self.owner,
198 self.owner,
199 static_ref,
199 static_ref,
200 static_state_ref,
200 static_state_ref,
201 ))
201 ))
202 }
202 }
203 }
203 }
204 }
204 }
205
205
206 /// Holds a mutable reference to data shared between Python and Rust.
206 /// Holds a mutable reference to data shared between Python and Rust.
207 pub struct PyRefMut<'a, T> {
207 pub struct PyRefMut<'a, T> {
208 inner: RefMut<'a, T>,
208 inner: RefMut<'a, T>,
209 py_shared_state: &'a PySharedState,
209 py_shared_state: &'a PySharedState,
210 }
210 }
211
211
212 impl<'a, T> PyRefMut<'a, T> {
212 impl<'a, T> PyRefMut<'a, T> {
213 // Must be constructed by PySharedState after checking its leak_count.
213 // Must be constructed by PySharedState after checking its leak_count.
214 // Otherwise, drop() would incorrectly update the state.
214 // Otherwise, drop() would incorrectly update the state.
215 fn new(
215 fn new(
216 _py: Python<'a>,
216 _py: Python<'a>,
217 inner: RefMut<'a, T>,
217 inner: RefMut<'a, T>,
218 py_shared_state: &'a PySharedState,
218 py_shared_state: &'a PySharedState,
219 ) -> Self {
219 ) -> Self {
220 Self {
220 Self {
221 inner,
221 inner,
222 py_shared_state,
222 py_shared_state,
223 }
223 }
224 }
224 }
225 }
225 }
226
226
227 impl<'a, T> std::ops::Deref for PyRefMut<'a, T> {
227 impl<'a, T> std::ops::Deref for PyRefMut<'a, T> {
228 type Target = RefMut<'a, T>;
228 type Target = RefMut<'a, T>;
229
229
230 fn deref(&self) -> &Self::Target {
230 fn deref(&self) -> &Self::Target {
231 &self.inner
231 &self.inner
232 }
232 }
233 }
233 }
234 impl<'a, T> std::ops::DerefMut for PyRefMut<'a, T> {
234 impl<'a, T> std::ops::DerefMut for PyRefMut<'a, T> {
235 fn deref_mut(&mut self) -> &mut Self::Target {
235 fn deref_mut(&mut self) -> &mut Self::Target {
236 &mut self.inner
236 &mut self.inner
237 }
237 }
238 }
238 }
239
239
240 impl<'a, T> Drop for PyRefMut<'a, T> {
240 impl<'a, T> Drop for PyRefMut<'a, T> {
241 fn drop(&mut self) {
241 fn drop(&mut self) {
242 let gil = Python::acquire_gil();
242 let gil = Python::acquire_gil();
243 let py = gil.python();
243 let py = gil.python();
244 unsafe {
244 unsafe {
245 self.py_shared_state.decrease_leak_count(py, true);
245 self.py_shared_state.decrease_leak_count(py, true);
246 }
246 }
247 }
247 }
248 }
248 }
249
249
250 /// Allows a `py_class!` generated struct to share references to one of its
250 /// Allows a `py_class!` generated struct to share references to one of its
251 /// data members with Python.
251 /// data members with Python.
252 ///
252 ///
253 /// # Warning
253 /// # Warning
254 ///
254 ///
255 /// TODO allow Python container types: for now, integration with the garbage
255 /// TODO allow Python container types: for now, integration with the garbage
256 /// collector does not extend to Rust structs holding references to Python
256 /// collector does not extend to Rust structs holding references to Python
257 /// objects. Should the need surface, `__traverse__` and `__clear__` will
257 /// objects. Should the need surface, `__traverse__` and `__clear__` will
258 /// need to be written as per the `rust-cpython` docs on GC integration.
258 /// need to be written as per the `rust-cpython` docs on GC integration.
259 ///
259 ///
260 /// # Parameters
260 /// # Parameters
261 ///
261 ///
262 /// * `$name` is the same identifier used in for `py_class!` macro call.
262 /// * `$name` is the same identifier used in for `py_class!` macro call.
263 /// * `$inner_struct` is the identifier of the underlying Rust struct
263 /// * `$inner_struct` is the identifier of the underlying Rust struct
264 /// * `$data_member` is the identifier of the data member of `$inner_struct`
264 /// * `$data_member` is the identifier of the data member of `$inner_struct`
265 /// that will be shared.
265 /// that will be shared.
266 /// * `$shared_accessor` is the function name to be generated, which allows
266 /// * `$shared_accessor` is the function name to be generated, which allows
267 /// safe access to the data member.
267 /// safe access to the data member.
268 ///
268 ///
269 /// # Safety
269 /// # Safety
270 ///
270 ///
271 /// `$data_member` must persist while the `$name` object is alive. In other
271 /// `$data_member` must persist while the `$name` object is alive. In other
272 /// words, it must be an accessor to a data field of the Python object.
272 /// words, it must be an accessor to a data field of the Python object.
273 ///
273 ///
274 /// # Example
274 /// # Example
275 ///
275 ///
276 /// ```
276 /// ```
277 /// struct MyStruct {
277 /// struct MyStruct {
278 /// inner: Vec<u32>;
278 /// inner: Vec<u32>;
279 /// }
279 /// }
280 ///
280 ///
281 /// py_class!(pub class MyType |py| {
281 /// py_class!(pub class MyType |py| {
282 /// data inner: PySharedRefCell<MyStruct>;
282 /// data inner: PySharedRefCell<MyStruct>;
283 /// });
283 /// });
284 ///
284 ///
285 /// py_shared_ref!(MyType, MyStruct, inner, inner_shared);
285 /// py_shared_ref!(MyType, MyStruct, inner, inner_shared);
286 /// ```
286 /// ```
287 macro_rules! py_shared_ref {
287 macro_rules! py_shared_ref {
288 (
288 (
289 $name: ident,
289 $name: ident,
290 $inner_struct: ident,
290 $inner_struct: ident,
291 $data_member: ident,
291 $data_member: ident,
292 $shared_accessor: ident
292 $shared_accessor: ident
293 ) => {
293 ) => {
294 impl $name {
294 impl $name {
295 /// Returns a safe reference to the shared `$data_member`.
295 /// Returns a safe reference to the shared `$data_member`.
296 ///
296 ///
297 /// This function guarantees that `PySharedRef` is created with
297 /// This function guarantees that `PySharedRef` is created with
298 /// the valid `self` and `self.$data_member(py)` pair.
298 /// the valid `self` and `self.$data_member(py)` pair.
299 fn $shared_accessor<'a>(
299 fn $shared_accessor<'a>(
300 &'a self,
300 &'a self,
301 py: Python<'a>,
301 py: Python<'a>,
302 ) -> $crate::ref_sharing::PySharedRef<'a, $inner_struct> {
302 ) -> $crate::ref_sharing::PySharedRef<'a, $inner_struct> {
303 use cpython::PythonObject;
303 use cpython::PythonObject;
304 use $crate::ref_sharing::PySharedRef;
304 use $crate::ref_sharing::PySharedRef;
305 let owner = self.as_object();
305 let owner = self.as_object();
306 let data = self.$data_member(py);
306 let data = self.$data_member(py);
307 unsafe { PySharedRef::new(py, owner, data) }
307 unsafe { PySharedRef::new(py, owner, data) }
308 }
308 }
309 }
309 }
310 };
310 };
311 }
311 }
312
312
313 /// Manage immutable references to `PyObject` leaked into Python iterators.
313 /// Manage immutable references to `PyObject` leaked into Python iterators.
314 pub struct PyLeakedRef<T> {
314 pub struct PyLeakedRef<T> {
315 inner: PyObject,
315 inner: PyObject,
316 data: Option<T>,
316 data: Option<T>,
317 py_shared_state: &'static PySharedState,
317 py_shared_state: &'static PySharedState,
318 }
318 }
319
319
320 // DO NOT implement Deref for PyLeakedRef<T>! Dereferencing PyLeakedRef
320 // DO NOT implement Deref for PyLeakedRef<T>! Dereferencing PyLeakedRef
321 // without taking Python GIL wouldn't be safe.
321 // without taking Python GIL wouldn't be safe.
322
322
323 impl<T> PyLeakedRef<T> {
323 impl<T> PyLeakedRef<T> {
324 /// # Safety
324 /// # Safety
325 ///
325 ///
326 /// The `py_shared_state` must be owned by the `inner` Python object.
326 /// The `py_shared_state` must be owned by the `inner` Python object.
327 // Marked as unsafe so client code wouldn't construct PyLeakedRef
327 // Marked as unsafe so client code wouldn't construct PyLeakedRef
328 // struct by mistake. Its drop() is unsafe.
328 // struct by mistake. Its drop() is unsafe.
329 pub unsafe fn new(
329 pub unsafe fn new(
330 py: Python,
330 py: Python,
331 inner: &PyObject,
331 inner: &PyObject,
332 data: T,
332 data: T,
333 py_shared_state: &'static PySharedState,
333 py_shared_state: &'static PySharedState,
334 ) -> Self {
334 ) -> Self {
335 Self {
335 Self {
336 inner: inner.clone_ref(py),
336 inner: inner.clone_ref(py),
337 data: Some(data),
337 data: Some(data),
338 py_shared_state,
338 py_shared_state,
339 }
339 }
340 }
340 }
341
341
342 /// Returns an immutable reference to the inner value.
342 /// Returns an immutable reference to the inner value.
343 pub fn get_ref<'a>(&'a self, _py: Python<'a>) -> &'a T {
343 pub fn get_ref<'a>(&'a self, _py: Python<'a>) -> &'a T {
344 self.data.as_ref().unwrap()
344 self.data.as_ref().unwrap()
345 }
345 }
346
346
347 /// Returns a mutable reference to the inner value.
347 /// Returns a mutable reference to the inner value.
348 ///
348 ///
349 /// Typically `T` is an iterator. If `T` is an immutable reference,
349 /// Typically `T` is an iterator. If `T` is an immutable reference,
350 /// `get_mut()` is useless since the inner value can't be mutated.
350 /// `get_mut()` is useless since the inner value can't be mutated.
351 pub fn get_mut<'a>(&'a mut self, _py: Python<'a>) -> &'a mut T {
351 pub fn get_mut<'a>(&'a mut self, _py: Python<'a>) -> &'a mut T {
352 self.data.as_mut().unwrap()
352 self.data.as_mut().unwrap()
353 }
353 }
354
354
355 /// Converts the inner value by the given function.
355 /// Converts the inner value by the given function.
356 ///
356 ///
357 /// Typically `T` is a static reference to a container, and `U` is an
357 /// Typically `T` is a static reference to a container, and `U` is an
358 /// iterator of that container.
358 /// iterator of that container.
359 ///
359 ///
360 /// # Safety
360 /// # Safety
361 ///
361 ///
362 /// The lifetime of the object passed in to the function `f` is cheated.
362 /// The lifetime of the object passed in to the function `f` is cheated.
363 /// It's typically a static reference, but is valid only while the
363 /// It's typically a static reference, but is valid only while the
364 /// corresponding `PyLeakedRef` is alive. Do not copy it out of the
364 /// corresponding `PyLeakedRef` is alive. Do not copy it out of the
365 /// function call.
365 /// function call.
366 pub unsafe fn map<U>(
366 pub unsafe fn map<U>(
367 mut self,
367 mut self,
368 py: Python,
368 py: Python,
369 f: impl FnOnce(T) -> U,
369 f: impl FnOnce(T) -> U,
370 ) -> PyLeakedRef<U> {
370 ) -> PyLeakedRef<U> {
371 // f() could make the self.data outlive. That's why map() is unsafe.
371 // f() could make the self.data outlive. That's why map() is unsafe.
372 // In order to make this function safe, maybe we'll need a way to
372 // In order to make this function safe, maybe we'll need a way to
373 // temporarily restrict the lifetime of self.data and translate the
373 // temporarily restrict the lifetime of self.data and translate the
374 // returned object back to Something<'static>.
374 // returned object back to Something<'static>.
375 let new_data = f(self.data.take().unwrap());
375 let new_data = f(self.data.take().unwrap());
376 PyLeakedRef {
376 PyLeakedRef {
377 inner: self.inner.clone_ref(py),
377 inner: self.inner.clone_ref(py),
378 data: Some(new_data),
378 data: Some(new_data),
379 py_shared_state: self.py_shared_state,
379 py_shared_state: self.py_shared_state,
380 }
380 }
381 }
381 }
382 }
382 }
383
383
384 impl<T> Drop for PyLeakedRef<T> {
384 impl<T> Drop for PyLeakedRef<T> {
385 fn drop(&mut self) {
385 fn drop(&mut self) {
386 // py_shared_state should be alive since we do have
386 // py_shared_state should be alive since we do have
387 // a Python reference to the owner object. Taking GIL makes
387 // a Python reference to the owner object. Taking GIL makes
388 // sure that the state is only accessed by this thread.
388 // sure that the state is only accessed by this thread.
389 let gil = Python::acquire_gil();
389 let gil = Python::acquire_gil();
390 let py = gil.python();
390 let py = gil.python();
391 if self.data.is_none() {
391 if self.data.is_none() {
392 return; // moved to another PyLeakedRef
392 return; // moved to another PyLeakedRef
393 }
393 }
394 unsafe {
394 unsafe {
395 self.py_shared_state.decrease_leak_count(py, false);
395 self.py_shared_state.decrease_leak_count(py, false);
396 }
396 }
397 }
397 }
398 }
398 }
399
399
400 /// Defines a `py_class!` that acts as a Python iterator over a Rust iterator.
400 /// Defines a `py_class!` that acts as a Python iterator over a Rust iterator.
401 ///
401 ///
402 /// TODO: this is a bit awkward to use, and a better (more complicated)
402 /// TODO: this is a bit awkward to use, and a better (more complicated)
403 /// procedural macro would simplify the interface a lot.
403 /// procedural macro would simplify the interface a lot.
404 ///
404 ///
405 /// # Parameters
405 /// # Parameters
406 ///
406 ///
407 /// * `$name` is the identifier to give to the resulting Rust struct.
407 /// * `$name` is the identifier to give to the resulting Rust struct.
408 /// * `$leaked` corresponds to `$leaked` in the matching `py_shared_ref!` call.
408 /// * `$leaked` corresponds to `$leaked` in the matching `py_shared_ref!` call.
409 /// * `$iterator_type` is the type of the Rust iterator.
409 /// * `$iterator_type` is the type of the Rust iterator.
410 /// * `$success_func` is a function for processing the Rust `(key, value)`
410 /// * `$success_func` is a function for processing the Rust `(key, value)`
411 /// tuple on iteration success, turning it into something Python understands.
411 /// tuple on iteration success, turning it into something Python understands.
412 /// * `$success_func` is the return type of `$success_func`
412 /// * `$success_func` is the return type of `$success_func`
413 ///
413 ///
414 /// # Example
414 /// # Example
415 ///
415 ///
416 /// ```
416 /// ```
417 /// struct MyStruct {
417 /// struct MyStruct {
418 /// inner: HashMap<Vec<u8>, Vec<u8>>;
418 /// inner: HashMap<Vec<u8>, Vec<u8>>;
419 /// }
419 /// }
420 ///
420 ///
421 /// py_class!(pub class MyType |py| {
421 /// py_class!(pub class MyType |py| {
422 /// data inner: PySharedRefCell<MyStruct>;
422 /// data inner: PySharedRefCell<MyStruct>;
423 ///
423 ///
424 /// def __iter__(&self) -> PyResult<MyTypeItemsIterator> {
424 /// def __iter__(&self) -> PyResult<MyTypeItemsIterator> {
425 /// let leaked_ref = self.inner_shared(py).leak_immutable()?;
425 /// let leaked_ref = self.inner_shared(py).leak_immutable()?;
426 /// MyTypeItemsIterator::from_inner(
426 /// MyTypeItemsIterator::from_inner(
427 /// py,
427 /// py,
428 /// unsafe { leaked_ref.map(py, |o| o.iter()) },
428 /// unsafe { leaked_ref.map(py, |o| o.iter()) },
429 /// )
429 /// )
430 /// }
430 /// }
431 /// });
431 /// });
432 ///
432 ///
433 /// impl MyType {
433 /// impl MyType {
434 /// fn translate_key_value(
434 /// fn translate_key_value(
435 /// py: Python,
435 /// py: Python,
436 /// res: (&Vec<u8>, &Vec<u8>),
436 /// res: (&Vec<u8>, &Vec<u8>),
437 /// ) -> PyResult<Option<(PyBytes, PyBytes)>> {
437 /// ) -> PyResult<Option<(PyBytes, PyBytes)>> {
438 /// let (f, entry) = res;
438 /// let (f, entry) = res;
439 /// Ok(Some((
439 /// Ok(Some((
440 /// PyBytes::new(py, f),
440 /// PyBytes::new(py, f),
441 /// PyBytes::new(py, entry),
441 /// PyBytes::new(py, entry),
442 /// )))
442 /// )))
443 /// }
443 /// }
444 /// }
444 /// }
445 ///
445 ///
446 /// py_shared_ref!(MyType, MyStruct, inner, MyTypeLeakedRef);
446 /// py_shared_ref!(MyType, MyStruct, inner, MyTypeLeakedRef);
447 ///
447 ///
448 /// py_shared_iterator!(
448 /// py_shared_iterator!(
449 /// MyTypeItemsIterator,
449 /// MyTypeItemsIterator,
450 /// PyLeakedRef<HashMap<'static, Vec<u8>, Vec<u8>>>,
450 /// PyLeakedRef<HashMap<'static, Vec<u8>, Vec<u8>>>,
451 /// MyType::translate_key_value,
451 /// MyType::translate_key_value,
452 /// Option<(PyBytes, PyBytes)>
452 /// Option<(PyBytes, PyBytes)>
453 /// );
453 /// );
454 /// ```
454 /// ```
455 macro_rules! py_shared_iterator {
455 macro_rules! py_shared_iterator {
456 (
456 (
457 $name: ident,
457 $name: ident,
458 $leaked: ty,
458 $leaked: ty,
459 $success_func: expr,
459 $success_func: expr,
460 $success_type: ty
460 $success_type: ty
461 ) => {
461 ) => {
462 py_class!(pub class $name |py| {
462 py_class!(pub class $name |py| {
463 data inner: RefCell<Option<$leaked>>;
463 data inner: RefCell<Option<$leaked>>;
464
464
465 def __next__(&self) -> PyResult<$success_type> {
465 def __next__(&self) -> PyResult<$success_type> {
466 let mut inner_opt = self.inner(py).borrow_mut();
466 let mut inner_opt = self.inner(py).borrow_mut();
467 if let Some(leaked) = inner_opt.as_mut() {
467 if let Some(leaked) = inner_opt.as_mut() {
468 match leaked.get_mut(py).next() {
468 match leaked.get_mut(py).next() {
469 None => {
469 None => {
470 // replace Some(inner) by None, drop $leaked
470 // replace Some(inner) by None, drop $leaked
471 inner_opt.take();
471 inner_opt.take();
472 Ok(None)
472 Ok(None)
473 }
473 }
474 Some(res) => {
474 Some(res) => {
475 $success_func(py, res)
475 $success_func(py, res)
476 }
476 }
477 }
477 }
478 } else {
478 } else {
479 Ok(None)
479 Ok(None)
480 }
480 }
481 }
481 }
482
482
483 def __iter__(&self) -> PyResult<Self> {
483 def __iter__(&self) -> PyResult<Self> {
484 Ok(self.clone_ref(py))
484 Ok(self.clone_ref(py))
485 }
485 }
486 });
486 });
487
487
488 impl $name {
488 impl $name {
489 pub fn from_inner(
489 pub fn from_inner(
490 py: Python,
490 py: Python,
491 leaked: $leaked,
491 leaked: $leaked,
492 ) -> PyResult<Self> {
492 ) -> PyResult<Self> {
493 Self::create_instance(
493 Self::create_instance(
494 py,
494 py,
495 RefCell::new(Some(leaked)),
495 RefCell::new(Some(leaked)),
496 )
496 )
497 }
497 }
498 }
498 }
499 };
499 };
500 }
500 }
General Comments 0
You need to be logged in to leave comments. Login now