Debian Codegraph @

third_party/rust/async-trait/tests/test.rs

raw
1 #![cfg_attr(
2 async_trait_nightly_testing,
3 feature(min_specialization, type_alias_impl_trait)
4 )]
5 #![deny(rust_2021_compatibility)]
6 #![allow(
7 clippy::let_underscore_untyped,
8 clippy::let_unit_value,
9 clippy::missing_panics_doc,
10 clippy::missing_safety_doc,
11 clippy::needless_return,
12 clippy::trivially_copy_pass_by_ref,
13 clippy::unused_async
14 )]
15
16 use async_trait::async_trait;
17
18 pub mod executor;
19
20 // Dummy module to check that the expansion refer to rust's core crate
21 mod core {}
22
23 #[async_trait]
24 trait Trait {
25 type Assoc;
26
27 async fn selfvalue(self)
28 where
29 Self: Sized,
30 {
31 }
32
33 async fn selfref(&self) {}
34
35 async fn selfmut(&mut self) {}
36
37 async fn required() -> Self::Assoc;
38
39 async fn elided_lifetime(_x: &str) {}
40
41 async fn explicit_lifetime<'a>(_x: &'a str) {}
42
43 async fn generic_type_param<T: Send>(x: Box<T>) -> T {
44 *x
45 }
46
47 async fn calls(&self) {
48 self.selfref().await;
49 Self::elided_lifetime("").await;
50 <Self>::elided_lifetime("").await;
51 }
52
53 async fn calls_mut(&mut self) {
54 self.selfmut().await;
55 }
56 }
57
58 struct Struct;
59
60 #[async_trait]
61 impl Trait for Struct {
62 type Assoc = ();
63
64 async fn selfvalue(self) {}
65
66 async fn selfref(&self) {}
67
68 async fn selfmut(&mut self) {}
69
70 async fn required() -> Self::Assoc {}
71
72 async fn elided_lifetime(_x: &str) {}
73
74 async fn explicit_lifetime<'a>(_x: &'a str) {}
75
76 async fn generic_type_param<T: Send>(x: Box<T>) -> T {
77 *x
78 }
79
80 async fn calls(&self) {
81 self.selfref().await;
82 Self::elided_lifetime("").await;
83 <Self>::elided_lifetime("").await;
84 }
85
86 async fn calls_mut(&mut self) {
87 self.selfmut().await;
88 }
89 }
90
91 pub async fn test() {
92 let mut s = Struct;
93 s.selfref().await;
94 s.selfmut().await;
95 s.selfvalue().await;
96
97 Struct::required().await;
98 Struct::elided_lifetime("").await;
99 Struct::explicit_lifetime("").await;
100 Struct::generic_type_param(Box::new("")).await;
101
102 let mut s = Struct;
103 s.calls().await;
104 s.calls_mut().await;
105 }
106
107 pub async fn test_object_safe_without_default() {
108 #[async_trait]
109 trait ObjectSafe {
110 async fn f(&self);
111 }
112
113 #[async_trait]
114 impl ObjectSafe for Struct {
115 async fn f(&self) {}
116 }
117
118 let object = &Struct as &dyn ObjectSafe;
119 object.f().await;
120 }
121
122 pub async fn test_object_safe_with_default() {
123 #[async_trait]
124 trait ObjectSafe: Sync {
125 async fn f(&self) {}
126 }
127
128 #[async_trait]
129 impl ObjectSafe for Struct {
130 async fn f(&self) {}
131 }
132
133 let object = &Struct as &dyn ObjectSafe;
134 object.f().await;
135 }
136
137 pub async fn test_object_no_send() {
138 #[async_trait(?Send)]
139 trait ObjectSafe: Sync {
140 async fn f(&self) {}
141 }
142
143 #[async_trait(?Send)]
144 impl ObjectSafe for Struct {
145 async fn f(&self) {}
146 }
147
148 let object = &Struct as &dyn ObjectSafe;
149 object.f().await;
150 }
151
152 #[async_trait]
153 pub unsafe trait UnsafeTrait {}
154
155 #[async_trait]
156 unsafe impl UnsafeTrait for () {}
157
158 #[async_trait]
159 pub(crate) unsafe trait UnsafeTraitPubCrate {}
160
161 #[async_trait]
162 unsafe trait UnsafeTraitPrivate {}
163
164 pub async fn test_can_destruct() {
165 #[async_trait]
166 trait CanDestruct {
167 async fn f(&self, foos: (u8, u8, u8, u8));
168 }
169
170 #[async_trait]
171 impl CanDestruct for Struct {
172 async fn f(&self, (a, ref mut b, ref c, d): (u8, u8, u8, u8)) {
173 let _a: u8 = a;
174 let _b: &mut u8 = b;
175 let _c: &u8 = c;
176 let _d: u8 = d;
177 }
178 }
179 }
180
181 pub async fn test_self_in_macro() {
182 #[async_trait]
183 trait Trait {
184 async fn a(self);
185 async fn b(&mut self);
186 async fn c(&self);
187 }
188
189 #[async_trait]
190 impl Trait for String {
191 async fn a(self) {
192 println!("{}", self);
193 }
194 async fn b(&mut self) {
195 println!("{}", self);
196 }
197 async fn c(&self) {
198 println!("{}", self);
199 }
200 }
201 }
202
203 pub async fn test_inference() {
204 #[async_trait]
205 pub trait Trait {
206 async fn f() -> Box<dyn Iterator<Item = ()>> {
207 Box::new(std::iter::empty())
208 }
209 }
210 }
211
212 pub async fn test_internal_items() {
213 #[async_trait]
214 #[allow(dead_code, clippy::items_after_statements)]
215 pub trait Trait: Sized {
216 async fn f(self) {
217 struct Struct;
218
219 impl Struct {
220 fn f(self) {
221 let _ = self;
222 }
223 }
224 }
225 }
226 }
227
228 pub async fn test_unimplemented() {
229 #[async_trait]
230 pub trait Trait {
231 async fn f() {
232 unimplemented!()
233 }
234 }
235 }
236
237 // https://github.com/dtolnay/async-trait/issues/1
238 pub mod issue1 {
239 use async_trait::async_trait;
240
241 #[async_trait]
242 trait Issue1 {
243 async fn f<U>(&self);
244 }
245
246 #[async_trait]
247 impl<T: Sync> Issue1 for Vec<T> {
248 async fn f<U>(&self) {}
249 }
250 }
251
252 // https://github.com/dtolnay/async-trait/issues/2
253 pub mod issue2 {
254 use async_trait::async_trait;
255 use std::future::Future;
256
257 #[async_trait]
258 pub trait Issue2: Future {
259 async fn flatten(self) -> <Self::Output as Future>::Output
260 where
261 Self::Output: Future + Send,
262 Self: Sized,
263 {
264 let nested_future = self.await;
265 nested_future.await
266 }
267 }
268 }
269
270 // https://github.com/dtolnay/async-trait/issues/9
271 pub mod issue9 {
272 use async_trait::async_trait;
273
274 #[async_trait]
275 pub trait Issue9: Sized + Send {
276 async fn f(_x: Self) {}
277 }
278 }
279
280 // https://github.com/dtolnay/async-trait/issues/11
281 pub mod issue11 {
282 use async_trait::async_trait;
283 use std::sync::Arc;
284
285 #[async_trait]
286 trait Issue11 {
287 async fn example(self: Arc<Self>);
288 }
289
290 struct Struct;
291
292 #[async_trait]
293 impl Issue11 for Struct {
294 async fn example(self: Arc<Self>) {}
295 }
296 }
297
298 // https://github.com/dtolnay/async-trait/issues/15
299 pub mod issue15 {
300 use async_trait::async_trait;
301 use std::marker::PhantomData;
302
303 trait Trait {}
304
305 #[async_trait]
306 trait Issue15 {
307 async fn myfn(&self, _: PhantomData<dyn Trait + Send>) {}
308 }
309 }
310
311 // https://github.com/dtolnay/async-trait/issues/17
312 pub mod issue17 {
313 use async_trait::async_trait;
314
315 #[async_trait]
316 trait Issue17 {
317 async fn f(&self);
318 }
319
320 struct Struct {
321 string: String,
322 }
323
324 #[async_trait]
325 impl Issue17 for Struct {
326 async fn f(&self) {
327 println!("{}", self.string);
328 }
329 }
330 }
331
332 // https://github.com/dtolnay/async-trait/issues/23
333 pub mod issue23 {
334 use async_trait::async_trait;
335
336 #[async_trait]
337 pub trait Issue23 {
338 async fn f(self);
339
340 async fn g(mut self)
341 where
342 Self: Sized,
343 {
344 do_something(&mut self);
345 }
346 }
347
348 struct S {}
349
350 #[async_trait]
351 impl Issue23 for S {
352 async fn f(mut self) {
353 do_something(&mut self);
354 }
355 }
356
357 fn do_something<T>(_: &mut T) {}
358 }
359
360 // https://github.com/dtolnay/async-trait/issues/25
361 #[cfg(async_trait_nightly_testing)]
362 pub mod issue25 {
363 use crate::executor;
364 use async_trait::async_trait;
365 use std::fmt::{Display, Write};
366
367 #[async_trait]
368 trait AsyncToString {
369 async fn async_to_string(&self) -> String;
370 }
371
372 #[async_trait]
373 impl AsyncToString for String {
374 async fn async_to_string(&self) -> String {
375 "special".to_owned()
376 }
377 }
378
379 macro_rules! hide_from_stable_parser {
380 ($($tt:tt)*) => {
381 $($tt)*
382 };
383 }
384
385 hide_from_stable_parser! {
386 #[async_trait]
387 impl<T: ?Sized + Display + Sync> AsyncToString for T {
388 default async fn async_to_string(&self) -> String {
389 let mut buf = String::new();
390 buf.write_fmt(format_args!("{}", self)).unwrap();
391 buf
392 }
393 }
394 }
395
396 #[test]
397 fn test() {
398 let fut = true.async_to_string();
399 assert_eq!(executor::block_on_simple(fut), "true");
400
401 let string = String::new();
402 let fut = string.async_to_string();
403 assert_eq!(executor::block_on_simple(fut), "special");
404 }
405 }
406
407 // https://github.com/dtolnay/async-trait/issues/28
408 pub mod issue28 {
409 use async_trait::async_trait;
410
411 struct Str<'a>(&'a str);
412
413 #[async_trait]
414 trait Trait1<'a> {
415 async fn f(x: Str<'a>) -> &'a str;
416 async fn g(x: Str<'a>) -> &'a str {
417 x.0
418 }
419 }
420
421 #[async_trait]
422 impl<'a> Trait1<'a> for str {
423 async fn f(x: Str<'a>) -> &'a str {
424 x.0
425 }
426 }
427
428 #[async_trait]
429 trait Trait2 {
430 async fn f();
431 }
432
433 #[async_trait]
434 impl<'a> Trait2 for &'a () {
435 async fn f() {}
436 }
437
438 #[async_trait]
439 trait Trait3<'a, 'b> {
440 async fn f(_: &'a &'b ()); // chain 'a and 'b
441 async fn g(_: &'b ()); // chain 'b only
442 async fn h(); // do not chain
443 }
444 }
445
446 // https://github.com/dtolnay/async-trait/issues/31
447 pub mod issue31 {
448 use async_trait::async_trait;
449
450 pub struct Struct<'a> {
451 pub name: &'a str,
452 }
453
454 #[async_trait]
455 pub trait Trait<'a> {
456 async fn hello(thing: Struct<'a>) -> String;
457 async fn hello_twice(one: Struct<'a>, two: Struct<'a>) -> String {
458 let str1 = Self::hello(one).await;
459 let str2 = Self::hello(two).await;
460 str1 + &str2
461 }
462 }
463 }
464
465 // https://github.com/dtolnay/async-trait/issues/42
466 pub mod issue42 {
467 use async_trait::async_trait;
468
469 #[async_trait]
470 pub trait Context: Sized {
471 async fn from_parts() -> Self;
472 }
473
474 pub struct TokenContext;
475
476 #[async_trait]
477 impl Context for TokenContext {
478 async fn from_parts() -> TokenContext {
479 TokenContext
480 }
481 }
482 }
483
484 // https://github.com/dtolnay/async-trait/issues/44
485 pub mod issue44 {
486 use async_trait::async_trait;
487
488 #[async_trait]
489 pub trait StaticWithWhereSelf
490 where
491 Box<Self>: Sized,
492 Self: Sized + Send,
493 {
494 async fn get_one() -> u8 {
495 1
496 }
497 }
498
499 pub struct Struct;
500
501 #[async_trait]
502 impl StaticWithWhereSelf for Struct {}
503 }
504
505 // https://github.com/dtolnay/async-trait/issues/45
506 pub mod issue45 {
507 use crate::executor;
508 use async_trait::async_trait;
509 use std::fmt::Debug;
510 use std::sync::atomic::{AtomicU64, Ordering};
511 use std::sync::{Arc, Mutex};
512 use tracing::event::Event;
513 use tracing::field::{Field, Visit};
514 use tracing::span::{Attributes, Id, Record};
515 use tracing::{info, instrument, subscriber, Metadata, Subscriber};
516
517 #[async_trait]
518 pub trait Parent {
519 async fn foo(&mut self, v: usize);
520 }
521
522 #[async_trait]
523 pub trait Child {
524 async fn bar(&self);
525 }
526
527 #[derive(Debug)]
528 struct Impl(usize);
529
530 #[async_trait]
531 impl Parent for Impl {
532 #[instrument]
533 async fn foo(&mut self, v: usize) {
534 self.0 = v;
535 self.bar().await;
536 }
537 }
538
539 #[async_trait]
540 impl Child for Impl {
541 // Let's check that tracing detects the renaming of the `self` variable
542 // too, as tracing::instrument is not going to be able to skip the
543 // `self` argument if it can't find it in the function signature.
544 #[instrument(skip(self))]
545 async fn bar(&self) {
546 info!(val = self.0);
547 }
548 }
549
550 // A simple subscriber implementation to test the behavior of async-trait
551 // with tokio-rs/tracing. This implementation is not robust against race
552 // conditions, but it's not an issue here as we are only polling on a single
553 // future at a time.
554 #[derive(Debug)]
555 struct SubscriberInner {
556 current_depth: AtomicU64,
557 // We assert that nested functions work. If the fix were to break, we
558 // would see two top-level functions instead of `bar` nested in `foo`.
559 max_depth: AtomicU64,
560 max_span_id: AtomicU64,
561 // Name of the variable / value / depth when the event was recorded.
562 value: Mutex<Option<(&'static str, u64, u64)>>,
563 }
564
565 #[derive(Debug, Clone)]
566 struct TestSubscriber {
567 inner: Arc<SubscriberInner>,
568 }
569
570 impl TestSubscriber {
571 fn new() -> Self {
572 TestSubscriber {
573 inner: Arc::new(SubscriberInner {
574 current_depth: AtomicU64::new(0),
575 max_depth: AtomicU64::new(0),
576 max_span_id: AtomicU64::new(1),
577 value: Mutex::new(None),
578 }),
579 }
580 }
581 }
582
583 struct U64Visitor(Option<(&'static str, u64)>);
584
585 impl Visit for U64Visitor {
586 fn record_debug(&mut self, _field: &Field, _value: &dyn Debug) {}
587
588 fn record_u64(&mut self, field: &Field, value: u64) {
589 self.0 = Some((field.name(), value));
590 }
591 }
592
593 impl Subscriber for TestSubscriber {
594 fn enabled(&self, _metadata: &Metadata) -> bool {
595 true
596 }
597 fn new_span(&self, _span: &Attributes) -> Id {
598 Id::from_u64(self.inner.max_span_id.fetch_add(1, Ordering::AcqRel))
599 }
600 fn record(&self, _span: &Id, _values: &Record) {}
601 fn record_follows_from(&self, _span: &Id, _follows: &Id) {}
602 fn event(&self, event: &Event) {
603 let mut visitor = U64Visitor(None);
604 event.record(&mut visitor);
605 if let Some((s, v)) = visitor.0 {
606 let current_depth = self.inner.current_depth.load(Ordering::Acquire);
607 *self.inner.value.lock().unwrap() = Some((s, v, current_depth));
608 }
609 }
610 fn enter(&self, _span: &Id) {
611 let old_depth = self.inner.current_depth.fetch_add(1, Ordering::AcqRel);
612 if old_depth + 1 > self.inner.max_depth.load(Ordering::Acquire) {
613 self.inner.max_depth.fetch_add(1, Ordering::AcqRel);
614 }
615 }
616 fn exit(&self, _span: &Id) {
617 self.inner.current_depth.fetch_sub(1, Ordering::AcqRel);
618 }
619 }
620
621 #[test]
622 #[cfg_attr(miri, ignore)] // https://github.com/matklad/once_cell/pull/185
623 fn tracing() {
624 // Create the future outside of the subscriber, as no call to tracing
625 // should be made until the future is polled.
626 let mut struct_impl = Impl(0);
627 let fut = struct_impl.foo(5);
628 let subscriber = TestSubscriber::new();
629 subscriber::with_default(subscriber.clone(), || executor::block_on_simple(fut));
630 // Did we enter bar inside of foo?
631 assert_eq!(subscriber.inner.max_depth.load(Ordering::Acquire), 2);
632 // Have we exited all spans?
633 assert_eq!(subscriber.inner.current_depth.load(Ordering::Acquire), 0);
634 // Did we create only two spans? Note: spans start at 1, hence the -1.
635 assert_eq!(subscriber.inner.max_span_id.load(Ordering::Acquire) - 1, 2);
636 // Was the value recorded at the right depth i.e. in the right function?
637 // If so, was it the expected value?
638 assert_eq!(*subscriber.inner.value.lock().unwrap(), Some(("val", 5, 2)));
639 }
640 }
641
642 // https://github.com/dtolnay/async-trait/issues/46
643 pub mod issue46 {
644 use async_trait::async_trait;
645
646 macro_rules! implement_commands_workaround {
647 ($tyargs:tt : $ty:tt) => {
648 #[async_trait]
649 pub trait AsyncCommands1: Sized {
650 async fn f<$tyargs: $ty>(&mut self, x: $tyargs) {
651 self.f(x).await
652 }
653 }
654 };
655 }
656
657 implement_commands_workaround!(K: Send);
658
659 macro_rules! implement_commands {
660 ($tyargs:ident : $ty:ident) => {
661 #[async_trait]
662 pub trait AsyncCommands2: Sized {
663 async fn f<$tyargs: $ty>(&mut self, x: $tyargs) {
664 self.f(x).await
665 }
666 }
667 };
668 }
669
670 implement_commands!(K: Send);
671 }
672
673 // https://github.com/dtolnay/async-trait/issues/53
674 pub mod issue53 {
675 use async_trait::async_trait;
676
677 pub struct Unit;
678 pub struct Tuple(u8);
679 pub struct Struct {
680 pub x: u8,
681 }
682
683 #[async_trait]
684 pub trait Trait {
685 async fn method();
686 }
687
688 #[async_trait]
689 impl Trait for Unit {
690 async fn method() {
691 let _ = Self;
692 }
693 }
694
695 #[async_trait]
696 impl Trait for Tuple {
697 async fn method() {
698 let _ = Self(0);
699 }
700 }
701
702 #[async_trait]
703 impl Trait for Struct {
704 async fn method() {
705 let _ = Self { x: 0 };
706 }
707 }
708
709 #[async_trait]
710 impl Trait for std::marker::PhantomData<Struct> {
711 async fn method() {
712 let _ = Self;
713 }
714 }
715 }
716
717 // https://github.com/dtolnay/async-trait/issues/57
718 #[cfg(async_trait_nightly_testing)]
719 pub mod issue57 {
720 use crate::executor;
721 use async_trait::async_trait;
722
723 #[async_trait]
724 trait Trait {
725 async fn const_generic<T: Send, const C: usize>(_: [T; C]) {}
726 }
727
728 struct Struct;
729
730 #[async_trait]
731 impl Trait for Struct {
732 async fn const_generic<T: Send, const C: usize>(_: [T; C]) {}
733 }
734
735 #[test]
736 fn test() {
737 let fut = Struct::const_generic([0; 10]);
738 executor::block_on_simple(fut);
739 }
740 }
741
742 // https://github.com/dtolnay/async-trait/issues/68
743 pub mod issue68 {
744 #[async_trait::async_trait]
745 pub trait Example {
746 async fn method(&self) {
747 macro_rules! t {
748 () => {{
749 let _: &Self = self;
750 }};
751 }
752 t!();
753 }
754 }
755 }
756
757 // https://github.com/dtolnay/async-trait/issues/73
758 pub mod issue73 {
759 use async_trait::async_trait;
760
761 #[async_trait]
762 pub trait Example {
763 const ASSOCIATED: &'static str;
764
765 async fn associated(&self) {
766 println!("Associated:{}", Self::ASSOCIATED);
767 }
768 }
769 }
770
771 // https://github.com/dtolnay/async-trait/issues/81
772 pub mod issue81 {
773 use async_trait::async_trait;
774
775 #[async_trait]
776 pub trait Trait {
777 async fn handle(&self);
778 }
779
780 pub enum Enum {
781 Variant,
782 }
783
784 #[async_trait]
785 impl Trait for Enum {
786 async fn handle(&self) {
787 let Enum::Variant = self;
788 let Self::Variant = self;
789 }
790 }
791 }
792
793 // https://github.com/dtolnay/async-trait/issues/83
794 pub mod issue83 {
795 #![allow(clippy::needless_arbitrary_self_type)]
796
797 use async_trait::async_trait;
798
799 #[async_trait]
800 pub trait Trait {
801 async fn f(&self) {}
802 async fn g(self: &Self) {}
803 }
804 }
805
806 // https://github.com/dtolnay/async-trait/issues/85
807 pub mod issue85 {
808 #![deny(non_snake_case)]
809
810 use async_trait::async_trait;
811
812 #[async_trait]
813 pub trait Trait {
814 #[allow(non_snake_case)]
815 async fn camelCase();
816 }
817
818 pub struct Struct;
819
820 #[async_trait]
821 impl Trait for Struct {
822 async fn camelCase() {}
823 }
824 }
825
826 // https://github.com/dtolnay/async-trait/issues/87
827 pub mod issue87 {
828 use async_trait::async_trait;
829
830 #[async_trait]
831 pub trait Trait {
832 async fn f(&self);
833 }
834
835 pub enum Tuple {
836 V(),
837 }
838
839 pub enum Struct {
840 V {},
841 }
842
843 #[async_trait]
844 impl Trait for Tuple {
845 async fn f(&self) {
846 let Tuple::V() = self;
847 let Self::V() = self;
848 let _ = Self::V;
849 let _ = Self::V();
850 }
851 }
852
853 #[async_trait]
854 impl Trait for Struct {
855 async fn f(&self) {
856 let Struct::V {} = self;
857 let Self::V {} = self;
858 let _ = Self::V {};
859 }
860 }
861 }
862
863 // https://github.com/dtolnay/async-trait/issues/89
864 pub mod issue89 {
865 #![allow(bare_trait_objects)]
866
867 use async_trait::async_trait;
868
869 #[async_trait]
870 trait Trait {
871 async fn f(&self);
872 }
873
874 #[async_trait]
875 impl Trait for Send + Sync {
876 async fn f(&self) {}
877 }
878
879 #[async_trait]
880 impl Trait for dyn Fn(i8) + Send + Sync {
881 async fn f(&self) {}
882 }
883
884 #[async_trait]
885 impl Trait for (dyn Fn(u8) + Send + Sync) {
886 async fn f(&self) {}
887 }
888 }
889
890 // https://github.com/dtolnay/async-trait/issues/92
891 pub mod issue92 {
892 use async_trait::async_trait;
893
894 macro_rules! mac {
895 ($($tt:tt)*) => {
896 $($tt)*
897 };
898 }
899
900 pub struct Struct<T> {
901 _x: T,
902 }
903
904 impl<T> Struct<T> {
905 const ASSOCIATED1: &'static str = "1";
906 async fn associated1() {}
907 }
908
909 #[async_trait]
910 pub trait Trait
911 where
912 mac!(Self): Send,
913 {
914 const ASSOCIATED2: &'static str;
915 type Associated2;
916
917 #[allow(path_statements, clippy::let_underscore_future, clippy::no_effect)]
918 async fn associated2(&self) {
919 // trait items
920 mac!(let _: Self::Associated2;);
921 mac!(let _: <Self>::Associated2;);
922 mac!(let _: <Self as Trait>::Associated2;);
923 mac!(Self::ASSOCIATED2;);
924 mac!(<Self>::ASSOCIATED2;);
925 mac!(<Self as Trait>::ASSOCIATED2;);
926 mac!(let _ = Self::associated2(self););
927 mac!(let _ = <Self>::associated2(self););
928 mac!(let _ = <Self as Trait>::associated2(self););
929 }
930 }
931
932 #[async_trait]
933 impl<T: Send + Sync> Trait for Struct<T>
934 where
935 mac!(Self): Send,
936 {
937 const ASSOCIATED2: &'static str = "2";
938 type Associated2 = ();
939
940 #[allow(path_statements, clippy::let_underscore_future, clippy::no_effect)]
941 async fn associated2(&self) {
942 // inherent items
943 mac!(Self::ASSOCIATED1;);
944 mac!(<Self>::ASSOCIATED1;);
945 mac!(let _ = Self::associated1(););
946 mac!(let _ = <Self>::associated1(););
947
948 // trait items
949 mac!(let _: <Self as Trait>::Associated2;);
950 mac!(Self::ASSOCIATED2;);
951 mac!(<Self>::ASSOCIATED2;);
952 mac!(<Self as Trait>::ASSOCIATED2;);
953 mac!(let _ = Self::associated2(self););
954 mac!(let _ = <Self>::associated2(self););
955 mac!(let _ = <Self as Trait>::associated2(self););
956 }
957 }
958
959 pub struct Unit;
960
961 #[async_trait]
962 impl Trait for Unit {
963 const ASSOCIATED2: &'static str = "2";
964 type Associated2 = ();
965
966 async fn associated2(&self) {
967 mac!(let Self: Self = *self;);
968 }
969 }
970 }
971
972 // https://github.com/dtolnay/async-trait/issues/92#issuecomment-683370136
973 pub mod issue92_2 {
974 use async_trait::async_trait;
975
976 macro_rules! mac {
977 ($($tt:tt)*) => {
978 $($tt)*
979 };
980 }
981
982 pub trait Trait1 {
983 fn func1();
984 }
985
986 #[async_trait]
987 pub trait Trait2: Trait1 {
988 async fn func2() {
989 mac!(Self::func1());
990
991 macro_rules! mac2 {
992 ($($tt:tt)*) => {
993 Self::func1();
994 };
995 }
996 mac2!();
997 }
998 }
999 }
1000
1001 // https://github.com/dtolnay/async-trait/issues/104
1002 pub mod issue104 {
1003 use async_trait::async_trait;
1004
1005 #[async_trait]
1006 trait T1 {
1007 async fn id(&self) -> i32;
1008 }
1009
1010 macro_rules! impl_t1 {
1011 ($ty:ty, $id:expr) => {
1012 #[async_trait]
1013 impl T1 for $ty {
1014 async fn id(&self) -> i32 {
1015 $id
1016 }
1017 }
1018 };
1019 }
1020
1021 struct Foo;
1022
1023 impl_t1!(Foo, 1);
1024 }
1025
1026 // https://github.com/dtolnay/async-trait/issues/106
1027 pub mod issue106 {
1028 use async_trait::async_trait;
1029 use std::future::Future;
1030
1031 #[async_trait]
1032 pub trait ProcessPool: Send + Sync {
1033 type ThreadPool;
1034
1035 async fn spawn<F, Fut, T>(&self, work: F) -> T
1036 where
1037 F: FnOnce(&Self::ThreadPool) -> Fut + Send,
1038 Fut: Future<Output = T> + 'static;
1039 }
1040
1041 #[async_trait]
1042 impl<P> ProcessPool for &P
1043 where
1044 P: ?Sized + ProcessPool,
1045 {
1046 type ThreadPool = P::ThreadPool;
1047
1048 async fn spawn<F, Fut, T>(&self, work: F) -> T
1049 where
1050 F: FnOnce(&Self::ThreadPool) -> Fut + Send,
1051 Fut: Future<Output = T> + 'static,
1052 {
1053 (**self).spawn(work).await
1054 }
1055 }
1056 }
1057
1058 // https://github.com/dtolnay/async-trait/issues/110
1059 pub mod issue110 {
1060 use async_trait::async_trait;
1061 use std::marker::PhantomData;
1062
1063 #[async_trait]
1064 pub trait Loader {
1065 async fn load(&self, key: &str);
1066 }
1067
1068 pub struct AwsEc2MetadataLoader<'a> {
1069 marker: PhantomData<&'a ()>,
1070 }
1071
1072 #[async_trait]
1073 impl Loader for AwsEc2MetadataLoader<'_> {
1074 async fn load(&self, _key: &str) {}
1075 }
1076 }
1077
1078 // https://github.com/dtolnay/async-trait/issues/120
1079 pub mod issue120 {
1080 #![deny(clippy::trivially_copy_pass_by_ref)]
1081
1082 use async_trait::async_trait;
1083
1084 #[async_trait]
1085 trait Trait {
1086 async fn f(&self);
1087 }
1088
1089 #[async_trait]
1090 impl Trait for () {
1091 async fn f(&self) {}
1092 }
1093 }
1094
1095 // https://github.com/dtolnay/async-trait/issues/123
1096 pub mod issue123 {
1097 use async_trait::async_trait;
1098
1099 #[async_trait]
1100 trait Trait<T = ()> {
1101 async fn f(&self) -> &str
1102 where
1103 T: 'async_trait,
1104 {
1105 "default"
1106 }
1107 }
1108
1109 #[async_trait]
1110 impl<T> Trait<T> for () {}
1111 }
1112
1113 // https://github.com/dtolnay/async-trait/issues/129
1114 pub mod issue129 {
1115 use async_trait::async_trait;
1116
1117 #[async_trait]
1118 pub trait TestTrait {
1119 async fn a(_b: u8, c: u8) -> u8 {
1120 c
1121 }
1122 }
1123
1124 pub struct TestStruct;
1125
1126 #[async_trait]
1127 impl TestTrait for TestStruct {
1128 async fn a(_b: u8, c: u8) -> u8 {
1129 c
1130 }
1131 }
1132 }
1133
1134 // https://github.com/dtolnay/async-trait/issues/134
1135 #[cfg(async_trait_nightly_testing)]
1136 pub mod issue134 {
1137 use async_trait::async_trait;
1138
1139 #[async_trait]
1140 trait TestTrait {
1141 async fn run<const DUMMY: bool>(self)
1142 where
1143 Self: Sized,
1144 {
1145 }
1146 }
1147
1148 pub struct TestStruct;
1149
1150 #[async_trait]
1151 impl TestTrait for TestStruct {
1152 async fn run<const DUMMY: bool>(self)
1153 where
1154 Self: Sized,
1155 {
1156 }
1157 }
1158 }
1159
1160 // https://github.com/dtolnay/async-trait/pull/125#pullrequestreview-491880881
1161 pub mod drop_order {
1162 use crate::executor;
1163 use async_trait::async_trait;
1164 use std::sync::atomic::{AtomicBool, Ordering};
1165
1166 struct Flagger<'a>(&'a AtomicBool);
1167
1168 impl Drop for Flagger<'_> {
1169 fn drop(&mut self) {
1170 self.0.fetch_xor(true, Ordering::AcqRel);
1171 }
1172 }
1173
1174 #[async_trait]
1175 trait Trait {
1176 async fn async_trait(_: Flagger<'_>, flag: &AtomicBool);
1177 }
1178
1179 struct Struct;
1180
1181 #[async_trait]
1182 impl Trait for Struct {
1183 async fn async_trait(_: Flagger<'_>, flag: &AtomicBool) {
1184 flag.fetch_or(true, Ordering::AcqRel);
1185 }
1186 }
1187
1188 async fn standalone(_: Flagger<'_>, flag: &AtomicBool) {
1189 flag.fetch_or(true, Ordering::AcqRel);
1190 }
1191
1192 #[async_trait]
1193 trait SelfTrait {
1194 async fn async_trait(self, flag: &AtomicBool);
1195 }
1196
1197 #[async_trait]
1198 impl SelfTrait for Flagger<'_> {
1199 async fn async_trait(self, flag: &AtomicBool) {
1200 flag.fetch_or(true, Ordering::AcqRel);
1201 }
1202 }
1203
1204 #[test]
1205 fn test_drop_order() {
1206 // 0 : 0 ^ 1 = 1 | 1 = 1 (if flagger then block)
1207 // 0 : 0 | 1 = 1 ^ 1 = 0 (if block then flagger)
1208
1209 let flag = AtomicBool::new(false);
1210 executor::block_on_simple(standalone(Flagger(&flag), &flag));
1211 assert!(!flag.load(Ordering::Acquire));
1212
1213 executor::block_on_simple(Struct::async_trait(Flagger(&flag), &flag));
1214 assert!(!flag.load(Ordering::Acquire));
1215
1216 executor::block_on_simple(Flagger(&flag).async_trait(&flag));
1217 assert!(!flag.load(Ordering::Acquire));
1218 }
1219 }
1220
1221 // https://github.com/dtolnay/async-trait/issues/145
1222 pub mod issue145 {
1223 #![deny(clippy::type_complexity)]
1224
1225 use async_trait::async_trait;
1226
1227 #[async_trait]
1228 pub trait ManageConnection: Sized + Send + Sync + 'static {
1229 type Connection: Send + 'static;
1230 type Error: Send + 'static;
1231
1232 async fn connect(&self) -> Result<Self::Connection, Self::Error>;
1233 }
1234 }
1235
1236 // https://github.com/dtolnay/async-trait/issues/147
1237 pub mod issue147 {
1238 #![deny(clippy::let_unit_value)]
1239
1240 use async_trait::async_trait;
1241
1242 pub struct MyType;
1243
1244 #[async_trait]
1245 pub trait MyTrait {
1246 async fn x();
1247 async fn y() -> ();
1248 async fn z();
1249 }
1250
1251 #[async_trait]
1252 impl MyTrait for MyType {
1253 async fn x() {}
1254 async fn y() -> () {}
1255 async fn z() {
1256 unimplemented!()
1257 }
1258 }
1259 }
1260
1261 // https://github.com/dtolnay/async-trait/issues/149
1262 pub mod issue149 {
1263 use async_trait::async_trait;
1264
1265 pub struct Thing;
1266 pub trait Ret {}
1267 impl Ret for Thing {}
1268
1269 pub async fn ok() -> &'static dyn Ret {
1270 return &Thing;
1271 }
1272
1273 #[async_trait]
1274 pub trait Trait {
1275 async fn fail() -> &'static dyn Ret {
1276 return &Thing;
1277 }
1278 }
1279 }
1280
1281 // https://github.com/dtolnay/async-trait/issues/152
1282 #[cfg(async_trait_nightly_testing)]
1283 pub mod issue152 {
1284 use async_trait::async_trait;
1285
1286 #[async_trait]
1287 trait Trait {
1288 type Assoc;
1289
1290 async fn f(&self) -> Self::Assoc;
1291 }
1292
1293 struct Struct;
1294
1295 #[async_trait]
1296 impl Trait for Struct {
1297 type Assoc = impl Sized;
1298
1299 async fn f(&self) -> Self::Assoc {}
1300 }
1301 }
1302
1303 // https://github.com/dtolnay/async-trait/issues/154
1304 pub mod issue154 {
1305 #![deny(clippy::items_after_statements)]
1306
1307 use async_trait::async_trait;
1308
1309 #[async_trait]
1310 pub trait MyTrait {
1311 async fn f(&self);
1312 }
1313
1314 pub struct Struct;
1315
1316 #[async_trait]
1317 impl MyTrait for Struct {
1318 async fn f(&self) {
1319 const MAX: u16 = 128;
1320 println!("{}", MAX);
1321 }
1322 }
1323 }
1324
1325 // https://github.com/dtolnay/async-trait/issues/158
1326 pub mod issue158 {
1327 use async_trait::async_trait;
1328
1329 fn f() {}
1330
1331 #[async_trait]
1332 pub trait Trait {
1333 async fn f(&self) {
1334 self::f();
1335 }
1336 }
1337 }
1338
1339 // https://github.com/dtolnay/async-trait/issues/161
1340 #[allow(clippy::mut_mut)]
1341 pub mod issue161 {
1342 use async_trait::async_trait;
1343 use futures::future::FutureExt;
1344 use std::sync::Arc;
1345
1346 #[async_trait]
1347 pub trait Trait {
1348 async fn f(self: Arc<Self>);
1349 }
1350
1351 pub struct MyStruct(bool);
1352
1353 #[async_trait]
1354 impl Trait for MyStruct {
1355 async fn f(self: Arc<Self>) {
1356 futures::select! {
1357 _ = async {
1358 println!("{}", self.0);
1359 }.fuse() => {}
1360 }
1361 }
1362 }
1363 }
1364
1365 // https://github.com/dtolnay/async-trait/issues/169
1366 #[deny(where_clauses_object_safety)]
1367 pub mod issue169 {
1368 use async_trait::async_trait;
1369
1370 #[async_trait]
1371 pub trait Trait: ::core::marker::Sync {
1372 async fn f(&self) {}
1373 }
1374
1375 pub fn test(_t: &dyn Trait) {}
1376 }
1377
1378 // https://github.com/dtolnay/async-trait/issues/177
1379 pub mod issue177 {
1380 use async_trait::async_trait;
1381
1382 #[async_trait]
1383 pub trait Trait {
1384 async fn foo(&self, _callback: impl FnMut(&str) + Send) {}
1385 }
1386
1387 pub struct Struct;
1388
1389 #[async_trait]
1390 impl Trait for Struct {
1391 async fn foo(&self, _callback: impl FnMut(&str) + Send) {}
1392 }
1393 }
1394
1395 // https://github.com/dtolnay/async-trait/issues/183
1396 pub mod issue183 {
1397 #![deny(clippy::shadow_same)]
1398
1399 use async_trait::async_trait;
1400
1401 #[async_trait]
1402 trait Foo {
1403 async fn foo(_n: i32) {}
1404 }
1405 }
1406
1407 // https://github.com/dtolnay/async-trait/issues/199
1408 pub mod issue199 {
1409 use async_trait::async_trait;
1410 use std::cell::Cell;
1411
1412 struct IncrementOnDrop<'a>(&'a Cell<usize>);
1413
1414 impl<'a> Drop for IncrementOnDrop<'a> {
1415 fn drop(&mut self) {
1416 self.0.set(self.0.get() + 1);
1417 }
1418 }
1419
1420 #[async_trait(?Send)]
1421 trait Trait {
1422 async fn f(counter: &Cell<usize>, arg: IncrementOnDrop<'_>);
1423 }
1424
1425 struct Struct;
1426
1427 #[async_trait(?Send)]
1428 impl Trait for Struct {
1429 async fn f(counter: &Cell<usize>, _: IncrementOnDrop<'_>) {
1430 assert_eq!(counter.get(), 0); // second arg not dropped yet
1431 }
1432 }
1433
1434 #[test]
1435 fn test() {
1436 let counter = Cell::new(0);
1437 let future = Struct::f(&counter, IncrementOnDrop(&counter));
1438 assert_eq!(counter.get(), 0);
1439 drop(future);
1440 assert_eq!(counter.get(), 1);
1441 }
1442 }
1443
1444 // https://github.com/dtolnay/async-trait/issues/204
1445 pub mod issue204 {
1446 use async_trait::async_trait;
1447
1448 #[async_trait]
1449 pub trait Trait {
1450 async fn f(arg: &impl Trait);
1451 async fn g(arg: *const impl Trait);
1452 }
1453 }
1454
1455 // https://github.com/dtolnay/async-trait/issues/210
1456 pub mod issue210 {
1457 use async_trait::async_trait;
1458 use std::sync::Arc;
1459
1460 #[async_trait]
1461 pub trait Trait {
1462 async fn f(self: Arc<Self>) {}
1463 }
1464 }
1465
1466 // https://github.com/dtolnay/async-trait/issues/226
1467 pub mod issue226 {
1468 use async_trait::async_trait;
1469
1470 #[async_trait]
1471 pub trait Trait {
1472 async fn cfg_param(&self, param: u8);
1473 async fn cfg_param_wildcard(&self, _: u8);
1474 async fn cfg_param_tuple(&self, (left, right): (u8, u8));
1475 }
1476
1477 struct Struct;
1478
1479 #[async_trait]
1480 impl Trait for Struct {
1481 async fn cfg_param(&self, #[cfg(any())] param: u8, #[cfg(all())] _unused: u8) {}
1482
1483 async fn cfg_param_wildcard(&self, #[cfg(any())] _: u8, #[cfg(all())] _: u8) {}
1484
1485 async fn cfg_param_tuple(
1486 &self,
1487 #[cfg(any())] (left, right): (u8, u8),
1488 #[cfg(all())] (_left, _right): (u8, u8),
1489 ) {
1490 }
1491 }
1492 }
1493
1494 // https://github.com/dtolnay/async-trait/issues/232
1495 pub mod issue232 {
1496 use async_trait::async_trait;
1497
1498 #[async_trait]
1499 pub trait Generic<T> {
1500 async fn take_ref(&self, thing: &T);
1501 }
1502
1503 pub struct One;
1504
1505 #[async_trait]
1506 impl<T> Generic<T> for One {
1507 async fn take_ref(&self, _: &T) {}
1508 }
1509
1510 pub struct Two;
1511
1512 #[async_trait]
1513 impl<T: Sync> Generic<(T, T)> for Two {
1514 async fn take_ref(&self, (a, b): &(T, T)) {
1515 let _ = a;
1516 let _ = b;
1517 }
1518 }
1519
1520 pub struct Three;
1521
1522 #[async_trait]
1523 impl<T> Generic<(T, T, T)> for Three {
1524 async fn take_ref(&self, (_a, _b, _c): &(T, T, T)) {}
1525 }
1526 }
1527
1528 // https://github.com/dtolnay/async-trait/issues/234
1529 pub mod issue234 {
1530 use async_trait::async_trait;
1531
1532 pub struct Droppable;
1533
1534 impl Drop for Droppable {
1535 fn drop(&mut self) {}
1536 }
1537
1538 pub struct Tuple<T, U>(T, U);
1539
1540 #[async_trait]
1541 pub trait Trait {
1542 async fn f(arg: Tuple<Droppable, i32>);
1543 }
1544
1545 pub struct UnderscorePattern;
1546
1547 #[async_trait]
1548 impl Trait for UnderscorePattern {
1549 async fn f(Tuple(_, _int): Tuple<Droppable, i32>) {}
1550 }
1551
1552 pub struct DotDotPattern;
1553
1554 #[async_trait]
1555 impl Trait for DotDotPattern {
1556 async fn f(Tuple { 1: _int, .. }: Tuple<Droppable, i32>) {}
1557 }
1558 }
1559
1560 // https://github.com/dtolnay/async-trait/issues/236
1561 pub mod issue236 {
1562 #![deny(clippy::async_yields_async)]
1563 #![allow(clippy::manual_async_fn)]
1564
1565 use async_trait::async_trait;
1566 use std::future::{self, Future, Ready};
1567
1568 // Does not trigger the lint.
1569 pub async fn async_fn() -> Ready<()> {
1570 future::ready(())
1571 }
1572
1573 #[allow(clippy::async_yields_async)]
1574 pub fn impl_future_fn() -> impl Future<Output = Ready<()>> {
1575 async { future::ready(()) }
1576 }
1577
1578 // The async_trait attribute turns the former into the latter, so we make it
1579 // put its own allow(async_yeilds_async) to remain consistent with async fn.
1580 #[async_trait]
1581 pub trait Trait {
1582 async fn f() -> Ready<()> {
1583 future::ready(())
1584 }
1585 }
1586 }
1587
1588 // https://github.com/dtolnay/async-trait/issues/238
1589 pub mod issue238 {
1590 #![deny(single_use_lifetimes)]
1591
1592 use async_trait::async_trait;
1593
1594 #[async_trait]
1595 pub trait Trait {
1596 async fn f();
1597 }
1598
1599 pub struct Struct;
1600
1601 #[async_trait]
1602 impl Trait for &Struct {
1603 async fn f() {}
1604 }
1605 }