use crate::{
AsObject, PyObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine, convert::ToPyObject,
};
use core::borrow::Borrow;
pub enum Either<A, B> {
A(A),
B(B),
}
impl<A, B> Borrow<PyObject> for Either<A, B>
where
A: Borrow<PyObject>,
B: Borrow<PyObject>,
{
#[inline(always)]
fn borrow(&self) -> &PyObject {
match self {
Self::A(a) => a.borrow(),
Self::B(b) => b.borrow(),
}
}
}
impl<A, B> AsRef<PyObject> for Either<A, B>
where
A: AsRef<PyObject>,
B: AsRef<PyObject>,
{
#[inline(always)]
fn as_ref(&self) -> &PyObject {
match self {
Self::A(a) => a.as_ref(),
Self::B(b) => b.as_ref(),
}
}
}
impl<A, B> From<Either<A, B>> for PyObjectRef
where
A: Into<Self>,
B: Into<Self>,
{
#[inline(always)]
fn from(value: Either<A, B>) -> Self {
match value {
Either::A(a) => a.into(),
Either::B(b) => b.into(),
}
}
}
impl<A, B> ToPyObject for Either<A, B>
where
A: ToPyObject,
B: ToPyObject,
{
#[inline(always)]
fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef {
match self {
Self::A(a) => a.to_pyobject(vm),
Self::B(b) => b.to_pyobject(vm),
}
}
}
impl<A, B> TryFromObject for Either<A, B>
where
A: TryFromObject,
B: TryFromObject,
{
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
A::try_from_object(vm, obj.clone())
.map(Either::A)
.or_else(|_| B::try_from_object(vm, obj.clone()).map(Either::B))
.map_err(|_| vm.new_type_error(format!("unexpected type {}", obj.class())))
}
}