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
//! A simple macro for creating newtype-structs (`MyType(X)`).
//!
//! ```
//! qnewtype! {
//!     #[meta]...
//!     [pub] type MyType: X;
//!
//!     ...
//! }
//! ```
//!
//! Corresponds to 
//!
//! ```
//! #[meta]...
//! [pub] struct MyType(X);
//!
//! impl From<X> for MyType {
//!     ...
//! }
//!
//! impl Into<X> for MyType {
//!     ...
//! }
//!
//! impl ::std::ops::Deref for MyType {
//!     type Target = X;
//!     ...
//! }
//!
//! impl ::std::ops::DerefMut for MyType {
//!     ...
//! }
//!
//! ...
//! ```
//!
//! If there's only statement, you can omit the semicolon.
//!
//! ```
//! qnewtype!([pub] type MyType: X);
//! ```
//!

#[macro_export] 
macro_rules! qnewtype {

    // pub single
    ($(#[$mmm:meta])* pub type $name:ident: $base:ty) => {
        qnewtype!($(#[$mmm])* pub type $name: $base;);
    };

    // non-pub single
    ($(#[$mmm:meta])* type $name:ident: $base:ty) => {
        qnewtype!($(#[$mmm])* type $name: $base;);
    };

    // pub
    ($($(#[$mmm:meta])* pub type $name:ident: $base:ty;)+) => {$(

        $(#[$mmm])*
        pub struct $name($base);

        qnewtype!(@impl_traits; $name; $base);

    )+};

    // non-pub
    ($($(#[$mmm:meta])* type $name:ident: $base:ty;)+) => {$(

        $(#[$mmm])*
        struct $name($base);

        qnewtype!(@impl_traits; $name; $base);

    )+};

    // (non-'derive'-able) trait implementations
    (@impl_traits; $name:ident; $base:ty) => {
        impl From<$base> for $name {
            fn from(base: $base) -> Self { $name(base) }
        }

        impl Into<$base> for $name {
            fn into(self) -> $base { self.0 }
        }

        impl ::std::ops::Deref for $name {
            type Target = $base;
            fn deref(&self) -> &Self::Target { &self.0 }
        }

        impl ::std::ops::DerefMut for $name {
            fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 }
        }

    };
}