Either accept any TryFromObject

This commit is contained in:
Aviv Palivoda
2019-10-17 17:00:07 +03:00
parent 70a22ab196
commit 16f8dbf87a
2 changed files with 7 additions and 32 deletions

View File

@@ -17,9 +17,7 @@ use super::objstr::{PyString, PyStringRef};
use super::objtuple::PyTupleRef;
use crate::function::OptionalArg;
use crate::pyhash;
use crate::pyobject::{
Either, PyIterable, PyObjectRef, PyRef, PyResult, PyValue, TryFromObject, TypeProtocol,
};
use crate::pyobject::{Either, PyIterable, PyObjectRef, PyResult, TryFromObject, TypeProtocol};
use crate::vm::VirtualMachine;
#[derive(Debug, Default, Clone)]
@@ -48,22 +46,6 @@ impl TryFromObject for PyByteInner {
}
}
impl<B: PyValue> TryFromObject for Either<PyByteInner, PyRef<B>> {
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
match PyByteInner::try_from_object(vm, obj.clone()) {
Ok(a) => Ok(Either::A(a)),
Err(_) => match obj.clone().downcast::<B>() {
Ok(b) => Ok(Either::B(b)),
Err(_) => Err(vm.new_type_error(format!(
"a bytes-like object or {} is required, not {}",
B::class(vm),
obj.class()
))),
},
}
}
}
#[derive(FromArgs)]
pub struct ByteInnerNewOptions {
#[pyarg(positional_only, optional = true)]

View File

@@ -1126,23 +1126,16 @@ impl<A: PyValue, B: PyValue> Either<PyRef<A>, PyRef<B>> {
/// }
/// }
/// ```
impl<A, B> TryFromObject for Either<PyRef<A>, PyRef<B>>
impl<A, B> TryFromObject for Either<A, B>
where
A: PyValue,
B: PyValue,
A: TryFromObject,
B: TryFromObject,
{
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
obj.downcast::<A>()
A::try_from_object(vm, obj.clone())
.map(Either::A)
.or_else(|obj| obj.clone().downcast::<B>().map(Either::B))
.map_err(|obj| {
vm.new_type_error(format!(
"must be {} or {}, not {}",
A::class(vm),
B::class(vm),
obj.class()
))
})
.or(B::try_from_object(vm, obj.clone()).map(Either::B))
.map_err(|_| vm.new_type_error(format!("unexpected type {}", obj.class())))
}
}