try-specialize 0.1.2

Zero-cost specialization in generic context on stable Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
use core::fmt::{Debug, Display, Write as FmtWrite};
use core::future::{Future, IntoFuture};
use core::hash::Hash;
use core::ops::Deref;
use core::panic::{RefUnwindSafe, UnwindSafe};
use core::str::FromStr;
#[cfg(feature = "std")]
use std::io::{Read as IoRead, Write as IoWrite};

use crate::LifetimeFree;

/// Generates a function which returns `true` if the given type implements
/// specified trait. Note that all the lifetimes are erased and not accounted
/// for.
///
/// Library tests ensure that the `impls_trait` checks are performed at compile
/// time and are fully optimized with no runtime cost at `opt-level >= 1`. Note
/// that the release profile uses `opt-level = 3` by default.
///
/// Custom attributes:
/// - `#[auto_doc]` attribute enables automatic documentation generation for the
///   generated function including the `Reliability` documentation section.
/// - `#[+reliability_doc]` attribute enables automatic generation of
///   `Reliability` documentation section for the generated function.
///
/// # Reliability
///
/// While it is unlikely, there is still a possibility that the functions
/// generated by this macro may return false negatives in future Rust versions.
///
/// The correctness of the results returned by the functions depends on
/// the following:
/// - Documented behavior that if `T` implements `Eq`, two `Rc`s that point to
///   the same allocation are always equal:
///   <https://doc.rust-lang.org/1.82.0/std/rc/struct.Rc.html#method.eq>.
/// - Undocumented behavior that the `Rc::partial_eq` implementation for `T: Eq`
///   will not use `PartialEq::eq` if both `Rc`s point to the same memory
///   location.
/// - The assumption that the undocumented short-circuit behavior described
///   above will be retained for optimization purposes.
///
/// There is no formal guarantee that the undocumented behavior described above
/// will be retained. If the implementation changes in a future Rust version,
/// the function may return a false negative, that is, it may return `false`,
/// even though `T` implements the trait. However, the implementation guarantees
/// that a false positive result is impossible, i.e., the function will never
/// return true if `T` does not implement the trait in any future Rust version.
///
/// Details:
/// - <https://internals.rust-lang.org/t/rc-uses-visibly-behavior-changing-specialization-is-that-okay/16173/6>,
/// - <https://users.rust-lang.org/t/hack-to-specialize-w-write-for-vec-u8/100366>,
/// - <https://doc.rust-lang.org/1.82.0/std/rc/struct.Rc.html#method.eq>,
/// - <https://github.com/rust-lang/rust/issues/42655>.
///
/// # Examples
///
/// ```rust
/// # #[cfg(all(feature = "alloc", feature = "unreliable"))] {
/// use try_specialize::define_impls_trait_ignore_lt_fn;
///
/// define_impls_trait_ignore_lt_fn!(
///     #[auto_doc] pub impls_into_iterator_u32: IntoIterator<Item = u32>
/// );
/// assert!(impls_into_iterator_u32::<[u32; 4]>());
/// assert!(impls_into_iterator_u32::<Vec<u32>>());
/// assert!(!impls_into_iterator_u32::<Vec<i32>>());
/// # }
/// ```
///
/// ```rust
/// # #[cfg(all(feature = "alloc", feature = "unreliable"))] {
/// use try_specialize::define_impls_trait_ignore_lt_fn;
///
/// define_impls_trait_ignore_lt_fn!(
///     pub impls_copy_eq_ord: Copy + Eq + Ord
/// );
/// assert!(impls_copy_eq_ord::<u32>());
/// assert!(impls_copy_eq_ord::<[u32; 4]>());
/// assert!(!impls_copy_eq_ord::<Vec<u32>>());
/// # }
/// ```
///
/// ```rust
/// # #[cfg(all(feature = "alloc", feature = "unreliable"))] {
/// use try_specialize::define_impls_trait_ignore_lt_fn;
///
/// pub trait IsRef {}
/// impl<T> IsRef for &T where T: ?Sized {}
///
/// pub trait IsMutRef {}
/// impl<T> IsMutRef for &mut T where T: ?Sized {}
///
/// pub trait IsBox {}
/// impl<T> IsBox for Box<T> where T: ?Sized {}
///
/// define_impls_trait_ignore_lt_fn!(
///     #[+reliability_doc]
///     /// Returns `true` if the given type is a const reference like `&T`.
///     pub is_ref: IsRef
/// );
///
/// define_impls_trait_ignore_lt_fn!(
///     #[+reliability_doc]
///     /// Returns `true` if the given type is a mutable reference like
///     /// `&mut T`.
///     pub is_mut_ref: IsMutRef
/// );
///
/// define_impls_trait_ignore_lt_fn!(
///     #[+reliability_doc]
///     /// Returns `true` if the given type is a `Box<T>`-type.
///     pub is_box: IsBox
/// );
///
/// assert!(!is_ref::<u32>());
/// assert!(!is_ref::<[u32; 4]>());
/// assert!(!is_ref::<Vec<u32>>());
/// assert!(is_ref::<&u32>());
/// assert!(is_ref::<&[u32]>());
/// assert!(!is_ref::<&mut u32>());
///
/// assert!(!is_mut_ref::<u32>());
/// assert!(!is_mut_ref::<&u32>());
/// assert!(is_mut_ref::<&mut u32>());
///
/// assert!(!is_box::<u32>());
/// assert!(!is_box::<&u32>());
/// assert!(!is_box::<&mut u32>());
/// assert!(is_box::<Box<u32>>());
/// assert!(is_box::<Box<(char, u32, i128)>>());
/// # }
/// ```
#[macro_export]
macro_rules! define_impls_trait_ignore_lt_fn {
    ( #[auto_doc] $( #[$meta:meta] )* $vis:vis $fn_name:ident: $( $bounds:tt )+ ) => {
        define_impls_trait_ignore_lt_fn! {
            #[doc = "Returns `true` if the given type implements `"]
            #[doc = stringify!( $( $bounds )+ )]
            #[doc = "`."]
            ///
            /// Use [`define_impls_trait_ignore_lt_fn`] macro to generate other
            /// trait implementation check functions.
            ///
            /// Library tests ensure that the `impls_trait` checks are performed
            /// at compile time and fully optimized with no runtime cost at
            /// `opt-level >= 1`. Note that the release profile uses
            /// `opt-level = 3` by default.
            ///
            /// [`define_impls_trait_ignore_lt_fn`]: https://docs.rs/try-specialize/latest/try_specialize/macro.define_impls_trait_ignore_lt_fn.html
            ///
            #[+reliability_doc]
            $( #[$meta] )*
            $vis $fn_name: $( $bounds )+
        }
    };
    (
        $( #[$meta1:meta] )* #[+reliability_doc] $( #[$meta2:meta] )*
        $vis:vis $fn_name:ident: $( $bounds:tt )+
    ) => {
        define_impls_trait_ignore_lt_fn! {
            $( #[$meta1] )*
            ///
            /// # Reliability
            ///
            /// While it is unlikely, there is still a possibility that this
            /// function may return false negatives in future Rust versions.
            ///
            /// The correctness of the results returned by the functions depends
            /// on the following:
            /// - Documented behavior that if `T` implements `Eq`, two `Rc`s
            ///   that point to the same allocation are always equal:
            ///   <https://doc.rust-lang.org/1.82.0/std/rc/struct.Rc.html#method.eq>.
            /// - Undocumented behavior that the `Rc::partial_eq` implementation
            ///   for `T: Eq` will not use `PartialEq::eq` if both `Rc`s point
            ///   to the same memory location.
            /// - The assumption that the undocumented short-circuit behavior
            ///   described above will be retained for optimization purposes.
            ///
            /// There is no formal guarantee that the undocumented behavior
            /// described above will be retained. If the implementation changes
            /// in a future Rust version, the function may return a false
            /// negative, that is, it may return `false`, even though `T`
            /// implements the trait. However, the implementation guarantees
            /// that a false positive result is impossible, i.e., the function
            /// will never return true if `T` does not implement the trait in
            /// any future Rust version.
            ///
            /// Details:
            /// - <https://internals.rust-lang.org/t/rc-uses-visibly-behavior-changing-specialization-is-that-okay/16173/6>,
            /// - <https://users.rust-lang.org/t/hack-to-specialize-w-write-for-vec-u8/100366>,
            /// - <https://doc.rust-lang.org/1.82.0/std/rc/struct.Rc.html#method.eq>,
            /// - <https://github.com/rust-lang/rust/issues/42655>.
            ///
            $( #[$meta2] )*
            $vis $fn_name: $( $bounds )+
        }
    };
    ( $( #[$meta:meta] )* $vis:vis $fn_name:ident: $( $bounds:tt )+ ) => {
        $( #[$meta] )*
        #[inline]
        #[must_use]
        $vis fn $fn_name<T>() -> bool
        where
            T: ?Sized
        {
            struct Impl<'a, T>(&'a ::core::cell::Cell<bool>, ::core::marker::PhantomData<T>)
            where
                T: ?Sized;

            impl<T> PartialEq for Impl<'_, T>
            where
                T: ?Sized,
            {
                fn eq(&self, _other: &Self) -> bool {
                    let _ = self.0.set(true);
                    true
                }
            }

            impl<T> Eq for Impl<'_, T> where T: ?Sized + $( $bounds )+ {}

            let not_impls_trait = ::core::cell::Cell::new(false);
            let rc = $crate::macro_deps::Rc::new(Impl(
                &not_impls_trait,
                ::core::marker::PhantomData::<T>
            ));
            let _ = rc == rc;
            !not_impls_trait.get()
        }
    };
}

define_impls_trait_ignore_lt_fn!(#[auto_doc] pub impls_sized_weak: Sized);
define_impls_trait_ignore_lt_fn!(#[auto_doc] pub impls_send_weak: Send);
define_impls_trait_ignore_lt_fn!(#[auto_doc] pub impls_sync_weak: Sync);
define_impls_trait_ignore_lt_fn!(#[auto_doc] pub impls_unpin_weak: Unpin);
define_impls_trait_ignore_lt_fn!(#[auto_doc] pub impls_unwind_safe_weak: UnwindSafe);
define_impls_trait_ignore_lt_fn!(#[auto_doc] pub impls_ref_unwind_safe_weak: RefUnwindSafe);

define_impls_trait_ignore_lt_fn!(#[auto_doc] pub impls_deref_weak: Deref);
define_impls_trait_ignore_lt_fn!(
    #[auto_doc]
    /// # Examples
    ///
    /// ```rust
    /// # #[cfg(all(feature = "alloc", feature = "unreliable"))] {
    /// use core::sync::atomic::{AtomicU32, Ordering as AtomicOrdering};
    ///
    /// use try_specialize::unreliable::impls_copy_weak;
    ///
    /// #[derive(Eq, PartialEq, Debug)]
    /// pub struct ArrayLike<T, const N: usize> {
    /// #   inner: [T; N]
    /// }
    ///
    /// impl<T, const N: usize> From<[T; N]> for ArrayLike<T, N> {
    ///     #[inline]
    ///     fn from(value: [T; N]) -> Self {
    ///         // ...
    ///         # Self { inner: value }
    ///     }
    /// }
    ///
    /// impl<T, const N: usize> AsRef<[T; N]> for ArrayLike<T, N> {
    ///     #[inline]
    ///     fn as_ref(&self) -> &[T; N] {
    ///         // ...
    ///         # &self.inner
    ///     }
    /// }
    ///
    /// static DEBUG: AtomicU32 = AtomicU32::new(0);
    ///
    /// impl<T, const N: usize> Clone for ArrayLike<T, N>
    /// where
    ///     T: Clone
    /// {
    ///     #[inline]
    ///     fn clone(&self) -> Self {
    ///         if impls_copy_weak::<T>() {
    ///             DEBUG.store(101, AtomicOrdering::Relaxed);
    ///             // Fast path for `T: Copy`.
    ///             unsafe { std::mem::transmute_copy(self) }
    ///         } else {
    ///             DEBUG.store(202, AtomicOrdering::Relaxed);
    ///             Self::from(self.as_ref().clone())
    ///         }
    ///     }
    /// }
    ///
    /// #[derive(Clone, Eq, PartialEq, Debug)]
    /// struct NonCopiable<T>(pub T);
    ///
    /// assert_eq!(
    ///     ArrayLike::from([1, 2, 3]).clone(),
    ///     ArrayLike::from([1, 2, 3])
    /// );
    /// assert_eq!(DEBUG.load(AtomicOrdering::Relaxed), 101);
    ///
    /// assert_eq!(
    ///     ArrayLike::from([NonCopiable(1), NonCopiable(2)]).clone(),
    ///     ArrayLike::from([NonCopiable(1), NonCopiable(2)])
    /// );
    /// assert_eq!(DEBUG.load(AtomicOrdering::Relaxed), 202);
    /// # }
    /// ```
    pub impls_copy_weak: Copy
);
define_impls_trait_ignore_lt_fn!(#[auto_doc] pub impls_clone_weak: Clone);
define_impls_trait_ignore_lt_fn!(
    #[auto_doc]
    /// # Examples
    ///
    /// ```rust
    /// # #[cfg(all(feature = "alloc", feature = "unreliable"))] {
    ///
    /// use core::sync::atomic::{AtomicU32, Ordering as AtomicOrdering};
    /// # use std::sync::Arc;
    ///
    /// use try_specialize::unreliable::impls_eq_weak;
    ///
    /// #[derive(Clone, Debug)]
    /// pub struct ArcLike<T> {
    ///     // ...
    /// #   inner: Arc<T>,
    /// }
    ///
    /// impl<T> ArcLike<T> {
    ///     #[inline]
    ///     fn new(value: T) -> Self {
    ///         // ...
    /// #       Self {
    /// #           inner: Arc::new(value),
    /// #       }
    ///     }
    ///
    ///     #[inline]
    ///     fn as_ptr(&self) -> *const T {
    ///         // ...
    /// #       Arc::as_ptr(&self.inner)
    ///     }
    /// }
    ///
    /// impl<T> AsRef<T> for ArcLike<T> {
    ///     #[inline]
    ///     fn as_ref(&self) -> &T {
    ///         // ...
    /// #       &*self.inner
    ///     }
    /// }
    ///
    /// impl<T> PartialEq for ArcLike<T>
    /// where
    ///     T: PartialEq,
    /// {
    ///     #[inline]
    ///     fn eq(&self, other: &Self) -> bool {
    ///         // Fast path for `T: Eq`.
    ///         if impls_eq_weak::<T>() && self.as_ptr() == other.as_ptr() {
    ///             // Fast path for `T: Eq` if pointers are equal.
    ///             return true;
    ///         }
    ///         self.as_ref() == other.as_ref()
    ///     }
    /// }
    ///
    /// #[derive(Copy, Clone, Eq, Debug)]
    /// struct Wrapper<T>(pub T);
    ///
    /// static COUNTER: AtomicU32 = AtomicU32::new(0);
    ///
    /// impl<T> PartialEq for Wrapper<T>
    /// where
    ///     T: PartialEq,
    /// {
    ///     #[inline]
    ///     fn eq(&self, other: &Self) -> bool {
    ///         let _ = COUNTER.fetch_add(1, AtomicOrdering::Relaxed);
    ///         self.0 == other.0
    ///     }
    /// }
    ///
    /// let arc_like1 = ArcLike::new(Wrapper(42_u32));
    /// let arc_like2 = arc_like1.clone();
    /// assert_eq!(arc_like1, arc_like2);
    /// // `u32` implements Eq. Fast path used. Counter not incremented.
    /// assert_eq!(COUNTER.load(AtomicOrdering::Relaxed), 0);
    ///
    /// let arc_like1 = ArcLike::new(Wrapper(123.456_f64));
    /// let arc_like2 = arc_like1.clone();
    /// assert_eq!(arc_like1, arc_like2);
    /// // `f64` doesn't implement Eq. Fast path is not used.
    /// // Counter incremented.
    /// assert_eq!(COUNTER.load(AtomicOrdering::Relaxed), 1);
    /// # }
    /// ```
    pub impls_eq_weak: Eq
);
define_impls_trait_ignore_lt_fn!(#[auto_doc] pub impls_partial_eq_weak: PartialEq);
define_impls_trait_ignore_lt_fn!(#[auto_doc] pub impls_ord_weak: Ord);
define_impls_trait_ignore_lt_fn!(#[auto_doc] pub impls_partial_ord_weak: PartialOrd);
define_impls_trait_ignore_lt_fn!(#[auto_doc] pub impls_hash_weak: Hash);
define_impls_trait_ignore_lt_fn!(#[auto_doc] pub impls_default_weak: Default);
define_impls_trait_ignore_lt_fn!(#[auto_doc] pub impls_debug_weak: Debug);
define_impls_trait_ignore_lt_fn!(#[auto_doc] pub impls_display_weak: Display);
define_impls_trait_ignore_lt_fn!(#[auto_doc] pub impls_from_str_weak: FromStr);
define_impls_trait_ignore_lt_fn!(#[auto_doc] pub impls_iterator_weak: Iterator);
define_impls_trait_ignore_lt_fn!(#[auto_doc] pub impls_into_iterator_weak: IntoIterator);
define_impls_trait_ignore_lt_fn!(#[auto_doc] pub impls_future_weak: Future);
define_impls_trait_ignore_lt_fn!(#[auto_doc] pub impls_into_future_weak: IntoFuture);
define_impls_trait_ignore_lt_fn!(#[auto_doc] pub impls_fmt_write_weak: FmtWrite);
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
define_impls_trait_ignore_lt_fn!(#[auto_doc] pub impls_io_read_weak: IoRead);
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
define_impls_trait_ignore_lt_fn!(#[auto_doc] pub impls_io_write_weak: IoWrite);

define_impls_trait_ignore_lt_fn!(#[auto_doc] pub impls_lifetime_free_weak: LifetimeFree);

#[cfg(test)]
mod tests {
    #[cfg(feature = "alloc")]
    use alloc::string::String;
    #[cfg(feature = "alloc")]
    use alloc::vec::Vec;

    use crate::unreliable::{
        impls_clone_weak, impls_copy_weak, impls_eq_weak, impls_lifetime_free_weak,
        impls_partial_eq_weak,
    };

    #[test]
    fn test_impls_copy() {
        #[derive(Copy, Clone)]
        struct Copiable;
        #[derive(Clone)]
        struct Cloneable;
        struct NonCloneable;

        assert!(impls_copy_weak::<()>());
        assert!(impls_copy_weak::<u32>());
        assert!(impls_copy_weak::<f64>());

        assert!(impls_copy_weak::<Copiable>());
        assert!(!impls_copy_weak::<Cloneable>());
        assert!(!impls_copy_weak::<NonCloneable>());
    }

    #[cfg(feature = "alloc")]
    #[test]
    fn test_impls_copy_alloc() {
        assert!(impls_copy_weak::<&String>());
        assert!(impls_copy_weak::<&Vec<u8>>());
        assert!(!impls_copy_weak::<String>());
        assert!(!impls_copy_weak::<Vec<u8>>());
        assert!(!impls_copy_weak::<&mut String>());
        assert!(!impls_copy_weak::<&mut Vec<u8>>());
    }

    #[test]
    fn test_impls_clone() {
        #[derive(Copy, Clone)]
        struct Copiable;
        #[derive(Clone)]
        struct Cloneable;
        struct NonCloneable;

        assert!(impls_clone_weak::<()>());
        assert!(impls_clone_weak::<u32>());
        assert!(impls_clone_weak::<f64>());

        assert!(impls_clone_weak::<Copiable>());
        assert!(impls_clone_weak::<Cloneable>());
        assert!(!impls_clone_weak::<NonCloneable>());
    }

    #[test]
    fn test_impls_eq() {
        assert!(impls_eq_weak::<()>());
        assert!(impls_eq_weak::<u32>());
        assert!(!impls_eq_weak::<f64>());
    }

    #[cfg(feature = "alloc")]
    #[test]
    fn test_impls_eq_alloc() {
        assert!(impls_eq_weak::<&String>());
        assert!(impls_eq_weak::<&Vec<u8>>());
        assert!(impls_eq_weak::<String>());
        assert!(impls_eq_weak::<Vec<u8>>());
        assert!(impls_eq_weak::<&mut String>());
        assert!(impls_eq_weak::<&mut Vec<u8>>());
    }

    #[test]
    fn test_impls_partial_eq() {
        assert!(impls_partial_eq_weak::<()>());
        assert!(impls_partial_eq_weak::<u32>());
        assert!(impls_partial_eq_weak::<f64>());
    }

    #[cfg(feature = "alloc")]
    #[test]
    fn test_impls_partial_eq_alloc() {
        assert!(impls_partial_eq_weak::<&String>());
        assert!(impls_partial_eq_weak::<&Vec<u8>>());
        assert!(impls_partial_eq_weak::<String>());
        assert!(impls_partial_eq_weak::<Vec<u8>>());
        assert!(impls_partial_eq_weak::<&mut String>());
        assert!(impls_partial_eq_weak::<&mut Vec<u8>>());
    }

    #[test]
    fn test_lifetime_free() {
        assert!(impls_lifetime_free_weak::<()>());
        assert!(impls_lifetime_free_weak::<u32>());
        assert!(impls_lifetime_free_weak::<f64>());
    }

    #[cfg(feature = "alloc")]
    #[test]
    fn test_lifetime_free_alloc() {
        assert!(!impls_lifetime_free_weak::<&String>());
        assert!(!impls_lifetime_free_weak::<&Vec<u8>>());
        assert!(impls_lifetime_free_weak::<String>());
        assert!(impls_lifetime_free_weak::<Vec<u8>>());
        assert!(!impls_lifetime_free_weak::<&mut String>());
        assert!(!impls_lifetime_free_weak::<&mut Vec<u8>>());
    }
}