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