deb/control/
macros.rs

1// {{{ Copyright (c) Paul R. Tagliamonte <paultag@debian.org>, 2024
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19// THE SOFTWARE. }}}
20
21macro_rules! def_serde_traits_for {
22    ($type:ident) => {
23        #[cfg(feature = "serde")]
24        mod serde {
25            use super::$type;
26            use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error};
27
28            impl Serialize for $type {
29                fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
30                where
31                    S: Serializer,
32                {
33                    String::serialize(&self.to_string(), serializer)
34                }
35            }
36
37            impl<'de> Deserialize<'de> for $type {
38                fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
39                    let s = String::deserialize(d)?;
40                    s.parse().map_err(|e| D::Error::custom(format!("{:?}", e)))
41                }
42            }
43        }
44    };
45}
46pub(super) use def_serde_traits_for;
47
48#[cfg(test)]
49macro_rules! def_parse_test {
50    ($name:ident, $type:ty, $from:expr, $compare:expr) => {
51        #[test]
52        fn $name() {
53            let v: $type = $from.parse().unwrap();
54            assert_eq!($compare, v);
55        }
56    };
57}
58#[cfg(test)]
59pub(super) use def_parse_test;
60
61#[cfg(test)]
62macro_rules! def_failing_parse_test {
63    ($name:ident, $type:ty, $from:expr) => {
64        #[test]
65        fn $name() {
66            assert!($from.parse::<$type>().is_err());
67        }
68    };
69}
70#[cfg(test)]
71pub(super) use def_failing_parse_test;
72
73// vim: foldmethod=marker