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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#![allow(missing_docs)]
use core::any::type_name;
use core::fmt::Debug;
use crate::{Interactive, InteractiveError, Methods, Result};
macro_rules! duck_type {
($vis:vis $AsTrait:ident ($method:ident) : $Trait:path | $Error:ident) => {
$vis trait $AsTrait {
fn $method(&self) -> Result<'_, &dyn $Trait>;
}
impl<T> $AsTrait for T {
default fn $method(&self) -> Result<'_, &dyn $Trait> {
Err(InteractiveError::$Error {
type_name: type_name::<T>(),
})
}
}
impl<T> $AsTrait for T
where
T: $Trait,
{
fn $method(&self) -> Result<'_, &dyn $Trait> {
Ok(self)
}
}
};
}
macro_rules! duck_type_mut {
($vis:vis $AsTrait:ident ($method:ident) : $Trait:path | $Error:ident) => {
$vis trait $AsTrait {
fn $method(&mut self) -> Result<'_, &mut dyn $Trait>;
}
impl<T> $AsTrait for T {
default fn $method(&mut self) -> Result<'_, &mut dyn $Trait> {
Err(InteractiveError::$Error {
type_name: type_name::<T>(),
})
}
}
impl<T> $AsTrait for T
where
T: $Trait,
{
fn $method(&mut self) -> Result<'_, &mut dyn $Trait> {
Ok(self)
}
}
};
}
duck_type!(pub AsInteractive(try_as_interactive): Interactive | InteractiveNotImplemented);
duck_type_mut!(pub AsInteractiveMut(try_as_interactive_mut): Interactive | InteractiveNotImplemented);
duck_type!(pub AsMethods(try_as_methods): Methods | MethodsNotImplemented);
duck_type_mut!(pub AsMethodsMut(try_as_methods_mut): Methods | MethodsNotImplemented);
duck_type!(pub AsDebug(try_as_debug): Debug | DebugNotImplemented);
macro_rules! deref_for_interactive {
($AsTrait:ident ($method:ident) : $Trait:path) => {
impl $AsTrait for &dyn Interactive {
fn $method(&self) -> Result<'_, &dyn $Trait> {
(&**self).$method()
}
}
impl $AsTrait for &mut dyn Interactive {
fn $method(&self) -> Result<'_, &dyn $Trait> {
(&**self).$method()
}
}
};
}
macro_rules! deref_for_interactive_mut {
($AsTrait:ident ($method:ident) : $Trait:path) => {
impl $AsTrait for &mut dyn Interactive {
fn $method(&mut self) -> Result<'_, &mut dyn $Trait> {
(&mut **self).$method()
}
}
};
}
deref_for_interactive!(AsMethods(try_as_methods): Methods);
deref_for_interactive_mut!(AsMethodsMut(try_as_methods_mut): Methods);
deref_for_interactive!(AsDebug(try_as_debug): Debug);
#[allow(missing_copy_implementations)]
#[derive(Debug)]
pub struct Unknown;