Skip to content
Prev Previous commit
Next Next commit
&self support for getter/setter
  • Loading branch information
youknowone committed Feb 5, 2020
commit ca557788c8d9330079cfadd05798feeeb5fe57f0
35 changes: 32 additions & 3 deletions vm/src/obj/objgetset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

*/
use super::objtype::PyClassRef;
use crate::function::OptionalArg;
use crate::function::{OptionalArg, OwnedParam, RefParam};
use crate::pyobject::{
IntoPyObject, PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue, TryFromObject,
};
Expand All @@ -16,7 +16,7 @@ pub trait IntoPyGetterFunc<T, R> {
fn into_getter(self) -> PyGetterFunc;
}

impl<F, T, R> IntoPyGetterFunc<T, R> for F
impl<F, T, R> IntoPyGetterFunc<OwnedParam<T>, R> for F
where
F: Fn(T, &VirtualMachine) -> R + 'static,
T: TryFromObject,
Expand All @@ -30,11 +30,25 @@ where
}
}

impl<F, S, R> IntoPyGetterFunc<RefParam<S>, R> for F
where
F: Fn(&S, &VirtualMachine) -> R + 'static,
S: PyValue,
R: IntoPyObject,
{
fn into_getter(self) -> PyGetterFunc {
Box::new(move |vm, obj| {
let zelf = PyRef::<S>::try_from_object(vm, obj)?;
(self)(&zelf, vm).into_pyobject(vm)
})
}
}

pub trait IntoPySetterFunc<T, V> {
fn into_setter(self) -> PySetterFunc;
}

impl<F, T, V> IntoPySetterFunc<T, V> for F
impl<F, T, V> IntoPySetterFunc<OwnedParam<T>, V> for F
where
F: Fn(T, V, &VirtualMachine) -> PyResult<()> + 'static,
T: TryFromObject,
Expand All @@ -49,6 +63,21 @@ where
}
}

impl<F, S, V> IntoPySetterFunc<RefParam<S>, V> for F
where
F: Fn(&S, V, &VirtualMachine) -> PyResult<()> + 'static,
S: PyValue,
V: TryFromObject,
{
fn into_setter(self) -> PySetterFunc {
Box::new(move |vm, obj, value| {
let zelf = PyRef::<S>::try_from_object(vm, obj)?;
let value = V::try_from_object(vm, value)?;
(self)(&zelf, value, vm)
})
}
}

#[pyclass]
pub struct PyGetSet {
name: String,
Expand Down