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
#![allow(clippy::cognitive_complexity)] // See arti#2556
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
#![warn(clippy::or_fun_call)]
28
#![deny(clippy::print_stderr)]
29
#![deny(clippy::print_stdout)]
30
#![warn(clippy::rc_buffer)]
31
#![deny(clippy::ref_option_ref)]
32
#![warn(clippy::semicolon_if_nothing_returned)]
33
#![warn(clippy::trait_duplication_in_bounds)]
34
#![deny(clippy::unchecked_time_subtraction)]
35
#![deny(clippy::unnecessary_wraps)]
36
#![warn(clippy::unseparated_literal_suffix)]
37
#![deny(clippy::unwrap_used)]
38
#![deny(clippy::mod_module_files)]
39
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
40
#![allow(clippy::uninlined_format_args)]
41
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
42
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
43
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
44
#![allow(clippy::needless_lifetimes)] // See arti#1765
45
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
46
#![allow(clippy::collapsible_if)] // See arti#2342
47
#![deny(clippy::unused_async)]
48
#![deny(clippy::string_slice)] // See arti#2571
49
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
50
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
51

            
52
// TODO: add to the list maintained by maint/add_warning once it's available on all crates
53
#![warn(unnameable_types)]
54

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

            
106
        impl From<$name> for $numtype {
107
27445960
            fn from(val: $name) -> $numtype { val.0 }
108
        }
109
        impl From<$numtype> for $name {
110
1577838
            fn from(num: $numtype) -> $name { $name(num) }
111
        }
112
        impl $name {
113
            $(
114
                $( #[$item_meta] )*
115
                pub const $id: $name = $name($num) ; )*
116
179292
            fn to_str(self) -> Option<&'static str> {
117
179292
                match self {
118
19473
                    $( $name::$id => Some(stringify!($id)), )*
119
948
                    _ => None,
120
                }
121
179292
            }
122
            /// Return true if this value is one that we recognize.
123
2
            $v fn is_recognized(self) -> bool {
124
2
                match self {
125
                    $( $name::$id  => true, )*
126
1
                    _ => false
127
                }
128
2
            }
129
            /// Try to convert this value from one of the recognized names.
130
12532791
            $v fn from_name(name: &str) -> Option<Self> {
131
12532791
                match name {
132
765831
                    $( stringify!($id) => Some($name::$id), )*
133
3688
                    _ => None
134
                }
135
12532791
            }
136
            /// Return the underlying integer that this value represents.
137
26952382
            fn get(self) -> $numtype {
138
26952382
                self.into()
139
26952382
            }
140
        }
141
        impl std::fmt::Display for $name {
142
179289
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143
179289
                match self.to_str() {
144
178342
                    Some(s) => write!(f, "{}", s),
145
947
                    None => write!(f, "{}", self.0),
146
                }
147
179289
            }
148
        }
149
        // `#[educe(Debug)]` could do this for us, but let's not deepen this macrology
150
        impl std::fmt::Debug for $name {
151
40226
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
152
40226
                write!(f, "{}({})", stringify!($name), self)
153
40226
            }
154
        }
155
    };
156

            
157
}