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
use std::fmt;
51
use std::ops::{RangeInclusive, RangeToInclusive};
52
use std::path::Path;
53
use std::time::Duration;
54

            
55
pub mod error_sources;
56
pub mod intern;
57
pub mod iter;
58
pub mod n_key_list;
59
pub mod n_key_set;
60
pub mod rand_hostname;
61
pub mod rangebounds;
62
pub mod retry;
63
pub mod test_rng;
64
pub mod token_bucket;
65

            
66
mod byte_qty;
67
pub use byte_qty::ByteQty;
68

            
69
pub use paste::paste;
70

            
71
use rand::Rng;
72

            
73
/// Sealed
74
mod sealed {
75
    /// Sealed
76
    pub trait Sealed {}
77
}
78
use sealed::Sealed;
79

            
80
// ----------------------------------------------------------------------
81

            
82
/// Function with the signature of `Debug::fmt` that just prints `".."`
83
///
84
/// ```
85
/// use educe::Educe;
86
/// use tor_basic_utils::skip_fmt;
87
///
88
/// #[derive(Educe, Default)]
89
/// #[educe(Debug)]
90
/// struct Wombat {
91
///     visible: usize,
92
///
93
///     #[educe(Debug(method = "skip_fmt"))]
94
///     invisible: [u8; 2],
95
/// }
96
///
97
/// assert_eq!( format!("{:?}", &Wombat::default()),
98
///             "Wombat { visible: 0, invisible: .. }" );
99
/// ```
100
15996
pub fn skip_fmt<T>(_: &T, f: &mut fmt::Formatter) -> fmt::Result {
101
    /// Inner function avoids code bloat due to generics
102
15996
    fn inner(f: &mut fmt::Formatter) -> fmt::Result {
103
15996
        write!(f, "..")
104
15996
    }
105
15996
    inner(f)
106
15996
}
107

            
108
// ----------------------------------------------------------------------
109

            
110
/// Formats an iterator as an object whose display implementation is a `separator`-separated string
111
/// of items from `iter`.
112
56
pub fn iter_join(
113
56
    separator: &str,
114
56
    iter: impl IntoIterator<Item: fmt::Display> + Clone,
115
56
) -> impl fmt::Display {
116
    // TODO MSRV 1.93: Replace with `std::fmt::from_fn()`?
117
    struct Fmt<'a, I: IntoIterator<Item: fmt::Display> + Clone> {
118
        /// Separates items in `iter`.
119
        separator: &'a str,
120
        /// Iterator to join.
121
        iter: I,
122
    }
123
    impl<'a, I: IntoIterator<Item: fmt::Display> + Clone> fmt::Display for Fmt<'a, I> {
124
56
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125
56
            let Self { separator, iter } = self;
126
56
            let mut iter = iter.clone().into_iter();
127
56
            if let Some(first) = iter.next() {
128
48
                write!(f, "{first}")?;
129
8
            }
130
56
            for x in iter {
131
28
                write!(f, "{separator}{x}")?;
132
            }
133
56
            Ok(())
134
56
        }
135
    }
136
56
    Fmt { separator, iter }
137
56
}
138

            
139
// ----------------------------------------------------------------------
140

            
141
/// Extension trait to provide `.strip_suffix_ignore_ascii_case()` etc.
142
// Using `.as_ref()` as a supertrait lets us make the method a provided one.
143
pub trait StrExt: AsRef<str> {
144
    /// Like `str.strip_suffix()` but ASCII-case-insensitive
145
    #[allow(clippy::string_slice)] // TODO
146
6784
    fn strip_suffix_ignore_ascii_case(&self, suffix: &str) -> Option<&str> {
147
6784
        let whole = self.as_ref();
148
6784
        let suffix_start = whole.len().checked_sub(suffix.len())?;
149
6715
        whole[suffix_start..]
150
6715
            .eq_ignore_ascii_case(suffix)
151
6715
            .then(|| &whole[..suffix_start])
152
6784
    }
153

            
154
    /// Like `str.ends_with()` but ASCII-case-insensitive
155
82
    fn ends_with_ignore_ascii_case(&self, suffix: &str) -> bool {
156
82
        self.strip_suffix_ignore_ascii_case(suffix).is_some()
157
82
    }
158
}
159
impl StrExt for str {}
160

            
161
// ----------------------------------------------------------------------
162

            
163
/// Extension trait to provide `.gen_range_checked()`
164
pub trait RngExt: Rng {
165
    /// Generate a random value in the given range.
166
    ///
167
    /// This function is optimised for the case that only a single sample is made from the given range. See also the [`Uniform`](rand::distr::uniform::Uniform)  distribution type which may be faster if sampling from the same range repeatedly.
168
    ///
169
    /// If the supplied range is empty, returns `None`.
170
    ///
171
    /// (This is a non-panicking version of [`rand::RngExt::random_range`].)
172
    ///
173
    /// ### Example
174
    ///
175
    /// ```
176
    /// use tor_basic_utils::RngExt as _;
177
    //
178
    // Fake plastic imitation tor_error, since that's actually higher up the stack
179
    /// # #[macro_use]
180
    /// # mod tor_error {
181
    /// #     #[derive(Debug)]
182
    /// #     pub struct Bug;
183
    /// #     pub fn internal() {} // makes `use` work
184
    /// # }
185
    /// # macro_rules! internal { { $x:expr } => { Bug } }
186
    //
187
    /// use tor_error::{Bug, internal};
188
    ///
189
    /// fn choose(slice: &[i32]) -> Result<i32, Bug> {
190
    ///     let index = rand::rng()
191
    ///         .gen_range_checked(0..slice.len())
192
    ///         .ok_or_else(|| internal!("empty slice"))?;
193
    ///     Ok(slice[index])
194
    /// }
195
    ///
196
    /// assert_eq!(choose(&[42]).unwrap(), 42);
197
    /// let _: Bug = choose(&[]).unwrap_err();
198
    /// ```
199
    //
200
    // TODO: We may someday wish to rename this function to random_range_checked,
201
    // since gen_range was renamed to random_range in rand 0.9.
202
    // Or we might decide to leave it alone.
203
442356
    fn gen_range_checked<T, R>(&mut self, range: R) -> Option<T>
204
442356
    where
205
442356
        T: rand::distr::uniform::SampleUniform,
206
442356
        R: rand::distr::uniform::SampleRange<T>,
207
    {
208
        #[allow(clippy::disallowed_methods)]
209
        {
210
            // Prove that rand::RngExt::random_range exists.  See arti.git/clippy.toml.
211
            let _ = |r: &mut rand::rngs::ThreadRng| rand::RngExt::random_range::<u8, _>(r, 0..10);
212
        }
213

            
214
442356
        if range.is_empty() {
215
            None
216
        } else {
217
            use rand::RngExt;
218
            #[allow(clippy::disallowed_methods)]
219
442356
            Some(self.random_range(range))
220
        }
221
442356
    }
222

            
223
    /// Generate a random value in the given upper-bounded-only range.
224
    ///
225
    /// For use with an inclusive upper-bounded-only range,
226
    /// with types that implement `GenRangeInfallible`
227
    /// (that necessarily then implement the appropriate `rand` traits).
228
    ///
229
    /// This function is optimised for the case that only a single sample is made from the given range. See also the [`Uniform`](rand::distr::uniform::Uniform)  distribution type which may be faster if sampling from the same range repeatedly.
230
    ///
231
    /// ### Example
232
    ///
233
    /// ```
234
    /// use std::time::Duration;
235
    /// use tor_basic_utils::RngExt as _;
236
    ///
237
    /// fn stochastic_sleep(max: Duration) {
238
    ///     let chosen_delay = rand::rng()
239
    ///         .gen_range_infallible(..=max);
240
    ///     std::thread::sleep(chosen_delay);
241
    /// }
242
    /// ```
243
313609
    fn gen_range_infallible<T>(&mut self, range: RangeToInclusive<T>) -> T
244
313609
    where
245
313609
        T: GenRangeInfallible,
246
    {
247
313609
        self.gen_range_checked(T::lower_bound()..=range.end)
248
313609
            .expect("GenRangeInfallible type with an empty lower_bound()..=T range")
249
313609
    }
250
}
251
impl<T: Rng> RngExt for T {}
252

            
253
/// Types that can be infallibly sampled using `gen_range_infallible`
254
///
255
/// In addition to the supertraits, the implementor of this trait must guarantee that:
256
///
257
/// `<Self as GenRangeInfallible>::lower_bound() ..= UPPER`
258
/// is a nonempty range for every value of `UPPER`.
259
//
260
// One might think that this trait is wrong because we might want to be able to
261
// implement gen_range_infallible for arguments other than RangeToInclusive<T>.
262
// However, double-ended ranges are inherently fallible because the actual values
263
// might be in the wrong order.  Non-inclusive ranges are fallible because the
264
// upper bound might be zero, unless a NonZero type is used, which seems like a further
265
// complication that we probably don't want to introduce here.  That leaves lower-bounded
266
// ranges, but those are very rare.
267
pub trait GenRangeInfallible: rand::distr::uniform::SampleUniform + Ord
268
where
269
    RangeInclusive<Self>: rand::distr::uniform::SampleRange<Self>,
270
{
271
    /// The usual lower bound, for converting a `RangeToInclusive` to a `RangeInclusive`
272
    ///
273
    /// Only makes sense with types with a sensible lower bound, such as zero.
274
    fn lower_bound() -> Self;
275
}
276

            
277
impl GenRangeInfallible for Duration {
278
426666
    fn lower_bound() -> Self {
279
426666
        Duration::ZERO
280
426666
    }
281
}
282

            
283
// ----------------------------------------------------------------------
284

            
285
/// Renaming of `Path::display` as `display_lossy`
286
pub trait PathExt: Sealed {
287
    /// Display this `Path` as an approximate string, for human consumption in messages
288
    ///
289
    /// Operating system paths cannot always be faithfully represented as Rust strings,
290
    /// because they might not be valid Unicode.
291
    ///
292
    /// This helper method provides a way to display a string for human users.
293
    /// **This may lose information** so should only be used for error messages etc.
294
    ///
295
    /// This method is exactly the same as [`std::path::Path::display`],
296
    /// but with a different and more discouraging name.
297
    fn display_lossy(&self) -> std::path::Display<'_>;
298
}
299
impl Sealed for Path {}
300
impl PathExt for Path {
301
    #[allow(clippy::disallowed_methods)]
302
3465
    fn display_lossy(&self) -> std::path::Display<'_> {
303
3465
        self.display()
304
3465
    }
305
}
306

            
307
// ----------------------------------------------------------------------
308

            
309
/// Define an "accessor trait", which describes structs that have fields of certain types
310
///
311
/// This can be useful if a large struct, living high up in the dependency graph,
312
/// contains fields that lower-lever crates want to be able to use without having
313
/// to copy the data about etc.
314
///
315
/// ```
316
/// // imagine this in the lower-level module
317
/// pub trait Supertrait {}
318
/// use tor_basic_utils::define_accessor_trait;
319
/// define_accessor_trait! {
320
///     pub trait View: Supertrait {
321
///         lorem: String,
322
///         ipsum: usize,
323
///         +
324
///         fn other_accessor(&self) -> bool;
325
///         // any other trait items can go here
326
///    }
327
/// }
328
///
329
/// fn test_view<V: View>(v: &V) {
330
///     assert_eq!(v.lorem(), "sit");
331
///     assert_eq!(v.ipsum(), &42);
332
/// }
333
///
334
/// // imagine this in the higher-level module
335
/// use derive_more::AsRef;
336
/// #[derive(AsRef)]
337
/// struct Everything {
338
///     #[as_ref] lorem: String,
339
///     #[as_ref] ipsum: usize,
340
///     dolor: Vec<()>,
341
/// }
342
/// impl Supertrait for Everything { }
343
/// impl View for Everything {
344
///     fn other_accessor(&self) -> bool { false }
345
/// }
346
///
347
/// let everything = Everything {
348
///     lorem: "sit".into(),
349
///     ipsum: 42,
350
///     dolor: vec![()],
351
/// };
352
///
353
/// test_view(&everything);
354
/// ```
355
///
356
/// ### Generated code
357
///
358
/// ```
359
/// # pub trait Supertrait { }
360
/// pub trait View: AsRef<String> + AsRef<usize> + Supertrait {
361
///     fn lorem(&self) -> &String { self.as_ref() }
362
///     fn ipsum(&self) -> &usize { self.as_ref() }
363
/// }
364
/// ```
365
#[macro_export]
366
macro_rules! define_accessor_trait {
367
    {
368
        $( #[ $attr:meta ])*
369
        $vis:vis trait $Trait:ident $( : $( $Super:path )* )? {
370
            $( $accessor:ident: $type:ty, )*
371
            $( + $( $rest:tt )* )?
372
        }
373
    } => {
374
        $( #[ $attr ])*
375
        $vis trait $Trait: $( core::convert::AsRef<$type> + )* $( $( $Super + )* )?
376
        {
377
            $(
378
                /// Access the field
379
680
                fn $accessor(&self) -> &$type { core::convert::AsRef::as_ref(self) }
380
            )*
381
            $(
382
                $( $rest )*
383
            )?
384
        }
385
    }
386
}
387

            
388
// ----------------------------------------------------------------------
389

            
390
/// Helper for assisting with macro "argument" defaulting
391
///
392
/// ```ignore
393
/// macro_first_nonempty!{ [ something ]  ... }  // =>   something
394
/// macro_first_nonempty!{ [ ], [ other ] ... }  // =>   other
395
/// // etc.
396
/// ```
397
///
398
/// ### Usage note
399
///
400
/// It is generally possible to avoid use of `macro_first_nonempty`, at the cost of
401
/// providing many alternative matcher patterns.  Using `macro_first_nonempty` can make
402
/// it possible to provide a single pattern with the optional items in `$( )?`.
403
///
404
/// This is valuable because a single pattern with some optional items
405
/// makes much better documentation than several patterns which the reader must compare
406
/// by eye - and it also simplifies the implementation.
407
///
408
/// `macro_first_nonempty` takes each of its possible expansions in `[ ]` and returns
409
/// the first nonempty one.
410
#[macro_export]
411
macro_rules! macro_first_nonempty {
412
    { [ $($yes:tt)+ ] $($rhs:tt)* } => { $($yes)* };
413
    { [ ]$(,)? [ $($otherwise:tt)* ] $($rhs:tt)* } => {
414
        $crate::macro_first_nonempty!{ [ $($otherwise)* ] $($rhs)* }
415
    };
416
}
417

            
418
/// Helper for assisting with defining macros that need to expand
419
/// conditionally when an argument is empty.
420
///
421
/// ```ignore
422
/// if_empty!{ {   } { x } { y } } // => x
423
/// if_empty!{ { z } { x } { y } } // => y
424
/// // etc.
425
/// ```
426
///
427
/// Note: The `{ y }` argument may be omitted.
428
#[macro_export]
429
macro_rules! if_empty {
430
    { { }                  { $($x:tt)* } $({ $($y:tt)* })? } => { $($x)* };
431
    { { $($nonempty:tt)+ } { $($x:tt)* } $({ $($y:tt)* })? } => { $($($y)*)? };
432
}
433

            
434
// ----------------------------------------------------------------------
435

            
436
/// Define `Debug` to print as hex
437
///
438
/// # Usage
439
///
440
/// ```ignore
441
/// impl_debug_hex! { $type }
442
/// impl_debug_hex! { $type . $field_accessor }
443
/// impl_debug_hex! { $type , $accessor_fn }
444
/// ```
445
///
446
/// By default, this expects `$type` to implement `AsRef<[u8]>`.
447
///
448
/// Or, you can supply a series of tokens `$field_accessor`,
449
/// which will be used like this: `self.$field_accessor.as_ref()`
450
/// to get a `&[u8]`.
451
///
452
/// Or, you can supply `$accessor: fn(&$type) -> &[u8]`.
453
///
454
/// # Examples
455
///
456
/// ```
457
/// use tor_basic_utils::impl_debug_hex;
458
/// #[derive(Default)]
459
/// struct FourBytes([u8; 4]);
460
/// impl AsRef<[u8]> for FourBytes { fn as_ref(&self) -> &[u8] { &self.0 } }
461
/// impl_debug_hex! { FourBytes }
462
///
463
/// assert_eq!(
464
///     format!("{:?}", FourBytes::default()),
465
///     "FourBytes(00000000)",
466
/// );
467
/// ```
468
///
469
/// ```
470
/// use tor_basic_utils::impl_debug_hex;
471
/// #[derive(Default)]
472
/// struct FourBytes([u8; 4]);
473
/// impl_debug_hex! { FourBytes .0 }
474
///
475
/// assert_eq!(
476
///     format!("{:?}", FourBytes::default()),
477
///     "FourBytes(00000000)",
478
/// );
479
/// ```
480
///
481
/// ```
482
/// use tor_basic_utils::impl_debug_hex;
483
/// struct FourBytes([u8; 4]);
484
/// impl_debug_hex! { FourBytes, |self_| &self_.0 }
485
///
486
/// assert_eq!(
487
///     format!("{:?}", FourBytes([1,2,3,4])),
488
///     "FourBytes(01020304)",
489
/// )
490
/// ```
491
#[macro_export]
492
macro_rules! impl_debug_hex {
493
    { $type:ty $(,)? } => {
494
        $crate::impl_debug_hex! { $type, |self_| <$type as AsRef<[u8]>>::as_ref(&self_) }
495
    };
496
    { $type:ident . $($accessor:tt)+ } => {
497
557
        $crate::impl_debug_hex! { $type, |self_| self_ . $($accessor)* .as_ref() }
498
    };
499
    { $type:ty, $obtain:expr $(,)? } => {
500
        impl std::fmt::Debug for $type {
501
557
            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
502
                use std::fmt::Write;
503
557
                let obtain: fn(&$type) -> &[u8] = $obtain;
504
557
                let bytes: &[u8] = obtain(self);
505
557
                write!(f, "{}(", stringify!($type))?;
506
18656
                for b in bytes {
507
18656
                    write!(f, "{:02x}", b)?;
508
                }
509
557
                write!(f, ")")?;
510
557
                Ok(())
511
557
            }
512
        }
513
    };
514
}
515

            
516
// ----------------------------------------------------------------------
517

            
518
/// Helper for defining a struct which can be (de)serialized several ways, including "natively"
519
///
520
/// Ideally we would have
521
/// ```rust ignore
522
/// #[derive(Deserialize)]
523
/// #[serde(try_from=Possibilities)]
524
/// struct Main { /* principal definition */ }
525
///
526
/// #[derive(Deserialize)]
527
/// #[serde(untagged)]
528
/// enum Possibilities { Main(Main), Other(OtherRepr) }
529
///
530
/// #[derive(Deserialize)]
531
/// struct OtherRepr { /* other representation we still want to read */ }
532
///
533
/// impl TryFrom<Possibilities> for Main { /* ... */ }
534
/// ```
535
///
536
/// But the impl for `Possibilities` ends up honouring the `try_from` on `Main`
537
/// so is recursive.
538
///
539
/// We solve that (ab)using serde's remote feature,
540
/// on a second copy of the struct definition.
541
///
542
/// See the Example for instructions.
543
/// It is important to **add test cases**
544
/// for all the representations you expect to parse and serialise,
545
/// since there are easy-to-write bugs,
546
/// for example omitting some of the necessary attributes.
547
///
548
/// # Generated output:
549
///
550
///  * The original struct definition, unmodified
551
///  * `#[derive(Serialize, Deserialize)] struct $main_Raw { }`
552
///
553
/// The `$main_Raw` struct ought not normally be to constructed anywhere,
554
/// and *isn't* convertible to or from the near-identical `$main` struct.
555
/// It exists only as a thing to feed to the serde remove derive,
556
/// and name in `with=`.
557
///
558
/// # Example
559
///
560
/// ```
561
/// use serde::{Deserialize, Serialize};
562
/// use tor_basic_utils::derive_serde_raw;
563
///
564
/// derive_serde_raw! {
565
///     #[derive(Deserialize, Serialize, Default, Clone, Debug)]
566
///     #[serde(try_from="BridgeConfigBuilderSerde", into="BridgeConfigBuilderSerde")]
567
///     pub struct BridgeConfigBuilder = "BridgeConfigBuilder" {
568
///         transport: Option<String>,
569
///         //...
570
///     }
571
/// }
572
///
573
/// #[derive(Serialize,Deserialize)]
574
/// #[serde(untagged)]
575
/// enum BridgeConfigBuilderSerde {
576
///     BridgeLine(String),
577
///     Dict(#[serde(with="BridgeConfigBuilder_Raw")] BridgeConfigBuilder),
578
/// }
579
///
580
/// impl TryFrom<BridgeConfigBuilderSerde> for BridgeConfigBuilder { //...
581
/// #    type Error = std::io::Error;
582
/// #    fn try_from(_: BridgeConfigBuilderSerde) -> Result<Self, Self::Error> { todo!() } }
583
/// impl From<BridgeConfigBuilder> for BridgeConfigBuilderSerde { //...
584
/// #    fn from(_: BridgeConfigBuilder) -> BridgeConfigBuilderSerde { todo!() } }
585
/// ```
586
#[macro_export]
587
macro_rules! derive_serde_raw { {
588
    $( #[ $($attrs:meta)* ] )*
589
    $vis:vis struct $main:ident=$main_s:literal
590
    $($body:tt)*
591
} => {
592
    $(#[ $($attrs)* ])*
593
    $vis struct $main
594
    $($body)*
595

            
596
    $crate::paste! {
597
        #[allow(non_camel_case_types)]
598
        #[derive(Serialize, Deserialize)]
599
        #[serde(remote=$main_s)]
600
        struct [< $main _Raw >]
601
        $($body)*
602
    }
603
} }
604

            
605
// ----------------------------------------------------------------------
606

            
607
/// Give a compile time error if TYPE implements TRAIT
608
///
609
/// Includes the identifier $rule in the error message, to help the user diagnose
610
/// the problem (unlike the similar macro in `static_assertions`.
611
///
612
/// Supports generics (also, unlike the one in static_assertions`).
613
///
614
/// # Input syntaxes
615
///
616
/// ```
617
// With a fair amount of trickery, we can get the compiler to (mostly) syntax-check this!
618
/// # #![allow(nonstandard_style)]
619
/// # use tor_basic_utils::assert_not_impl;
620
/// # use std::cell::Cell;
621
/// # type TYPE = Cell<u32>;
622
/// # use Sync as TRAIT;
623
/// assert_not_impl! { [RULE_IDENTIFIER] TYPE: TRAIT }
624
//
625
// We can't get the compiler to syntax check this one:
626
// error[E0207]: the type parameter `TYPE_GENERICS` is not constrained ...
627
// Instead, we hide it from the compiler and write a very similar test, hidden from the reader.
628
/// # let _ = r#"
629
/// assert_not_impl! { [RULE_IDENTIFIER <TYPE_GENERICS>] TYPE: TRAIT }
630
/// # "#;
631
/// # assert_not_impl! { [RULE_IDENTIFIER <TYPE_GENERICS>] Cell<TYPE_GENERICS>: TRAIT }
632
/// ```
633
///
634
///  * `RULE_IDENTIFIER` is an arbitrary identifier; it will appear in the error message.
635
///    (There is no way to include arbitrary explanatory text.)
636
///  * `TYPE_GENERICS` are generic bindings needed for `TYPE`.
637
///    (Generics on the trait are not supported.)
638
///
639
/// # Examples
640
///
641
/// ```
642
/// use std::cell::Cell;
643
/// use tor_basic_utils::assert_not_impl;
644
///
645
/// // No error will occur; Cell is not Sync
646
/// assert_not_impl! {
647
///     [cell_must_not_be_sync] Cell<u32>: Sync
648
/// }
649
/// assert_not_impl! {
650
///     [cell_must_not_be_sync <T: Copy>]
651
///     Cell<T>: Sync
652
/// }
653
/// ```
654
///
655
/// ```compile_fail
656
/// // Compile-time error _is_ given; String implements Clone.
657
/// assert_not_impl! {
658
///     [clone_is_forbidden_here] String: Clone
659
/// }
660
/// ```
661
#[macro_export]
662
macro_rules! assert_not_impl {
663
    // we can't match the trailing > of generics - only the leading <
664
    {[$rule:ident $( < $($gens:tt)* )? ] $t:ty : $trait:path } => {
665
        const _ : () = {
666
            #[allow(dead_code, non_camel_case_types)]
667
            trait $rule<X> {
668
                fn item();
669
            }
670
            impl$( < $($gens)* )? $rule<()> for $t {
671
                fn item() {
672
                    let _ = Self::item;
673
                }
674
            }
675
            struct Invalid;
676
            impl<T : $trait + ?Sized> $rule<Invalid> for T { fn item() {} }
677
        };
678
    }
679
}
680

            
681
// ----------------------------------------------------------------------
682

            
683
/// Asserts that the type of the expression implements the given trait.
684
///
685
/// Example:
686
///
687
/// ```
688
/// # use tor_basic_utils::assert_val_impl_trait;
689
/// let x: u32 = 0;
690
/// assert_val_impl_trait!(x, Clone);
691
/// ```
692
#[macro_export]
693
macro_rules! assert_val_impl_trait {
694
    ($check:expr, $trait:path $(,)?) => {{
695
9462
        fn ensure_trait<T: $trait>(_s: &T) {}
696
        ensure_trait(&$check);
697
    }};
698
}
699

            
700
// ----------------------------------------------------------------------
701

            
702
#[cfg(test)]
703
mod test {
704
    // @@ begin test lint list maintained by maint/add_warning @@
705
    #![allow(clippy::bool_assert_comparison)]
706
    #![allow(clippy::clone_on_copy)]
707
    #![allow(clippy::dbg_macro)]
708
    #![allow(clippy::mixed_attributes_style)]
709
    #![allow(clippy::print_stderr)]
710
    #![allow(clippy::print_stdout)]
711
    #![allow(clippy::single_char_pattern)]
712
    #![allow(clippy::unwrap_used)]
713
    #![allow(clippy::unchecked_time_subtraction)]
714
    #![allow(clippy::useless_vec)]
715
    #![allow(clippy::needless_pass_by_value)]
716
    #![allow(clippy::string_slice)] // See arti#2571
717
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
718
    use super::*;
719

            
720
    #[test]
721
    fn test_strip_suffix_ignore_ascii_case() {
722
        assert_eq!(
723
            "hi there".strip_suffix_ignore_ascii_case("THERE"),
724
            Some("hi ")
725
        );
726
        assert_eq!("hi here".strip_suffix_ignore_ascii_case("THERE"), None);
727
        assert_eq!("THERE".strip_suffix_ignore_ascii_case("there"), Some(""));
728
        assert_eq!("hi".strip_suffix_ignore_ascii_case("THERE"), None);
729
    }
730
}