devices/virtio/video/
macros.rs

1// Copyright 2020 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Macros that helps virtio video implementation.
6
7/// Implements TryFrom<data_model::Le32> for an enum that implements `enumn::N`.
8#[macro_export]
9macro_rules! impl_try_from_le32_for_enumn {
10    ($ty:ty, $name:literal) => {
11        impl TryFrom<Le32> for $ty {
12            type Error = ReadCmdError;
13
14            fn try_from(x: Le32) -> Result<Self, Self::Error> {
15                let v: u32 = x.into();
16                Self::n(v).ok_or_else(|| {
17                    error!(concat!("invalid ", $name, ": {}"), v);
18                    ReadCmdError::InvalidArgument
19                })
20            }
21        }
22    };
23}
24
25/// Implements `From` between two structs whose each field implements `From` each other.
26#[macro_export]
27macro_rules! impl_from_for_interconvertible_structs {
28    ($t1:ident, $t2:ident, $($v:ident),+) => {
29        impl_from_for_interconvertible_structs_core!($t1, $t2, $( $v ),+ );
30        impl_from_for_interconvertible_structs_core!($t2, $t1, $( $v ),+ );
31    };
32}
33
34macro_rules! impl_from_for_interconvertible_structs_core {
35    ($t1:ident, $t2:ident, $($v:ident),+) => {
36        impl From<$t1> for $t2 {
37            #[allow(clippy::needless_update)]
38            fn from(x :$t1) -> Self {
39                $t2 {
40                    $( $v: x.$v.into(), )+
41                    ..Default::default() // for paddings
42                }
43            }
44        }
45    };
46}