comparison rust/hg-cpython/src/ref_sharing.rs @ 43174:1c675c5fe5fe

rust-cpython: move borrow_mut() to PySharedRefCell PySharedRefCell() will host almost all py_shared public functions. This change is the first step. borrow_mut() can be safely implemented since PySharedRefCell knows its inner object is managed by its own py_shared_state.
author Yuya Nishihara <yuya@tcha.org>
date Sat, 14 Sep 2019 23:17:19 +0900
parents 070a38737334
children a1908eb08342
comparison
equal deleted inserted replaced
43173:070a38737334 43174:1c675c5fe5fe
138 138
139 pub fn as_ptr(&self) -> *mut T { 139 pub fn as_ptr(&self) -> *mut T {
140 self.inner.as_ptr() 140 self.inner.as_ptr()
141 } 141 }
142 142
143 pub unsafe fn borrow_mut(&self) -> RefMut<T> { 143 // TODO: maybe this should be named as try_borrow_mut(), and use
144 // must be borrowed by self.py_shared_state(py).borrow_mut(). 144 // inner.try_borrow_mut(). The current implementation panics if
145 self.inner.borrow_mut() 145 // self.inner has been borrowed, but returns error if py_shared_state
146 // refuses to borrow.
147 pub fn borrow_mut<'a>(
148 &'a self,
149 py: Python<'a>,
150 ) -> PyResult<PyRefMut<'a, T>> {
151 self.py_shared_state.borrow_mut(py, self.inner.borrow_mut())
146 } 152 }
147 } 153 }
148 154
149 /// Holds a mutable reference to data shared between Python and Rust. 155 /// Holds a mutable reference to data shared between Python and Rust.
150 pub struct PyRefMut<'a, T> { 156 pub struct PyRefMut<'a, T> {
229 $inner_struct: ident, 235 $inner_struct: ident,
230 $data_member: ident, 236 $data_member: ident,
231 $leaked: ident, 237 $leaked: ident,
232 ) => { 238 ) => {
233 impl $name { 239 impl $name {
240 // TODO: remove this function in favor of inner(py).borrow_mut()
234 fn borrow_mut<'a>( 241 fn borrow_mut<'a>(
235 &'a self, 242 &'a self,
236 py: Python<'a>, 243 py: Python<'a>,
237 ) -> PyResult<crate::ref_sharing::PyRefMut<'a, $inner_struct>> 244 ) -> PyResult<crate::ref_sharing::PyRefMut<'a, $inner_struct>>
238 { 245 {
239 // assert $data_member type 246 // assert $data_member type
240 use crate::ref_sharing::PySharedRefCell; 247 use crate::ref_sharing::PySharedRefCell;
241 let data: &PySharedRefCell<_> = self.$data_member(py); 248 let data: &PySharedRefCell<_> = self.$data_member(py);
242 data.py_shared_state 249 data.borrow_mut(py)
243 .borrow_mut(py, unsafe { data.borrow_mut() })
244 } 250 }
245 251
246 /// Returns a leaked reference and its management object. 252 /// Returns a leaked reference and its management object.
247 /// 253 ///
248 /// # Safety 254 /// # Safety