##// END OF EJS Templates
rust-cpython: make PyLeakedRef operations relatively safe...
Yuya Nishihara -
r43579:ffc1fbd7 default
parent child Browse files
Show More
@@ -1,120 +1,117 b''
1 // copymap.rs
1 // copymap.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 `hg::dirstate::dirstate_map::CopyMap` provided by the
8 //! Bindings for `hg::dirstate::dirstate_map::CopyMap` provided by the
9 //! `hg-core` package.
9 //! `hg-core` package.
10
10
11 use cpython::{PyBytes, PyClone, PyDict, PyObject, PyResult, Python};
11 use cpython::{PyBytes, PyClone, PyDict, PyObject, PyResult, Python};
12 use std::cell::RefCell;
12 use std::cell::RefCell;
13
13
14 use crate::dirstate::dirstate_map::DirstateMap;
14 use crate::dirstate::dirstate_map::DirstateMap;
15 use crate::ref_sharing::PyLeakedRef;
15 use crate::ref_sharing::PyLeakedRef;
16 use hg::DirstateMap as RustDirstateMap;
17 use hg::{utils::hg_path::HgPathBuf, CopyMapIter};
16 use hg::{utils::hg_path::HgPathBuf, CopyMapIter};
18
17
19 py_class!(pub class CopyMap |py| {
18 py_class!(pub class CopyMap |py| {
20 data dirstate_map: DirstateMap;
19 data dirstate_map: DirstateMap;
21
20
22 def __getitem__(&self, key: PyObject) -> PyResult<PyBytes> {
21 def __getitem__(&self, key: PyObject) -> PyResult<PyBytes> {
23 (*self.dirstate_map(py)).copymapgetitem(py, key)
22 (*self.dirstate_map(py)).copymapgetitem(py, key)
24 }
23 }
25
24
26 def __len__(&self) -> PyResult<usize> {
25 def __len__(&self) -> PyResult<usize> {
27 self.dirstate_map(py).copymaplen(py)
26 self.dirstate_map(py).copymaplen(py)
28 }
27 }
29
28
30 def __contains__(&self, key: PyObject) -> PyResult<bool> {
29 def __contains__(&self, key: PyObject) -> PyResult<bool> {
31 self.dirstate_map(py).copymapcontains(py, key)
30 self.dirstate_map(py).copymapcontains(py, key)
32 }
31 }
33
32
34 def get(
33 def get(
35 &self,
34 &self,
36 key: PyObject,
35 key: PyObject,
37 default: Option<PyObject> = None
36 default: Option<PyObject> = None
38 ) -> PyResult<Option<PyObject>> {
37 ) -> PyResult<Option<PyObject>> {
39 self.dirstate_map(py).copymapget(py, key, default)
38 self.dirstate_map(py).copymapget(py, key, default)
40 }
39 }
41
40
42 def pop(
41 def pop(
43 &self,
42 &self,
44 key: PyObject,
43 key: PyObject,
45 default: Option<PyObject> = None
44 default: Option<PyObject> = None
46 ) -> PyResult<Option<PyObject>> {
45 ) -> PyResult<Option<PyObject>> {
47 self.dirstate_map(py).copymappop(py, key, default)
46 self.dirstate_map(py).copymappop(py, key, default)
48 }
47 }
49
48
50 def __iter__(&self) -> PyResult<CopyMapKeysIterator> {
49 def __iter__(&self) -> PyResult<CopyMapKeysIterator> {
51 self.dirstate_map(py).copymapiter(py)
50 self.dirstate_map(py).copymapiter(py)
52 }
51 }
53
52
54 // Python's `dict()` builtin works with either a subclass of dict
53 // Python's `dict()` builtin works with either a subclass of dict
55 // or an abstract mapping. Said mapping needs to implement `__getitem__`
54 // or an abstract mapping. Said mapping needs to implement `__getitem__`
56 // and `keys`.
55 // and `keys`.
57 def keys(&self) -> PyResult<CopyMapKeysIterator> {
56 def keys(&self) -> PyResult<CopyMapKeysIterator> {
58 self.dirstate_map(py).copymapiter(py)
57 self.dirstate_map(py).copymapiter(py)
59 }
58 }
60
59
61 def items(&self) -> PyResult<CopyMapItemsIterator> {
60 def items(&self) -> PyResult<CopyMapItemsIterator> {
62 self.dirstate_map(py).copymapitemsiter(py)
61 self.dirstate_map(py).copymapitemsiter(py)
63 }
62 }
64
63
65 def iteritems(&self) -> PyResult<CopyMapItemsIterator> {
64 def iteritems(&self) -> PyResult<CopyMapItemsIterator> {
66 self.dirstate_map(py).copymapitemsiter(py)
65 self.dirstate_map(py).copymapitemsiter(py)
67 }
66 }
68
67
69 def __setitem__(
68 def __setitem__(
70 &self,
69 &self,
71 key: PyObject,
70 key: PyObject,
72 item: PyObject
71 item: PyObject
73 ) -> PyResult<()> {
72 ) -> PyResult<()> {
74 self.dirstate_map(py).copymapsetitem(py, key, item)?;
73 self.dirstate_map(py).copymapsetitem(py, key, item)?;
75 Ok(())
74 Ok(())
76 }
75 }
77
76
78 def copy(&self) -> PyResult<PyDict> {
77 def copy(&self) -> PyResult<PyDict> {
79 self.dirstate_map(py).copymapcopy(py)
78 self.dirstate_map(py).copymapcopy(py)
80 }
79 }
81
80
82 });
81 });
83
82
84 impl CopyMap {
83 impl CopyMap {
85 pub fn from_inner(py: Python, dm: DirstateMap) -> PyResult<Self> {
84 pub fn from_inner(py: Python, dm: DirstateMap) -> PyResult<Self> {
86 Self::create_instance(py, dm)
85 Self::create_instance(py, dm)
87 }
86 }
88 fn translate_key(
87 fn translate_key(
89 py: Python,
88 py: Python,
90 res: (&HgPathBuf, &HgPathBuf),
89 res: (&HgPathBuf, &HgPathBuf),
91 ) -> PyResult<Option<PyBytes>> {
90 ) -> PyResult<Option<PyBytes>> {
92 Ok(Some(PyBytes::new(py, res.0.as_ref())))
91 Ok(Some(PyBytes::new(py, res.0.as_ref())))
93 }
92 }
94 fn translate_key_value(
93 fn translate_key_value(
95 py: Python,
94 py: Python,
96 res: (&HgPathBuf, &HgPathBuf),
95 res: (&HgPathBuf, &HgPathBuf),
97 ) -> PyResult<Option<(PyBytes, PyBytes)>> {
96 ) -> PyResult<Option<(PyBytes, PyBytes)>> {
98 let (k, v) = res;
97 let (k, v) = res;
99 Ok(Some((
98 Ok(Some((
100 PyBytes::new(py, k.as_ref()),
99 PyBytes::new(py, k.as_ref()),
101 PyBytes::new(py, v.as_ref()),
100 PyBytes::new(py, v.as_ref()),
102 )))
101 )))
103 }
102 }
104 }
103 }
105
104
106 py_shared_iterator!(
105 py_shared_iterator!(
107 CopyMapKeysIterator,
106 CopyMapKeysIterator,
108 PyLeakedRef<&'static RustDirstateMap>,
107 PyLeakedRef<CopyMapIter<'static>>,
109 CopyMapIter<'static>,
110 CopyMap::translate_key,
108 CopyMap::translate_key,
111 Option<PyBytes>
109 Option<PyBytes>
112 );
110 );
113
111
114 py_shared_iterator!(
112 py_shared_iterator!(
115 CopyMapItemsIterator,
113 CopyMapItemsIterator,
116 PyLeakedRef<&'static RustDirstateMap>,
114 PyLeakedRef<CopyMapIter<'static>>,
117 CopyMapIter<'static>,
118 CopyMap::translate_key_value,
115 CopyMap::translate_key_value,
119 Option<(PyBytes, PyBytes)>
116 Option<(PyBytes, PyBytes)>
120 );
117 );
@@ -1,133 +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 mut leak_handle =
95 let leaked_ref = self.inner_shared(py).leak_immutable()?;
96 unsafe { self.inner_shared(py).leak_immutable()? };
97 let leaked_ref = leak_handle.data.take().unwrap();
98 DirsMultisetKeysIterator::from_inner(
96 DirsMultisetKeysIterator::from_inner(
99 py,
97 py,
100 leak_handle,
98 unsafe { leaked_ref.map(py, |o| o.iter()) },
101 leaked_ref.iter(),
102 )
99 )
103 }
100 }
104
101
105 def __contains__(&self, item: PyObject) -> PyResult<bool> {
102 def __contains__(&self, item: PyObject) -> PyResult<bool> {
106 Ok(self.inner(py).borrow().contains(HgPath::new(
103 Ok(self.inner(py).borrow().contains(HgPath::new(
107 item.extract::<PyBytes>(py)?.data(py).as_ref(),
104 item.extract::<PyBytes>(py)?.data(py).as_ref(),
108 )))
105 )))
109 }
106 }
110 });
107 });
111
108
112 py_shared_ref!(Dirs, DirsMultiset, inner, inner_shared);
109 py_shared_ref!(Dirs, DirsMultiset, inner, inner_shared);
113
110
114 impl Dirs {
111 impl Dirs {
115 pub fn from_inner(py: Python, d: DirsMultiset) -> PyResult<Self> {
112 pub fn from_inner(py: Python, d: DirsMultiset) -> PyResult<Self> {
116 Self::create_instance(py, PySharedRefCell::new(d))
113 Self::create_instance(py, PySharedRefCell::new(d))
117 }
114 }
118
115
119 fn translate_key(
116 fn translate_key(
120 py: Python,
117 py: Python,
121 res: &HgPathBuf,
118 res: &HgPathBuf,
122 ) -> PyResult<Option<PyBytes>> {
119 ) -> PyResult<Option<PyBytes>> {
123 Ok(Some(PyBytes::new(py, res.as_ref())))
120 Ok(Some(PyBytes::new(py, res.as_ref())))
124 }
121 }
125 }
122 }
126
123
127 py_shared_iterator!(
124 py_shared_iterator!(
128 DirsMultisetKeysIterator,
125 DirsMultisetKeysIterator,
129 PyLeakedRef<&'static DirsMultiset>,
126 PyLeakedRef<DirsMultisetIter<'static>>,
130 DirsMultisetIter<'static>,
131 Dirs::translate_key,
127 Dirs::translate_key,
132 Option<PyBytes>
128 Option<PyBytes>
133 );
129 );
@@ -1,521 +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(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(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(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(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(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 mut leak_handle =
307 let leaked_ref = self.inner_shared(py).leak_immutable()?;
308 unsafe { self.inner_shared(py).leak_immutable()? };
309 let leaked_ref = leak_handle.data.take().unwrap();
310 DirstateMapKeysIterator::from_inner(
308 DirstateMapKeysIterator::from_inner(
311 py,
309 py,
312 leak_handle,
310 unsafe { leaked_ref.map(py, |o| o.iter()) },
313 leaked_ref.iter(),
314 )
311 )
315 }
312 }
316
313
317 def items(&self) -> PyResult<DirstateMapItemsIterator> {
314 def items(&self) -> PyResult<DirstateMapItemsIterator> {
318 let mut leak_handle =
315 let leaked_ref = self.inner_shared(py).leak_immutable()?;
319 unsafe { self.inner_shared(py).leak_immutable()? };
320 let leaked_ref = leak_handle.data.take().unwrap();
321 DirstateMapItemsIterator::from_inner(
316 DirstateMapItemsIterator::from_inner(
322 py,
317 py,
323 leak_handle,
318 unsafe { leaked_ref.map(py, |o| o.iter()) },
324 leaked_ref.iter(),
325 )
319 )
326 }
320 }
327
321
328 def __iter__(&self) -> PyResult<DirstateMapKeysIterator> {
322 def __iter__(&self) -> PyResult<DirstateMapKeysIterator> {
329 let mut leak_handle =
323 let leaked_ref = self.inner_shared(py).leak_immutable()?;
330 unsafe { self.inner_shared(py).leak_immutable()? };
331 let leaked_ref = leak_handle.data.take().unwrap();
332 DirstateMapKeysIterator::from_inner(
324 DirstateMapKeysIterator::from_inner(
333 py,
325 py,
334 leak_handle,
326 unsafe { leaked_ref.map(py, |o| o.iter()) },
335 leaked_ref.iter(),
336 )
327 )
337 }
328 }
338
329
339 def getdirs(&self) -> PyResult<Dirs> {
330 def getdirs(&self) -> PyResult<Dirs> {
340 // TODO don't copy, share the reference
331 // TODO don't copy, share the reference
341 self.inner_shared(py).borrow_mut()?.set_dirs();
332 self.inner_shared(py).borrow_mut()?.set_dirs();
342 Dirs::from_inner(
333 Dirs::from_inner(
343 py,
334 py,
344 DirsMultiset::from_dirstate(
335 DirsMultiset::from_dirstate(
345 &self.inner(py).borrow(),
336 &self.inner(py).borrow(),
346 Some(EntryState::Removed),
337 Some(EntryState::Removed),
347 ),
338 ),
348 )
339 )
349 }
340 }
350 def getalldirs(&self) -> PyResult<Dirs> {
341 def getalldirs(&self) -> PyResult<Dirs> {
351 // TODO don't copy, share the reference
342 // TODO don't copy, share the reference
352 self.inner_shared(py).borrow_mut()?.set_all_dirs();
343 self.inner_shared(py).borrow_mut()?.set_all_dirs();
353 Dirs::from_inner(
344 Dirs::from_inner(
354 py,
345 py,
355 DirsMultiset::from_dirstate(
346 DirsMultiset::from_dirstate(
356 &self.inner(py).borrow(),
347 &self.inner(py).borrow(),
357 None,
348 None,
358 ),
349 ),
359 )
350 )
360 }
351 }
361
352
362 // TODO all copymap* methods, see docstring above
353 // TODO all copymap* methods, see docstring above
363 def copymapcopy(&self) -> PyResult<PyDict> {
354 def copymapcopy(&self) -> PyResult<PyDict> {
364 let dict = PyDict::new(py);
355 let dict = PyDict::new(py);
365 for (key, value) in self.inner(py).borrow().copy_map.iter() {
356 for (key, value) in self.inner(py).borrow().copy_map.iter() {
366 dict.set_item(
357 dict.set_item(
367 py,
358 py,
368 PyBytes::new(py, key.as_ref()),
359 PyBytes::new(py, key.as_ref()),
369 PyBytes::new(py, value.as_ref()),
360 PyBytes::new(py, value.as_ref()),
370 )?;
361 )?;
371 }
362 }
372 Ok(dict)
363 Ok(dict)
373 }
364 }
374
365
375 def copymapgetitem(&self, key: PyObject) -> PyResult<PyBytes> {
366 def copymapgetitem(&self, key: PyObject) -> PyResult<PyBytes> {
376 let key = key.extract::<PyBytes>(py)?;
367 let key = key.extract::<PyBytes>(py)?;
377 match self.inner(py).borrow().copy_map.get(HgPath::new(key.data(py))) {
368 match self.inner(py).borrow().copy_map.get(HgPath::new(key.data(py))) {
378 Some(copy) => Ok(PyBytes::new(py, copy.as_ref())),
369 Some(copy) => Ok(PyBytes::new(py, copy.as_ref())),
379 None => Err(PyErr::new::<exc::KeyError, _>(
370 None => Err(PyErr::new::<exc::KeyError, _>(
380 py,
371 py,
381 String::from_utf8_lossy(key.data(py)),
372 String::from_utf8_lossy(key.data(py)),
382 )),
373 )),
383 }
374 }
384 }
375 }
385 def copymap(&self) -> PyResult<CopyMap> {
376 def copymap(&self) -> PyResult<CopyMap> {
386 CopyMap::from_inner(py, self.clone_ref(py))
377 CopyMap::from_inner(py, self.clone_ref(py))
387 }
378 }
388
379
389 def copymaplen(&self) -> PyResult<usize> {
380 def copymaplen(&self) -> PyResult<usize> {
390 Ok(self.inner(py).borrow().copy_map.len())
381 Ok(self.inner(py).borrow().copy_map.len())
391 }
382 }
392 def copymapcontains(&self, key: PyObject) -> PyResult<bool> {
383 def copymapcontains(&self, key: PyObject) -> PyResult<bool> {
393 let key = key.extract::<PyBytes>(py)?;
384 let key = key.extract::<PyBytes>(py)?;
394 Ok(self
385 Ok(self
395 .inner(py)
386 .inner(py)
396 .borrow()
387 .borrow()
397 .copy_map
388 .copy_map
398 .contains_key(HgPath::new(key.data(py))))
389 .contains_key(HgPath::new(key.data(py))))
399 }
390 }
400 def copymapget(
391 def copymapget(
401 &self,
392 &self,
402 key: PyObject,
393 key: PyObject,
403 default: Option<PyObject>
394 default: Option<PyObject>
404 ) -> PyResult<Option<PyObject>> {
395 ) -> PyResult<Option<PyObject>> {
405 let key = key.extract::<PyBytes>(py)?;
396 let key = key.extract::<PyBytes>(py)?;
406 match self
397 match self
407 .inner(py)
398 .inner(py)
408 .borrow()
399 .borrow()
409 .copy_map
400 .copy_map
410 .get(HgPath::new(key.data(py)))
401 .get(HgPath::new(key.data(py)))
411 {
402 {
412 Some(copy) => Ok(Some(
403 Some(copy) => Ok(Some(
413 PyBytes::new(py, copy.as_ref()).into_object(),
404 PyBytes::new(py, copy.as_ref()).into_object(),
414 )),
405 )),
415 None => Ok(default),
406 None => Ok(default),
416 }
407 }
417 }
408 }
418 def copymapsetitem(
409 def copymapsetitem(
419 &self,
410 &self,
420 key: PyObject,
411 key: PyObject,
421 value: PyObject
412 value: PyObject
422 ) -> PyResult<PyObject> {
413 ) -> PyResult<PyObject> {
423 let key = key.extract::<PyBytes>(py)?;
414 let key = key.extract::<PyBytes>(py)?;
424 let value = value.extract::<PyBytes>(py)?;
415 let value = value.extract::<PyBytes>(py)?;
425 self.inner_shared(py).borrow_mut()?.copy_map.insert(
416 self.inner_shared(py).borrow_mut()?.copy_map.insert(
426 HgPathBuf::from_bytes(key.data(py)),
417 HgPathBuf::from_bytes(key.data(py)),
427 HgPathBuf::from_bytes(value.data(py)),
418 HgPathBuf::from_bytes(value.data(py)),
428 );
419 );
429 Ok(py.None())
420 Ok(py.None())
430 }
421 }
431 def copymappop(
422 def copymappop(
432 &self,
423 &self,
433 key: PyObject,
424 key: PyObject,
434 default: Option<PyObject>
425 default: Option<PyObject>
435 ) -> PyResult<Option<PyObject>> {
426 ) -> PyResult<Option<PyObject>> {
436 let key = key.extract::<PyBytes>(py)?;
427 let key = key.extract::<PyBytes>(py)?;
437 match self
428 match self
438 .inner_shared(py)
429 .inner_shared(py)
439 .borrow_mut()?
430 .borrow_mut()?
440 .copy_map
431 .copy_map
441 .remove(HgPath::new(key.data(py)))
432 .remove(HgPath::new(key.data(py)))
442 {
433 {
443 Some(_) => Ok(None),
434 Some(_) => Ok(None),
444 None => Ok(default),
435 None => Ok(default),
445 }
436 }
446 }
437 }
447
438
448 def copymapiter(&self) -> PyResult<CopyMapKeysIterator> {
439 def copymapiter(&self) -> PyResult<CopyMapKeysIterator> {
449 let mut leak_handle =
440 let leaked_ref = self.inner_shared(py).leak_immutable()?;
450 unsafe { self.inner_shared(py).leak_immutable()? };
451 let leaked_ref = leak_handle.data.take().unwrap();
452 CopyMapKeysIterator::from_inner(
441 CopyMapKeysIterator::from_inner(
453 py,
442 py,
454 leak_handle,
443 unsafe { leaked_ref.map(py, |o| o.copy_map.iter()) },
455 leaked_ref.copy_map.iter(),
456 )
444 )
457 }
445 }
458
446
459 def copymapitemsiter(&self) -> PyResult<CopyMapItemsIterator> {
447 def copymapitemsiter(&self) -> PyResult<CopyMapItemsIterator> {
460 let mut leak_handle =
448 let leaked_ref = self.inner_shared(py).leak_immutable()?;
461 unsafe { self.inner_shared(py).leak_immutable()? };
462 let leaked_ref = leak_handle.data.take().unwrap();
463 CopyMapItemsIterator::from_inner(
449 CopyMapItemsIterator::from_inner(
464 py,
450 py,
465 leak_handle,
451 unsafe { leaked_ref.map(py, |o| o.copy_map.iter()) },
466 leaked_ref.copy_map.iter(),
467 )
452 )
468 }
453 }
469
454
470 });
455 });
471
456
472 impl DirstateMap {
457 impl DirstateMap {
473 pub fn get_inner<'a>(
458 pub fn get_inner<'a>(
474 &'a self,
459 &'a self,
475 py: Python<'a>,
460 py: Python<'a>,
476 ) -> Ref<'a, RustDirstateMap> {
461 ) -> Ref<'a, RustDirstateMap> {
477 self.inner_shared(py).borrow()
462 self.inner_shared(py).borrow()
478 }
463 }
479 fn translate_key(
464 fn translate_key(
480 py: Python,
465 py: Python,
481 res: (&HgPathBuf, &DirstateEntry),
466 res: (&HgPathBuf, &DirstateEntry),
482 ) -> PyResult<Option<PyBytes>> {
467 ) -> PyResult<Option<PyBytes>> {
483 Ok(Some(PyBytes::new(py, res.0.as_ref())))
468 Ok(Some(PyBytes::new(py, res.0.as_ref())))
484 }
469 }
485 fn translate_key_value(
470 fn translate_key_value(
486 py: Python,
471 py: Python,
487 res: (&HgPathBuf, &DirstateEntry),
472 res: (&HgPathBuf, &DirstateEntry),
488 ) -> PyResult<Option<(PyBytes, PyObject)>> {
473 ) -> PyResult<Option<(PyBytes, PyObject)>> {
489 let (f, entry) = res;
474 let (f, entry) = res;
490 Ok(Some((
475 Ok(Some((
491 PyBytes::new(py, f.as_ref()),
476 PyBytes::new(py, f.as_ref()),
492 make_dirstate_tuple(py, entry)?,
477 make_dirstate_tuple(py, entry)?,
493 )))
478 )))
494 }
479 }
495 }
480 }
496
481
497 py_shared_ref!(DirstateMap, RustDirstateMap, inner, inner_shared);
482 py_shared_ref!(DirstateMap, RustDirstateMap, inner, inner_shared);
498
483
499 py_shared_iterator!(
484 py_shared_iterator!(
500 DirstateMapKeysIterator,
485 DirstateMapKeysIterator,
501 PyLeakedRef<&'static RustDirstateMap>,
486 PyLeakedRef<StateMapIter<'static>>,
502 StateMapIter<'static>,
503 DirstateMap::translate_key,
487 DirstateMap::translate_key,
504 Option<PyBytes>
488 Option<PyBytes>
505 );
489 );
506
490
507 py_shared_iterator!(
491 py_shared_iterator!(
508 DirstateMapItemsIterator,
492 DirstateMapItemsIterator,
509 PyLeakedRef<&'static RustDirstateMap>,
493 PyLeakedRef<StateMapIter<'static>>,
510 StateMapIter<'static>,
511 DirstateMap::translate_key_value,
494 DirstateMap::translate_key_value,
512 Option<(PyBytes, PyObject)>
495 Option<(PyBytes, PyObject)>
513 );
496 );
514
497
515 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]> {
516 let bytes = obj.extract::<PyBytes>(py)?;
499 let bytes = obj.extract::<PyBytes>(py)?;
517 match bytes.data(py).try_into() {
500 match bytes.data(py).try_into() {
518 Ok(s) => Ok(s),
501 Ok(s) => Ok(s),
519 Err(e) => Err(PyErr::new::<exc::ValueError, _>(py, e.to_string())),
502 Err(e) => Err(PyErr::new::<exc::ValueError, _>(py, e.to_string())),
520 }
503 }
521 }
504 }
@@ -1,469 +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(&self) -> Ref<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()
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 temporarily held by its management object.
190 /// Returns a leaked reference.
191 ///
191 pub fn leak_immutable(&self) -> PyResult<PyLeakedRef<&'static T>> {
192 /// # Safety
192 let state = &self.data.py_shared_state;
193 ///
193 unsafe {
194 /// It's up to you to make sure that the management object lives
194 let (static_ref, static_state_ref) =
195 /// longer than the leaked reference. Otherwise, you'll get a
195 state.leak_immutable(self.py, self.data)?;
196 /// dangling reference.
196 Ok(PyLeakedRef::new(
197 pub unsafe fn leak_immutable(&self) -> PyResult<PyLeakedRef<&'static T>> {
197 self.py,
198 let (static_ref, static_state_ref) = self
198 self.owner,
199 .data
199 static_ref,
200 .py_shared_state
200 static_state_ref,
201 .leak_immutable(self.py, self.data)?;
201 ))
202 Ok(PyLeakedRef::new(
202 }
203 self.py,
204 self.owner,
205 static_ref,
206 static_state_ref,
207 ))
208 }
203 }
209 }
204 }
210
205
211 /// Holds a mutable reference to data shared between Python and Rust.
206 /// Holds a mutable reference to data shared between Python and Rust.
212 pub struct PyRefMut<'a, T> {
207 pub struct PyRefMut<'a, T> {
213 inner: RefMut<'a, T>,
208 inner: RefMut<'a, T>,
214 py_shared_state: &'a PySharedState,
209 py_shared_state: &'a PySharedState,
215 }
210 }
216
211
217 impl<'a, T> PyRefMut<'a, T> {
212 impl<'a, T> PyRefMut<'a, T> {
218 // Must be constructed by PySharedState after checking its leak_count.
213 // Must be constructed by PySharedState after checking its leak_count.
219 // Otherwise, drop() would incorrectly update the state.
214 // Otherwise, drop() would incorrectly update the state.
220 fn new(
215 fn new(
221 _py: Python<'a>,
216 _py: Python<'a>,
222 inner: RefMut<'a, T>,
217 inner: RefMut<'a, T>,
223 py_shared_state: &'a PySharedState,
218 py_shared_state: &'a PySharedState,
224 ) -> Self {
219 ) -> Self {
225 Self {
220 Self {
226 inner,
221 inner,
227 py_shared_state,
222 py_shared_state,
228 }
223 }
229 }
224 }
230 }
225 }
231
226
232 impl<'a, T> std::ops::Deref for PyRefMut<'a, T> {
227 impl<'a, T> std::ops::Deref for PyRefMut<'a, T> {
233 type Target = RefMut<'a, T>;
228 type Target = RefMut<'a, T>;
234
229
235 fn deref(&self) -> &Self::Target {
230 fn deref(&self) -> &Self::Target {
236 &self.inner
231 &self.inner
237 }
232 }
238 }
233 }
239 impl<'a, T> std::ops::DerefMut for PyRefMut<'a, T> {
234 impl<'a, T> std::ops::DerefMut for PyRefMut<'a, T> {
240 fn deref_mut(&mut self) -> &mut Self::Target {
235 fn deref_mut(&mut self) -> &mut Self::Target {
241 &mut self.inner
236 &mut self.inner
242 }
237 }
243 }
238 }
244
239
245 impl<'a, T> Drop for PyRefMut<'a, T> {
240 impl<'a, T> Drop for PyRefMut<'a, T> {
246 fn drop(&mut self) {
241 fn drop(&mut self) {
247 let gil = Python::acquire_gil();
242 let gil = Python::acquire_gil();
248 let py = gil.python();
243 let py = gil.python();
249 unsafe {
244 unsafe {
250 self.py_shared_state.decrease_leak_count(py, true);
245 self.py_shared_state.decrease_leak_count(py, true);
251 }
246 }
252 }
247 }
253 }
248 }
254
249
255 /// 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
256 /// data members with Python.
251 /// data members with Python.
257 ///
252 ///
258 /// # Warning
253 /// # Warning
259 ///
254 ///
260 /// TODO allow Python container types: for now, integration with the garbage
255 /// TODO allow Python container types: for now, integration with the garbage
261 /// collector does not extend to Rust structs holding references to Python
256 /// collector does not extend to Rust structs holding references to Python
262 /// objects. Should the need surface, `__traverse__` and `__clear__` will
257 /// objects. Should the need surface, `__traverse__` and `__clear__` will
263 /// 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.
264 ///
259 ///
265 /// # Parameters
260 /// # Parameters
266 ///
261 ///
267 /// * `$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.
268 /// * `$inner_struct` is the identifier of the underlying Rust struct
263 /// * `$inner_struct` is the identifier of the underlying Rust struct
269 /// * `$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`
270 /// that will be shared.
265 /// that will be shared.
271 /// * `$shared_accessor` is the function name to be generated, which allows
266 /// * `$shared_accessor` is the function name to be generated, which allows
272 /// safe access to the data member.
267 /// safe access to the data member.
273 ///
268 ///
274 /// # Safety
269 /// # Safety
275 ///
270 ///
276 /// `$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
277 /// 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.
278 ///
273 ///
279 /// # Example
274 /// # Example
280 ///
275 ///
281 /// ```
276 /// ```
282 /// struct MyStruct {
277 /// struct MyStruct {
283 /// inner: Vec<u32>;
278 /// inner: Vec<u32>;
284 /// }
279 /// }
285 ///
280 ///
286 /// py_class!(pub class MyType |py| {
281 /// py_class!(pub class MyType |py| {
287 /// data inner: PySharedRefCell<MyStruct>;
282 /// data inner: PySharedRefCell<MyStruct>;
288 /// });
283 /// });
289 ///
284 ///
290 /// py_shared_ref!(MyType, MyStruct, inner, inner_shared);
285 /// py_shared_ref!(MyType, MyStruct, inner, inner_shared);
291 /// ```
286 /// ```
292 macro_rules! py_shared_ref {
287 macro_rules! py_shared_ref {
293 (
288 (
294 $name: ident,
289 $name: ident,
295 $inner_struct: ident,
290 $inner_struct: ident,
296 $data_member: ident,
291 $data_member: ident,
297 $shared_accessor: ident
292 $shared_accessor: ident
298 ) => {
293 ) => {
299 impl $name {
294 impl $name {
300 /// Returns a safe reference to the shared `$data_member`.
295 /// Returns a safe reference to the shared `$data_member`.
301 ///
296 ///
302 /// This function guarantees that `PySharedRef` is created with
297 /// This function guarantees that `PySharedRef` is created with
303 /// the valid `self` and `self.$data_member(py)` pair.
298 /// the valid `self` and `self.$data_member(py)` pair.
304 fn $shared_accessor<'a>(
299 fn $shared_accessor<'a>(
305 &'a self,
300 &'a self,
306 py: Python<'a>,
301 py: Python<'a>,
307 ) -> $crate::ref_sharing::PySharedRef<'a, $inner_struct> {
302 ) -> $crate::ref_sharing::PySharedRef<'a, $inner_struct> {
308 use cpython::PythonObject;
303 use cpython::PythonObject;
309 use $crate::ref_sharing::PySharedRef;
304 use $crate::ref_sharing::PySharedRef;
310 let owner = self.as_object();
305 let owner = self.as_object();
311 let data = self.$data_member(py);
306 let data = self.$data_member(py);
312 unsafe { PySharedRef::new(py, owner, data) }
307 unsafe { PySharedRef::new(py, owner, data) }
313 }
308 }
314 }
309 }
315 };
310 };
316 }
311 }
317
312
318 /// Manage immutable references to `PyObject` leaked into Python iterators.
313 /// Manage immutable references to `PyObject` leaked into Python iterators.
319 ///
320 /// In truth, this does not represent leaked references themselves;
321 /// it is instead useful alongside them to manage them.
322 pub struct PyLeakedRef<T> {
314 pub struct PyLeakedRef<T> {
323 _inner: PyObject,
315 inner: PyObject,
324 pub data: Option<T>, // TODO: remove pub
316 data: Option<T>,
325 py_shared_state: &'static PySharedState,
317 py_shared_state: &'static PySharedState,
326 }
318 }
327
319
320 // DO NOT implement Deref for PyLeakedRef<T>! Dereferencing PyLeakedRef
321 // without taking Python GIL wouldn't be safe.
322
328 impl<T> PyLeakedRef<T> {
323 impl<T> PyLeakedRef<T> {
329 /// # Safety
324 /// # Safety
330 ///
325 ///
331 /// 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.
332 // Marked as unsafe so client code wouldn't construct PyLeakedRef
327 // Marked as unsafe so client code wouldn't construct PyLeakedRef
333 // struct by mistake. Its drop() is unsafe.
328 // struct by mistake. Its drop() is unsafe.
334 pub unsafe fn new(
329 pub unsafe fn new(
335 py: Python,
330 py: Python,
336 inner: &PyObject,
331 inner: &PyObject,
337 data: T,
332 data: T,
338 py_shared_state: &'static PySharedState,
333 py_shared_state: &'static PySharedState,
339 ) -> Self {
334 ) -> Self {
340 Self {
335 Self {
341 _inner: inner.clone_ref(py),
336 inner: inner.clone_ref(py),
342 data: Some(data),
337 data: Some(data),
343 py_shared_state,
338 py_shared_state,
344 }
339 }
345 }
340 }
341
342 /// Returns an immutable reference to the inner value.
343 pub fn get_ref<'a>(&'a self, _py: Python<'a>) -> &'a T {
344 self.data.as_ref().unwrap()
345 }
346
347 /// Returns a mutable reference to the inner value.
348 ///
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.
351 pub fn get_mut<'a>(&'a mut self, _py: Python<'a>) -> &'a mut T {
352 self.data.as_mut().unwrap()
353 }
354
355 /// Converts the inner value by the given function.
356 ///
357 /// Typically `T` is a static reference to a container, and `U` is an
358 /// iterator of that container.
359 ///
360 /// # Safety
361 ///
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
364 /// corresponding `PyLeakedRef` is alive. Do not copy it out of the
365 /// function call.
366 pub unsafe fn map<U>(
367 mut self,
368 py: Python,
369 f: impl FnOnce(T) -> U,
370 ) -> PyLeakedRef<U> {
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
373 // temporarily restrict the lifetime of self.data and translate the
374 // returned object back to Something<'static>.
375 let new_data = f(self.data.take().unwrap());
376 PyLeakedRef {
377 inner: self.inner.clone_ref(py),
378 data: Some(new_data),
379 py_shared_state: self.py_shared_state,
380 }
381 }
346 }
382 }
347
383
348 impl<T> Drop for PyLeakedRef<T> {
384 impl<T> Drop for PyLeakedRef<T> {
349 fn drop(&mut self) {
385 fn drop(&mut self) {
350 // py_shared_state should be alive since we do have
386 // py_shared_state should be alive since we do have
351 // a Python reference to the owner object. Taking GIL makes
387 // a Python reference to the owner object. Taking GIL makes
352 // sure that the state is only accessed by this thread.
388 // sure that the state is only accessed by this thread.
353 let gil = Python::acquire_gil();
389 let gil = Python::acquire_gil();
354 let py = gil.python();
390 let py = gil.python();
391 if self.data.is_none() {
392 return; // moved to another PyLeakedRef
393 }
355 unsafe {
394 unsafe {
356 self.py_shared_state.decrease_leak_count(py, false);
395 self.py_shared_state.decrease_leak_count(py, false);
357 }
396 }
358 }
397 }
359 }
398 }
360
399
361 /// 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.
362 ///
401 ///
363 /// 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)
364 /// procedural macro would simplify the interface a lot.
403 /// procedural macro would simplify the interface a lot.
365 ///
404 ///
366 /// # Parameters
405 /// # Parameters
367 ///
406 ///
368 /// * `$name` is the identifier to give to the resulting Rust struct.
407 /// * `$name` is the identifier to give to the resulting Rust struct.
369 /// * `$leaked` corresponds to `$leaked` in the matching `py_shared_ref!` call.
408 /// * `$leaked` corresponds to `$leaked` in the matching `py_shared_ref!` call.
370 /// * `$iterator_type` is the type of the Rust iterator.
409 /// * `$iterator_type` is the type of the Rust iterator.
371 /// * `$success_func` is a function for processing the Rust `(key, value)`
410 /// * `$success_func` is a function for processing the Rust `(key, value)`
372 /// tuple on iteration success, turning it into something Python understands.
411 /// tuple on iteration success, turning it into something Python understands.
373 /// * `$success_func` is the return type of `$success_func`
412 /// * `$success_func` is the return type of `$success_func`
374 ///
413 ///
375 /// # Example
414 /// # Example
376 ///
415 ///
377 /// ```
416 /// ```
378 /// struct MyStruct {
417 /// struct MyStruct {
379 /// inner: HashMap<Vec<u8>, Vec<u8>>;
418 /// inner: HashMap<Vec<u8>, Vec<u8>>;
380 /// }
419 /// }
381 ///
420 ///
382 /// py_class!(pub class MyType |py| {
421 /// py_class!(pub class MyType |py| {
383 /// data inner: PySharedRefCell<MyStruct>;
422 /// data inner: PySharedRefCell<MyStruct>;
384 ///
423 ///
385 /// def __iter__(&self) -> PyResult<MyTypeItemsIterator> {
424 /// def __iter__(&self) -> PyResult<MyTypeItemsIterator> {
386 /// let mut leak_handle =
425 /// let leaked_ref = self.inner_shared(py).leak_immutable()?;
387 /// unsafe { self.inner_shared(py).leak_immutable()? };
388 /// let leaked_ref = leak_handle.data.take().unwrap();
389 /// MyTypeItemsIterator::from_inner(
426 /// MyTypeItemsIterator::from_inner(
390 /// py,
427 /// py,
391 /// leak_handle,
428 /// unsafe { leaked_ref.map(py, |o| o.iter()) },
392 /// leaked_ref.iter(),
393 /// )
429 /// )
394 /// }
430 /// }
395 /// });
431 /// });
396 ///
432 ///
397 /// impl MyType {
433 /// impl MyType {
398 /// fn translate_key_value(
434 /// fn translate_key_value(
399 /// py: Python,
435 /// py: Python,
400 /// res: (&Vec<u8>, &Vec<u8>),
436 /// res: (&Vec<u8>, &Vec<u8>),
401 /// ) -> PyResult<Option<(PyBytes, PyBytes)>> {
437 /// ) -> PyResult<Option<(PyBytes, PyBytes)>> {
402 /// let (f, entry) = res;
438 /// let (f, entry) = res;
403 /// Ok(Some((
439 /// Ok(Some((
404 /// PyBytes::new(py, f),
440 /// PyBytes::new(py, f),
405 /// PyBytes::new(py, entry),
441 /// PyBytes::new(py, entry),
406 /// )))
442 /// )))
407 /// }
443 /// }
408 /// }
444 /// }
409 ///
445 ///
410 /// py_shared_ref!(MyType, MyStruct, inner, MyTypeLeakedRef);
446 /// py_shared_ref!(MyType, MyStruct, inner, MyTypeLeakedRef);
411 ///
447 ///
412 /// py_shared_iterator!(
448 /// py_shared_iterator!(
413 /// MyTypeItemsIterator,
449 /// MyTypeItemsIterator,
414 /// PyLeakedRef<&'static MyStruct>,
450 /// PyLeakedRef<HashMap<'static, Vec<u8>, Vec<u8>>>,
415 /// HashMap<'static, Vec<u8>, Vec<u8>>,
416 /// MyType::translate_key_value,
451 /// MyType::translate_key_value,
417 /// Option<(PyBytes, PyBytes)>
452 /// Option<(PyBytes, PyBytes)>
418 /// );
453 /// );
419 /// ```
454 /// ```
420 macro_rules! py_shared_iterator {
455 macro_rules! py_shared_iterator {
421 (
456 (
422 $name: ident,
457 $name: ident,
423 $leaked: ty,
458 $leaked: ty,
424 $iterator_type: ty,
425 $success_func: expr,
459 $success_func: expr,
426 $success_type: ty
460 $success_type: ty
427 ) => {
461 ) => {
428 py_class!(pub class $name |py| {
462 py_class!(pub class $name |py| {
429 data inner: RefCell<Option<$leaked>>;
463 data inner: RefCell<Option<$leaked>>;
430 data it: RefCell<$iterator_type>;
431
464
432 def __next__(&self) -> PyResult<$success_type> {
465 def __next__(&self) -> PyResult<$success_type> {
433 let mut inner_opt = self.inner(py).borrow_mut();
466 let mut inner_opt = self.inner(py).borrow_mut();
434 if inner_opt.is_some() {
467 if let Some(leaked) = inner_opt.as_mut() {
435 match self.it(py).borrow_mut().next() {
468 match leaked.get_mut(py).next() {
436 None => {
469 None => {
437 // replace Some(inner) by None, drop $leaked
470 // replace Some(inner) by None, drop $leaked
438 inner_opt.take();
471 inner_opt.take();
439 Ok(None)
472 Ok(None)
440 }
473 }
441 Some(res) => {
474 Some(res) => {
442 $success_func(py, res)
475 $success_func(py, res)
443 }
476 }
444 }
477 }
445 } else {
478 } else {
446 Ok(None)
479 Ok(None)
447 }
480 }
448 }
481 }
449
482
450 def __iter__(&self) -> PyResult<Self> {
483 def __iter__(&self) -> PyResult<Self> {
451 Ok(self.clone_ref(py))
484 Ok(self.clone_ref(py))
452 }
485 }
453 });
486 });
454
487
455 impl $name {
488 impl $name {
456 pub fn from_inner(
489 pub fn from_inner(
457 py: Python,
490 py: Python,
458 leaked: $leaked,
491 leaked: $leaked,
459 it: $iterator_type
460 ) -> PyResult<Self> {
492 ) -> PyResult<Self> {
461 Self::create_instance(
493 Self::create_instance(
462 py,
494 py,
463 RefCell::new(Some(leaked)),
495 RefCell::new(Some(leaked)),
464 RefCell::new(it)
465 )
496 )
466 }
497 }
467 }
498 }
468 };
499 };
469 }
500 }
General Comments 0
You need to be logged in to leave comments. Login now