1
#![cfg_attr(docsrs, feature(doc_cfg))]
2
#![doc = include_str!("../README.md")]
3
// @@ begin lint list maintained by maint/add_warning @@
4
#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5
#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6
#![warn(missing_docs)]
7
#![warn(noop_method_call)]
8
#![warn(unreachable_pub)]
9
#![warn(clippy::all)]
10
#![deny(clippy::await_holding_lock)]
11
#![deny(clippy::cargo_common_metadata)]
12
#![deny(clippy::cast_lossless)]
13
#![deny(clippy::checked_conversions)]
14
#![warn(clippy::cognitive_complexity)]
15
#![deny(clippy::debug_assert_with_mut_call)]
16
#![deny(clippy::exhaustive_enums)]
17
#![deny(clippy::exhaustive_structs)]
18
#![deny(clippy::expl_impl_clone_on_copy)]
19
#![deny(clippy::fallible_impl_from)]
20
#![deny(clippy::implicit_clone)]
21
#![deny(clippy::large_stack_arrays)]
22
#![warn(clippy::manual_ok_or)]
23
#![deny(clippy::missing_docs_in_private_items)]
24
#![warn(clippy::needless_borrow)]
25
#![warn(clippy::needless_pass_by_value)]
26
#![warn(clippy::option_option)]
27
#![deny(clippy::print_stderr)]
28
#![deny(clippy::print_stdout)]
29
#![warn(clippy::rc_buffer)]
30
#![deny(clippy::ref_option_ref)]
31
#![warn(clippy::semicolon_if_nothing_returned)]
32
#![warn(clippy::trait_duplication_in_bounds)]
33
#![deny(clippy::unchecked_time_subtraction)]
34
#![deny(clippy::unnecessary_wraps)]
35
#![warn(clippy::unseparated_literal_suffix)]
36
#![deny(clippy::unwrap_used)]
37
#![deny(clippy::mod_module_files)]
38
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
39
#![allow(clippy::uninlined_format_args)]
40
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
41
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
42
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
43
#![allow(clippy::needless_lifetimes)] // See arti#1765
44
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
45
#![allow(clippy::collapsible_if)] // See arti#2342
46
#![deny(clippy::unused_async)]
47
#![deny(clippy::string_slice)] // See arti#2571
48
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
49

            
50
/// Declare an integer type with some named elements.
51
///
52
/// This macro declares a struct that wraps an integer
53
/// type, and allows any integer type as a value.  Some values of this type
54
/// have names, and others do not, but they are all allowed.
55
///
56
/// This macro is suitable for protocol implementations that accept
57
/// any integer on the wire, and have definitions for some of those
58
/// integers.  For example, Tor cell commands are 8-bit integers, but
59
/// not every u8 is a currently recognized Tor command.
60
///
61
/// # Examples
62
/// ```
63
/// use caret::caret_int;
64
/// caret_int! {
65
///     pub struct FruitID(u8) {
66
///         AVOCADO = 7,
67
///         PERSIMMON = 8,
68
///         LONGAN = 99
69
///     }
70
/// }
71
///
72
/// // Known fruits work the way we would expect...
73
/// let a_num: u8 = FruitID::AVOCADO.into();
74
/// assert_eq!(a_num, 7);
75
/// let a_fruit: FruitID = 8.into();
76
/// assert_eq!(a_fruit, FruitID::PERSIMMON);
77
/// assert_eq!(format!("I'd like a {}", FruitID::PERSIMMON),
78
///            "I'd like a PERSIMMON");
79
///
80
/// // And we can construct unknown fruits, if we encounter any.
81
/// let weird_fruit: FruitID = 202.into();
82
/// assert_eq!(format!("I'd like a {}", weird_fruit),
83
///            "I'd like a 202");
84
/// ```
85
#[macro_export]
86
macro_rules! caret_int {
87
    {
88
       $(#[$meta:meta])*
89
       $v:vis struct $name:ident ( $numtype:ty ) {
90
           $(
91
               $(#[$item_meta:meta])*
92
               $id:ident = $num:literal
93
           ),*
94
           $(,)?
95
      }
96
    } => {
97
        #[derive(PartialEq,Eq,Copy,Clone)]
98
        $(#[$meta])*
99
        $v struct $name($numtype);
100

            
101
        impl From<$name> for $numtype {
102
2952201
            fn from(val: $name) -> $numtype { val.0 }
103
        }
104
        impl From<$numtype> for $name {
105
520275
            fn from(num: $numtype) -> $name { $name(num) }
106
        }
107
        impl $name {
108
            $(
109
                $( #[$item_meta] )*
110
                pub const $id: $name = $name($num) ; )*
111
80797
            fn to_str(self) -> Option<&'static str> {
112
80797
                match self {
113
12526
                    $( $name::$id => Some(stringify!($id)), )*
114
812
                    _ => None,
115
                }
116
80797
            }
117
            /// Return true if this value is one that we recognize.
118
4
            $v fn is_recognized(self) -> bool {
119
4
                match self {
120
                    $( $name::$id  => true, )*
121
2
                    _ => false
122
                }
123
4
            }
124
            /// Try to convert this value from one of the recognized names.
125
444938
            $v fn from_name(name: &str) -> Option<Self> {
126
444938
                match name {
127
4040
                    $( stringify!($id) => Some($name::$id), )*
128
1606
                    _ => None
129
                }
130
444938
            }
131
            /// Return the underlying integer that this value represents.
132
2491522
            fn get(self) -> $numtype {
133
2491522
                self.into()
134
2491522
            }
135
        }
136
        impl std::fmt::Display for $name {
137
80791
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138
80791
                match self.to_str() {
139
79981
                    Some(s) => write!(f, "{}", s),
140
810
                    None => write!(f, "{}", self.0),
141
                }
142
80791
            }
143
        }
144
        // `#[educe(Debug)]` could do this for us, but let's not deepen this macrology
145
        impl std::fmt::Debug for $name {
146
39472
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
147
39472
                write!(f, "{}({})", stringify!($name), self)
148
39472
            }
149
        }
150
    };
151

            
152
}