aboutsummaryrefslogtreecommitdiff
path: root/rust/qemu-api/src/assertions.rs
blob: eb12e9499a720c1081a1688864dc7ec142eaa9e8 (plain)
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
// Copyright 2024, Red Hat Inc.
// Author(s): Paolo Bonzini <pbonzini@redhat.com>
// SPDX-License-Identifier: GPL-2.0-or-later

#![doc(hidden)]
//! This module provides macros to check the equality of types and
//! the type of `struct` fields.  This can be useful to ensure that
//! types match the expectations of C code.
//!
//! Documentation is hidden because it only exposes macros, which
//! are exported directly from `qemu_api`.

// Based on https://stackoverflow.com/questions/64251852/x/70978292#70978292
// (stackoverflow answers are released under MIT license).

#[doc(hidden)]
pub trait EqType {
    type Itself;
}

impl<T> EqType for T {
    type Itself = T;
}

/// Assert that two types are the same.
///
/// # Examples
///
/// ```
/// # use qemu_api::assert_same_type;
/// # use std::ops::Deref;
/// assert_same_type!(u32, u32);
/// assert_same_type!(<Box<u32> as Deref>::Target, u32);
/// ```
///
/// Different types will cause a compile failure
///
/// ```compile_fail
/// # use qemu_api::assert_same_type;
/// assert_same_type!(&Box<u32>, &u32);
/// ```
#[macro_export]
macro_rules! assert_same_type {
    ($t1:ty, $t2:ty) => {
        const _: () = {
            #[allow(unused)]
            fn assert_same_type(v: $t1) {
                fn types_must_be_equal<T, U>(_: T)
                where
                    T: $crate::assertions::EqType<Itself = U>,
                {
                }
                types_must_be_equal::<_, $t2>(v);
            }
        };
    };
}

/// Assert that a field of a struct has the given type.
///
/// # Examples
///
/// ```
/// # use qemu_api::assert_field_type;
/// pub struct A {
///     field1: u32,
/// }
///
/// assert_field_type!(A, field1, u32);
/// ```
///
/// Different types will cause a compile failure
///
/// ```compile_fail
/// # use qemu_api::assert_field_type;
/// # pub struct A { field1: u32 }
/// assert_field_type!(A, field1, i32);
/// ```
#[macro_export]
macro_rules! assert_field_type {
    ($t:ty, $i:tt, $ti:ty) => {
        const _: () = {
            #[allow(unused)]
            fn assert_field_type(v: $t) {
                fn types_must_be_equal<T, U>(_: T)
                where
                    T: $crate::assertions::EqType<Itself = U>,
                {
                }
                types_must_be_equal::<_, $ti>(v.$i);
            }
        };
    };

    ($t:ty, $i:tt, $ti:ty, num = $num:ident) => {
        const _: () = {
            #[allow(unused)]
            fn assert_field_type(v: $t) {
                fn types_must_be_equal<T, U>(_: T)
                where
                    T: $crate::assertions::EqType<Itself = U>,
                {
                }
                let index: usize = v.$num.try_into().unwrap();
                types_must_be_equal::<_, &$ti>(&v.$i[index]);
            }
        };
    };
}

/// Assert that an expression matches a pattern.  This can also be
/// useful to compare enums that do not implement `Eq`.
///
/// # Examples
///
/// ```
/// # use qemu_api::assert_match;
/// // JoinHandle does not implement `Eq`, therefore the result
/// // does not either.
/// let result: Result<std::thread::JoinHandle<()>, u32> = Err(42);
/// assert_match!(result, Err(42));
/// ```
#[macro_export]
macro_rules! assert_match {
    ($a:expr, $b:pat) => {
        assert!(
            match $a {
                $b => true,
                _ => false,
            },
            "{} = {:?} does not match {}",
            stringify!($a),
            $a,
            stringify!($b)
        );
    };
}

/// Assert at compile time that an expression is true.  This is similar
/// to `const { assert!(...); }` but it works outside functions, as well as
/// on versions of Rust before 1.79.
///
/// # Examples
///
/// ```
/// # use qemu_api::static_assert;
/// static_assert!("abc".len() == 3);
/// ```
///
/// ```compile_fail
/// # use qemu_api::static_assert;
/// static_assert!("abc".len() == 2); // does not compile
/// ```
#[macro_export]
macro_rules! static_assert {
    ($x:expr) => {
        const _: () = assert!($x);
    };
}