This repository has been archived by the owner on Feb 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.rs
157 lines (129 loc) · 4.61 KB
/
lib.rs
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#![feature(raw)]
use std::sync::atomic::{AtomicUsize, Ordering};
use std::any::TypeId;
use std::raw::TraitObject;
/// Helper trait to allow upcasting trait objects back to `&Plugin`, so they can be downcasted again.
pub trait PluginBase {
fn as_plugin(&self) -> &(Plugin + 'static);
}
impl<T: Plugin> PluginBase for T {
fn as_plugin(&self) -> &Plugin {
self
}
}
/// The core piece of the trait downcasting
pub trait Plugin: PluginBase + 'static {
fn __downcast_ref(&self, target: TypeId) -> Option<TraitObject> {
// Default implementation to downcast to the concrete type only
if target == ::std::any::TypeId::of::<Self>() {
Some(::std::raw::TraitObject {
data: self as *const _ as *mut (),
vtable: std::ptr::null_mut(),
})
} else {
None
}
}
}
impl Plugin {
/// Downcast to a given type, which could be either the concrete type or a trait type.
pub fn downcast_ref<T: ?Sized + 'static>(&self) -> Option<&T> {
unsafe {
if let Some(obj) = self.__downcast_ref(TypeId::of::<T>()) {
Some(*(&obj as *const TraitObject as *const &T))
} else {
None
}
}
}
}
/// Helper macro to declare which traits given type should be downcastable to.
#[macro_export]
macro_rules! declare_interfaces (
( $typ: ident, [ $( $iface: ident ),* ]) => {
impl Plugin for $typ {
fn __downcast_ref(&self, target: ::std::any::TypeId) -> Option<::std::raw::TraitObject> {
unsafe {
$(
if target == ::std::any::TypeId::of::<$iface>() {
return Some(::std::mem::transmute(self as &$iface));
}
)*
}
if target == ::std::any::TypeId::of::<$typ>() {
Some(::std::raw::TraitObject {
data: self as *const _ as *mut (),
vtable: std::ptr::null_mut(),
})
} else {
None
}
}
}
}
);
// Example code
// Interfaces
/// Generate a greeting message for the given name.
trait Greeter: Plugin {
fn greet(&self, name: &str) -> String;
}
/// This is a formal version, which uses a first name and the a name.
trait FormalGreeter: Plugin {
fn greet_formal(&self, first_name: &str, last_name: &str) -> String;
}
// Implementations
/// Simple greeter
pub struct SimpleGreeter(String);
impl Greeter for SimpleGreeter {
fn greet(&self, name: &str) -> String {
format!("{}, {}!", self.0, name)
}
}
impl FormalGreeter for SimpleGreeter {
fn greet_formal(&self, first_name: &str, last_name: &str) -> String {
format!("{}, {} {}!", self.0, first_name, last_name)
}
}
declare_interfaces!(SimpleGreeter, [Greeter, FormalGreeter]);
// Counting greeter
pub struct CountingGreeter(AtomicUsize);
impl FormalGreeter for CountingGreeter {
fn greet_formal(&self, first_name: &str, last_name: &str) -> String {
self.0.fetch_add(1, Ordering::Relaxed);
format!("Greetings, {} {}.", last_name, first_name)
}
}
declare_interfaces!(CountingGreeter, [FormalGreeter]);
/// Polymorphic function
pub fn rsvp(first_name: &str, last_name: &str, plugin: &Plugin) -> String {
if let Some(gt) = plugin.downcast_ref::<Greeter>() {
return gt.greet(first_name);
}
if let Some(gt) = plugin.downcast_ref::<FormalGreeter>() {
return gt.greet_formal(first_name, last_name);
}
"Hello?".to_string()
}
#[test]
fn test() {
let simple: &Plugin = &SimpleGreeter("Hi".to_string()) as &Plugin;
let formal: &Plugin = &CountingGreeter(Default::default()) as &Plugin;
assert_eq!("Hi, Andrew!", rsvp("Andrew", "Baker", simple));
assert_eq!("Greetings, Baker Andrew.", rsvp("Andrew", "Baker", formal));
// cast back to the concrete type
let simple = simple.downcast_ref::<SimpleGreeter>().unwrap();
assert_eq!(simple.0, "Hi");
// cast back to the concrete type
let formal = formal.downcast_ref::<CountingGreeter>().unwrap();
assert_eq!(1, formal.0.load(Ordering::Relaxed));
}
#[test]
fn cross_casting() {
let simple: &Plugin = &SimpleGreeter("Hi".to_string()) as &Plugin;
let simple = simple.downcast_ref::<Greeter>().unwrap();
assert_eq!("Hi, Andrew!", simple.greet("Andrew"));
// cross-casting via upcasting back to &Plugin
let simple = simple.as_plugin().downcast_ref::<FormalGreeter>().unwrap();
assert_eq!("Hi, Andrew Baker!", simple.greet_formal("Andrew", "Baker"));
}