forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheither.rs
More file actions
83 lines (77 loc) · 2.21 KB
/
either.rs
File metadata and controls
83 lines (77 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use crate::{
convert::ToPyObject, AsObject, PyObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine,
};
use std::borrow::Borrow;
pub enum Either<A, B> {
A(A),
B(B),
}
impl<A: Borrow<PyObject>, B: Borrow<PyObject>> Borrow<PyObject> for Either<A, B> {
#[inline(always)]
fn borrow(&self) -> &PyObject {
match self {
Self::A(a) => a.borrow(),
Self::B(b) => b.borrow(),
}
}
}
impl<A: AsRef<PyObject>, B: AsRef<PyObject>> AsRef<PyObject> for Either<A, B> {
#[inline(always)]
fn as_ref(&self) -> &PyObject {
match self {
Self::A(a) => a.as_ref(),
Self::B(b) => b.as_ref(),
}
}
}
impl<A: Into<PyObjectRef>, B: Into<PyObjectRef>> From<Either<A, B>> for PyObjectRef {
#[inline(always)]
fn from(value: Either<A, B>) -> Self {
match value {
Either::A(a) => a.into(),
Either::B(b) => b.into(),
}
}
}
impl<A: ToPyObject, B: ToPyObject> ToPyObject for Either<A, B> {
#[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),
}
}
}
/// This allows a builtin method to accept arguments that may be one of two
/// types, raising a `TypeError` if it is neither.
///
/// # Example
///
/// ```
/// use rustpython_vm::VirtualMachine;
/// use rustpython_vm::builtins::{PyStrRef, PyIntRef};
/// use rustpython_vm::function::Either;
///
/// fn do_something(arg: Either<PyIntRef, PyStrRef>, vm: &VirtualMachine) {
/// match arg {
/// Either::A(int)=> {
/// // do something with int
/// }
/// Either::B(string) => {
/// // do something with string
/// }
/// }
/// }
/// ```
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())))
}
}