78
78
//! [`const_assert`]. If the expression evaluates to `false`, the file will fail
79
79
//! to compile. This is synonymous to [`static_assert` in C++][static_assert].
80
80
//!
81
+ //! As a [limitation](#limitations), a unique label is required if the macro is
82
+ //! used outside of a function.
83
+ //!
81
84
//! ```
82
85
//! # #[macro_use]
83
86
//! # extern crate static_assertions;
93
96
//! ```
94
97
//! # #[macro_use]
95
98
//! # extern crate static_assertions;
96
- //! # fn main() {
97
- //! const NUM: usize = 32;
98
- //! const_assert_eq!(NUM + NUM, 64);
99
- //!
100
99
//! const TWO: usize = 2;
101
- //! const_assert_eq!(TWO * TWO, TWO + TWO, 4);
102
- //! # }
100
+ //! const_assert_eq!(two; TWO * TWO, TWO + TWO, 4);
101
+ //!
102
+ //! // Produces a compilation failure:
103
+ //! // const_assert_eq!(two; TWO, TWO);
104
+ //!
105
+ //! fn main() {
106
+ //! const NUM: usize = 32;
107
+ //! const_assert_eq!(NUM + NUM, 64);
108
+ //! }
103
109
//! ```
104
110
//!
105
111
//! # Limitations
106
112
//!
107
- //! Due to implementation details, [`assert_eq_size`], [`const_assert`], and
108
- //! [`const_assert_eq`] can only be used from within the context of a function.
113
+ //! Due to implementation details, [`assert_eq_size`] can only be used from
114
+ //! within the context of a function.
115
+ //!
116
+ //! This is partially resolved in [`const_assert`] and [`const_assert_eq`] by
117
+ //! requiring a unique label when not inside a function.
109
118
//!
110
119
//! [crate]: https://crates.io/crates/static_assertions
111
120
//! [static_assert]: http://en.cppreference.com/w/cpp/language/static_assert
@@ -228,15 +237,12 @@ macro_rules! assert_eq_size_val {
228
237
/// ```
229
238
#[ macro_export]
230
239
macro_rules! const_assert {
231
- ( $cond: expr) => {
232
- // Causes overflow if condition is false
233
- let _ = [ ( ) ; 0 - ( !( $cond) as usize ) ] ;
234
- } ;
235
240
( $( $xs: expr) ,+) => {
236
- const_assert !( $( $xs) &&+) ;
241
+ let _ = [ ( ) ; 0 - ( !( $( $xs) &&+) as usize ) ] ;
237
242
} ;
238
- ( $( $xs: expr) ;+ $( ; ) * ) => {
239
- const_assert!( $( $xs) ,+) ;
243
+ ( $label: ident; $( $xs: expr) ,+) => {
244
+ #[ allow( dead_code, non_camel_case_types) ]
245
+ type $label = [ ( ) ; 0 - ( !( $( $xs) &&+) as usize ) ] ;
240
246
} ;
241
247
}
242
248
@@ -245,5 +251,8 @@ macro_rules! const_assert {
245
251
macro_rules! const_assert_eq {
246
252
( $x: expr, $( $xs: expr) ,+) => {
247
253
const_assert!( $( $x == $xs) ,+) ;
248
- }
254
+ } ;
255
+ ( $label: ident; $x: expr, $( $xs: expr) ,+) => {
256
+ const_assert!( $label; $( $x == $xs) ,+) ;
257
+ } ;
249
258
}
0 commit comments