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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
#![warn(clippy::all)]
#![warn(clippy::pedantic)]
#![warn(clippy::cargo)]
#![cfg_attr(test, allow(clippy::non_ascii_literal))]
#![cfg_attr(test, allow(clippy::shadow_unrelated))]
#![allow(unknown_lints)]
#![warn(missing_copy_implementations)]
#![warn(missing_debug_implementations)]
#![warn(missing_docs)]
#![warn(rust_2018_idioms)]
#![warn(trivial_casts, trivial_numeric_casts)]
#![warn(unused_qualifications)]
#![warn(variant_size_differences)]
// Enable feature callouts in generated documentation:
// https://doc.rust-lang.org/beta/unstable-book/language-features/doc-cfg.html
//
// This approach is borrowed from tokio.
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(docsrs, feature(doc_alias))]

//! Compile time assertions.
//!
//! This crate contains compile time assertion macros used for maintaining safety
//! invariants or limiting platform support. If the assertion is false, a compiler
//! error is emitted.
//!
//! # Examples
//!
//! ```
//! # use core::num::NonZeroU8;
//! # #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
//! qed::const_assert!(usize::BITS >= u32::BITS);
//! qed::const_assert_eq!("Veni, vidi, vici".len(), 16);
//! qed::const_assert_ne!('∎'.len_utf8(), 1);
//! qed::const_assert_matches!(NonZeroU8::new(42), Some(nz) if nz.get() == 42);
//! ```
//!
//!
//! Assertion failures will result in a compile error:
//!
//! ```compile_fail
//! qed::const_assert!("non-empty string".is_empty());
//! ```

#![no_std]
#![doc(html_root_url = "https://docs.rs/qed/1.6.1")]

// Ensure code blocks in `README.md` compile
#[cfg(all(doctest, any(target_pointer_width = "32", target_pointer_width = "64")))]
#[doc = include_str!("../README.md")]
mod readme {}

#[doc(hidden)]
#[allow(missing_docs)]
pub mod imp;

/// Asserts that a boolean expression is true at compile time.
///
/// This will result in a compile time type error if the boolean expression does
/// not evaluate to true.
///
/// # Uses
///
/// Assertions are always checked in both debug and release builds and cannot be
/// disabled.
///
/// Unsafe code and [`as` casts][casts] may rely on `const_assert!` to enforce
/// runtime invariants that, if violated, could lead to unsafety.
///
/// [casts]: https://doc.rust-lang.org/nomicon/casts.html
///
/// Other use-cases of `const_assert!` include limiting supported platforms and
/// architectures.
///
/// # Examples
///
/// ```
/// // Assert at compile time that the target platform has at least 32-bit
/// // `usize`.
/// # #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
/// qed::const_assert!(usize::BITS >= u32::BITS);
/// ```
///
/// Assertion failures will result in a compile error:
///
/// ```compile_fail
/// qed::const_assert!("non-empty string".is_empty());
/// ```
#[macro_export]
macro_rules! const_assert {
    ($x:expr $(,)?) => {
        const _: () = ::core::assert!($x);
    };
}

/// Asserts that two expressions are equal to each other (using [`PartialEq`])
/// at compile time.
///
/// See also [`const_assert!`].
///
/// # Examples
///
/// ```
/// qed::const_assert_eq!("Veni, vidi, vici".len(), 16);
/// ```
///
/// The following fails to compile because the expressions are not equal:
///
/// ```compile_fail
/// qed::const_assert_eq!("Carpe diem".len(), 100);
/// ```
#[macro_export]
macro_rules! const_assert_eq {
    ($x:expr, $y:expr $(,)?) => {
        $crate::const_assert!($x == $y);
    };
}

/// Asserts that two expressions are not equal to each other (using
/// [`PartialEq`]) at compile time.
///
/// See also [`const_assert!`].
///
/// # Examples
///
/// ```
/// const END_OF_PROOF: char = '∎';
/// qed::const_assert_ne!(END_OF_PROOF.len_utf8(), 1);
/// ```
///
/// The following fails to compile because the expressions are equal:
///
/// ```compile_fail
/// const END_OF_PROOF: char = '∎';
/// qed::const_assert_ne!(END_OF_PROOF.len_utf8(), 3);
/// ```
#[macro_export]
macro_rules! const_assert_ne {
    ($x:expr, $y:expr $(,)?) => {
        $crate::const_assert!($x != $y);
    };
}

/// Asserts that an expression matches any of the given patterns at compile
/// time.
///
/// Like in a `match` expression, the pattern can be optionally followed by `if`
/// and a guard expression that has access to names bound by the pattern.
///
/// See also [`const_assert!`].
///
/// # Examples
///
/// ```
/// # use core::num::NonZeroU8;
/// qed::const_assert_matches!(NonZeroU8::new(0), None);
/// qed::const_assert_matches!(NonZeroU8::new(29), Some(_));
/// qed::const_assert_matches!(NonZeroU8::new(42), Some(nz) if nz.get() == 42);
/// ```
///
/// Assertion failures will result in a compile error:
///
/// ```compile_fail
/// qed::const_assert_matches!(b"maybe c string".last(), Some(&0));
/// ```
#[macro_export]
macro_rules! const_assert_matches {
    ($left:expr, $(|)? $( $pattern:pat_param )|+ $( if $guard: expr )? $(,)?) => {
        $crate::const_assert!(match $left {
            $( $pattern )|+ $( if $guard )? => true,
            _ => false,
        });
    };
}

/// Cast a [`u32`] to [`usize`] at runtime with a compile time assert that the
/// cast is lossless and will not overflow.
///
/// This macro emits a compile time assertion that `usize` has at least as many
/// bits as `u32`.
///
/// # Examples
///
/// ```
/// # #![cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
/// #[derive(Default)]
/// struct SymbolTable {
///     next: u32,
///     table: [&'static str; 32],
/// }
///
/// impl SymbolTable {
///     pub fn intern(&mut self, symbol: &'static str) -> u32 {
///         let id = self.next;
///         let idx = qed::lossless_cast_u32_to_usize!(id);
///         self.table[idx] = symbol;
///         self.next += 1;
///         id
///     }
/// }
///
/// let mut table = SymbolTable::default();
/// assert_eq!(table.intern("end of proof"), 0);
/// assert_eq!(table.intern("∎"), 1);
/// ```
///
/// This macro requires a `u32` as its argument:
///
/// ```compile_fail
/// qed::lossless_cast_u32_to_usize!(0_i32);
/// ```
#[macro_export]
macro_rules! lossless_cast_u32_to_usize {
    ($num:expr) => {{
        $crate::const_assert!(::core::primitive::usize::BITS >= ::core::primitive::u32::BITS);
        let num: ::core::primitive::u32 = $num;
        num as ::core::primitive::usize
    }};
}

/// Asserts that two types have the same size at compile time.
///
/// See also [`const_assert!`].
///
/// # Examples
///
/// ```
/// qed::const_assert_size_eq!(u8, i8);
/// qed::const_assert_size_eq!([u32; 4], i128);
/// qed::const_assert_size_eq!(&[u8], &str);
/// ```
///
/// The following fails to compile because the types have different sizes:
///
/// ```compile_fail
/// qed::const_assert_size_eq!(u8, u64);
/// ```
#[macro_export]
macro_rules! const_assert_size_eq {
    ($left:ty, $right:ty $(,)?) => {
        const _: () = {
            let _assert = ::core::mem::transmute::<$left, $right>;
        };
    };
}

/// Asserts that a byte slice does not contain any NUL (`\0`) bytes.
///
/// This macro emits a compile error if the given slice contains any NUL bytes,
/// including a NUL terminator.
///
/// # Examples
///
/// ```
/// const ARRAY_CLASS: &[u8] = b"Array";
/// qed::const_assert_bytes_has_no_nul!(ARRAY_CLASS);
/// ```
///
/// The following fails to compile because the byte slice contains a NUL byte:
///
/// ```compile_fail
/// const BYTES: &[u8] = b"abc\0xyz";
/// qed::const_assert_bytes_has_no_nul!(BYTES);
/// ```
///
/// The following fails to compile because the byte slice contains a NUL
/// terminator:
///
/// ```compile_fail
/// const CSTR: &[u8] = b"Q.E.D.\x00";
/// qed::const_assert_bytes_has_no_nul!(CSTR);
/// ```
#[macro_export]
macro_rules! const_assert_bytes_has_no_nul {
    ($bytes:expr $(,)?) => {{
        const _: &[::core::primitive::u8] = $bytes;

        $crate::const_assert!(!$crate::imp::contains_nul($bytes));
    }};
}

/// Construct a const [`CStr`] from the given bytes at compile time and assert
/// that the given bytes are a valid `CStr` (NUL terminated with no interior NUL
/// bytes).
///
/// [`CStr`]: core::ffi::CStr
///
/// This macro emits a compile error if the given slice contains any interior
/// NUL bytes or does not have a NUL terminator.
///
/// # Examples
///
/// ```
/// use core::ffi::CStr;
///
/// const ARRAY_CLASS: &[u8] = b"Array\0";
/// const ARRAY_CLASS_CSTR: &CStr = qed::const_cstr_from_bytes!(ARRAY_CLASS);
/// ```
///
/// The following fails to compile because the byte slice contains an interior
/// NUL byte:
///
/// ```compile_fail
/// use core::ffi::CStr;
///
/// const BYTES: &[u8] = b"abc\0xyz";
/// const BYTES_CSTR: &CStr = qed::const_cstr_from_bytes!(BYTES);
/// ```
///
/// The following fails to compile because the byte slice does not contain a NUL
/// terminator:
///
/// ```compile_fail
/// use core::ffi::CStr;
///
/// const BYTES: &[u8] = b"Q.E.D.";
/// const BYTES_CSTR: &CStr = qed::const_cstr_from_bytes!(BYTES);
/// ```
///
/// The following fails to compile because the empty byte slice is not a valid
/// `CStr`:
///
/// ```compile_fail
/// use core::ffi::CStr;
///
/// const EMPTY: &[u8] = b"";
/// const CSTR: &CStr = qed::const_cstr_from_bytes!(BYTES);
/// ```
#[macro_export]
macro_rules! const_cstr_from_bytes {
    ($bytes:expr $(,)?) => {{
        const _: &[::core::primitive::u8] = $bytes;

        $crate::const_assert!($crate::imp::is_cstr($bytes));

        // SAFETY
        //
        // The compile time assert above ensures the given bytes:
        //
        // - Are NUL terminated
        // - Do not have any interior NUL bytes
        //
        // which meets the safety criteria for `CStr::from_bytes_with_nul_unchecked`.
        //
        // https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html#method.from_bytes_with_nul_unchecked
        unsafe { ::core::ffi::CStr::from_bytes_with_nul_unchecked($bytes) }
    }};
}

/// Construct a const [`CStr`] from the given `str` at compile time and assert
/// that the given `str` bytes are a valid `CStr` (NUL terminated with no
/// interior NUL bytes).
///
/// [`CStr`]: core::ffi::CStr
///
/// This macro emits a compile error if the given `str` contains any interior
/// NUL bytes or does not have a NUL terminator.
///
/// # Examples
///
/// ```
/// use core::ffi::CStr;
///
/// const ARRAY_CLASS_CSTR: &CStr = qed::const_cstr_from_str!("Array\0");
/// ```
///
/// The following fails to compile because the `str` slice contains an interior
/// NUL byte:
///
/// ```compile_fail
/// use core::ffi::CStr;
///
/// const CSTR: &CStr = qed::const_cstr_from_str!("abc\0xyz");
/// ```
///
/// The following fails to compile because the `str` slice does not contain a NUL
/// terminator:
///
/// ```compile_fail
/// use core::ffi::CStr;
///
/// const CSTR: &CStr = qed::const_cstr_from_str!("Q.E.D.");
/// ```
///
/// The following fails to compile because the empty string is not a valid
/// `CStr`:
///
/// ```compile_fail
/// use core::ffi::CStr;
///
/// const CSTR: &CStr = qed::const_cstr_from_str!("");
/// ```
#[macro_export]
macro_rules! const_cstr_from_str {
    ($str:expr $(,)?) => {{
        const _: &::core::primitive::str = $str;

        $crate::const_cstr_from_bytes!($str.as_bytes())
    }};
}

#[cfg(test)]
mod tests {
    use ::core::ffi::CStr;
    use ::core::num::NonZeroU8;

    mod core {}
    mod std {}
    mod imp {}

    #[test]
    fn const_assert_no_warnings() {
        crate::const_assert!(true);
        crate::const_assert!(NonZeroU8::new(0).is_none());
        crate::const_assert!(NonZeroU8::new(29).is_some());
    }

    #[test]
    fn const_assert_eq_no_warnings() {
        crate::const_assert_eq!(i8::BITS, u8::BITS);
        crate::const_assert_eq!(u8::BITS, u8::BITS);
    }

    #[test]
    fn const_assert_eq_no_warnings_literals() {
        crate::const_assert_eq!(0, 0);
        crate::const_assert_eq!(29_i32, 29_i32);
    }

    #[test]
    fn const_assert_ne_no_warnings() {
        crate::const_assert_ne!(u32::BITS, u8::BITS);
    }

    #[test]
    fn const_assert_ne_no_warings_literals() {
        crate::const_assert_ne!(9, 99);
        crate::const_assert_ne!(0_i32, 29_i32);
    }

    #[test]
    fn const_assert_matches_no_warnings() {
        crate::const_assert_matches!(NonZeroU8::new(0), None);
        crate::const_assert_matches!(NonZeroU8::new(29), Some(_));
        crate::const_assert_matches!(NonZeroU8::new(29), Some(x) if x.get() == 29);
    }

    #[test]
    fn const_assert_matches_no_warnings_literals() {
        crate::const_assert_matches!(None::<i8>, None);
        crate::const_assert_matches!(Some(0_i8), Some(_));

        crate::const_assert_matches!(None::<i8>, None::<i8>);
        crate::const_assert_matches!(Some(0_i8), Some(0_i8));
    }

    #[test]
    #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
    fn lossless_cast_u32_usize_no_warnings() {
        let n = crate::lossless_cast_u32_to_usize!(29_u32);
        assert_eq!(n, 29_usize);
    }

    #[test]
    #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
    fn lossless_cast_u32_usize_no_warnings_const() {
        const N: usize = crate::lossless_cast_u32_to_usize!(29_u32);
        assert_eq!(N, 29_usize);
    }

    #[test]
    fn size_eq_reference_transmute_no_warnings() {
        crate::const_assert_size_eq!(&[u8], &str);
    }

    #[test]
    fn size_eq_pointer_transmute_no_warnings() {
        crate::const_assert_size_eq!(*mut u8, *const u8);
    }

    #[test]
    fn const_assert_bytes_has_no_nul_no_warnings() {
        crate::const_assert_bytes_has_no_nul!("abcdefg".as_bytes());
        crate::const_assert_bytes_has_no_nul!("".as_bytes());
    }

    #[test]
    fn const_cstr_from_bytes_no_warnings() {
        const CSTR: &CStr = crate::const_cstr_from_bytes!("Array\0".as_bytes());
        const EMPTY: &CStr = crate::const_cstr_from_bytes!("\0".as_bytes());
        assert_eq!(CSTR.to_bytes(), b"Array");
        assert!(EMPTY.to_bytes().is_empty());
    }

    #[test]
    fn const_cstr_from_str_no_warnings() {
        const CSTR: &CStr = crate::const_cstr_from_str!("Array\0");
        const EMPTY: &CStr = crate::const_cstr_from_str!("\0");
        assert_eq!(CSTR.to_bytes(), b"Array");
        assert!(EMPTY.to_bytes().is_empty());
    }

    #[test]
    fn const_assert_bytes_has_no_nul_none_shadow() {
        #[allow(dead_code)]
        #[allow(non_upper_case_globals)]
        const None: () = ();

        crate::const_assert_bytes_has_no_nul!("abcdefg".as_bytes());
    }

    #[test]
    fn const_assert_bytes_has_no_nul_hygiene() {
        #[allow(dead_code)]
        #[allow(non_camel_case_types)]
        struct u8 {}
        crate::const_assert_bytes_has_no_nul!("abcdefg".as_bytes());
    }

    #[test]
    fn const_assert_hygiene_assert() {
        #[allow(unused_macros)]
        macro_rules! assert {
            ($e:expr) => {
                panic!("::core::assert! was shadowed")
            };
        }
        crate::const_assert!("".is_empty());
    }

    #[test]
    fn const_assert_hygiene_bool() {
        #[allow(dead_code)]
        #[allow(non_camel_case_types)]
        struct bool {}
        crate::const_assert!("".is_empty());
    }

    #[test]
    fn const_assert_hygiene_usize() {
        #[allow(dead_code)]
        #[allow(non_camel_case_types)]
        struct usize {}
        crate::const_assert!("".is_empty());
    }

    #[test]
    fn lossless_u32_to_usize_hygiene_u32() {
        #[allow(dead_code)]
        #[allow(non_camel_case_types)]
        struct u32 {}
        let n = crate::lossless_cast_u32_to_usize!(29_u32);
        assert_eq!(n, 29_usize);
    }

    #[test]
    fn lossless_u32_to_usize_hygiene_usize() {
        #[allow(dead_code)]
        #[allow(non_camel_case_types)]
        struct usize {}
        let n = crate::lossless_cast_u32_to_usize!(29_u32);
        assert_eq!(n, 29_usize);
    }

    #[test]
    fn const_cstr_from_bytes_hygiene() {
        #[allow(dead_code)]
        #[allow(non_camel_case_types)]
        struct u8 {}
        const _: &CStr = crate::const_cstr_from_str!("Abc\0");
    }

    #[test]
    fn const_cstr_from_str_hygiene_str() {
        #[allow(dead_code)]
        #[allow(non_camel_case_types)]
        struct str {}
        const _: &CStr = crate::const_cstr_from_str!("Abc\0");
    }

    #[test]
    fn const_cstr_from_str_hygiene_u8() {
        #[allow(dead_code)]
        #[allow(non_camel_case_types)]
        struct u8 {}
        const _: &CStr = crate::const_cstr_from_str!("Abc\0");
    }

    #[test]
    fn const_cstr_from_str_hygiene_str_u8() {
        #[allow(dead_code)]
        #[allow(non_camel_case_types)]
        struct str {}
        #[allow(dead_code)]
        #[allow(non_camel_case_types)]
        struct u8 {}
        const _: &CStr = crate::const_cstr_from_str!("Abc\0");
    }
}