-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathnewtype.rs
96 lines (82 loc) · 2.42 KB
/
newtype.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
//! Test implementing traits over newtype wrappers
use std::rc::Rc;
use std::sync::Arc;
mod inner {
use super::*;
use impl_tools::autoimpl;
#[autoimpl(for<T: trait + ?Sized> &T, &mut T, Box<T>, Rc<T>, Arc<T>)]
// Optionally, we can also implement Foo directly for these types:
// #[autoimpl(for<T: trait> NewFoo<T>, BoxFoo<T>)]
pub trait Foo {
fn is_true(&self) -> bool;
}
#[autoimpl(Deref<Target = T>, DerefMut using self.0)]
pub struct NewFoo<T: Foo>(T);
impl<T: Foo> NewFoo<T> {
pub fn new(foo: T) -> Self {
NewFoo(foo)
}
}
#[autoimpl(Deref<Target = dyn Foo + 'a> using self.0)]
pub struct FooRef<'a>(&'a dyn Foo);
impl<'a> FooRef<'a> {
pub fn new(foo: &'a dyn Foo) -> Self {
FooRef(foo)
}
}
#[autoimpl(Deref<Target = dyn Foo + 'a>, DerefMut using self.0)]
pub struct FooRefMut<'a>(&'a mut dyn Foo);
impl<'a> FooRefMut<'a> {
pub fn new(foo: &'a mut dyn Foo) -> Self {
FooRefMut(foo)
}
}
#[autoimpl(Deref<Target = T>, DerefMut using self.0)]
pub struct BoxFoo<T: Foo>(Box<T>);
impl<T: Foo> BoxFoo<T> {
pub fn new(foo: Box<T>) -> Self {
BoxFoo(foo)
}
}
#[autoimpl(Deref<Target = dyn Foo>, DerefMut using self.0)]
pub struct BoxDynFoo(Box<dyn Foo>);
impl BoxDynFoo {
pub fn new(foo: Box<dyn Foo>) -> Self {
BoxDynFoo(foo)
}
}
#[autoimpl(Deref<Target = dyn Foo>, DerefMut using self.0)]
pub struct RcDynFoo(Rc<dyn Foo>);
impl RcDynFoo {
pub fn new(foo: Rc<dyn Foo>) -> Self {
RcDynFoo(foo)
}
}
#[autoimpl(Deref<Target = dyn Foo>, DerefMut using self.0)]
pub struct ArcDynFoo(Arc<dyn Foo>);
impl ArcDynFoo {
pub fn new(foo: Arc<dyn Foo>) -> Self {
ArcDynFoo(foo)
}
}
}
#[derive(Clone, Copy, Default)]
pub struct V(bool);
impl inner::Foo for V {
fn is_true(&self) -> bool {
self.0
}
}
#[test]
fn newtype() {
use inner::*;
let mut v = V(true);
assert!(v.is_true());
assert!(NewFoo::new(v).is_true());
assert!(FooRef::new(&v).is_true());
assert!(FooRefMut::new(&mut v).is_true());
assert!(BoxFoo::new(Box::new(v)).is_true());
assert!(BoxDynFoo::new(Box::new(v)).is_true());
assert!(RcDynFoo::new(Rc::new(v)).is_true());
assert!(ArcDynFoo::new(Arc::new(v)).is_true());
}