57
57
//! [scalars-datetime64]: https://numpy.org/doc/stable/reference/arrays.scalars.html#numpy.datetime64
58
58
//! [scalars-timedelta64]: https://numpy.org/doc/stable/reference/arrays.scalars.html#numpy.timedelta64
59
59
60
- use std:: cell:: UnsafeCell ;
60
+ use std:: cell:: RefCell ;
61
61
use std:: collections:: hash_map:: Entry ;
62
62
use std:: fmt;
63
63
use std:: hash:: Hash ;
64
64
use std:: marker:: PhantomData ;
65
65
66
- use pyo3:: { Py , Python } ;
66
+ use pyo3:: { sync :: GILProtected , Py , Python } ;
67
67
use rustc_hash:: FxHashMap ;
68
68
69
69
use crate :: dtype:: { Element , PyArrayDescr } ;
@@ -206,32 +206,25 @@ impl<U: Unit> fmt::Debug for Timedelta<U> {
206
206
207
207
struct TypeDescriptors {
208
208
npy_type : NPY_TYPES ,
209
- dtypes : UnsafeCell < Option < FxHashMap < NPY_DATETIMEUNIT , Py < PyArrayDescr > > > > ,
209
+ #[ allow( clippy:: type_complexity) ]
210
+ dtypes : GILProtected < RefCell < Option < FxHashMap < NPY_DATETIMEUNIT , Py < PyArrayDescr > > > > > ,
210
211
}
211
212
212
- unsafe impl Sync for TypeDescriptors { }
213
-
214
213
impl TypeDescriptors {
215
214
/// `npy_type` must be either `NPY_DATETIME` or `NPY_TIMEDELTA`.
216
215
const unsafe fn new ( npy_type : NPY_TYPES ) -> Self {
217
216
Self {
218
217
npy_type,
219
- dtypes : UnsafeCell :: new ( None ) ,
218
+ dtypes : GILProtected :: new ( RefCell :: new ( None ) ) ,
220
219
}
221
220
}
222
221
223
- #[ allow( clippy:: mut_from_ref) ]
224
- unsafe fn get ( & self ) -> & mut FxHashMap < NPY_DATETIMEUNIT , Py < PyArrayDescr > > {
225
- ( * self . dtypes . get ( ) ) . get_or_insert_with ( Default :: default)
226
- }
227
-
228
222
#[ allow( clippy:: wrong_self_convention) ]
229
223
fn from_unit < ' py > ( & ' py self , py : Python < ' py > , unit : NPY_DATETIMEUNIT ) -> & ' py PyArrayDescr {
230
- // SAFETY: We hold the GIL and we do not call into user code which might re-enter.
231
- let dtypes = unsafe { self . get ( ) } ;
224
+ let mut dtypes = self . dtypes . get ( py) . borrow_mut ( ) ;
232
225
233
- match dtypes. entry ( unit) {
234
- Entry :: Occupied ( entry) => entry. into_mut ( ) . as_ref ( py) ,
226
+ match dtypes. get_or_insert_with ( Default :: default ) . entry ( unit) {
227
+ Entry :: Occupied ( entry) => entry. into_mut ( ) . clone ( ) . into_ref ( py) ,
235
228
Entry :: Vacant ( entry) => {
236
229
let dtype = PyArrayDescr :: new_from_npy_type ( py, self . npy_type ) ;
237
230
@@ -244,7 +237,7 @@ impl TypeDescriptors {
244
237
metadata. meta . num = 1 ;
245
238
}
246
239
247
- entry. insert ( dtype. into ( ) ) . as_ref ( py)
240
+ entry. insert ( dtype. into ( ) ) . clone ( ) . into_ref ( py)
248
241
}
249
242
}
250
243
}
0 commit comments