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
/*!
This crate provides `has_impl!(type: Trait)` macro to check if `Trait` is implemented for `type`
at complie time

```rust
use has_impl::*;

trait Foo {}

impl Foo for i32 {}

fn main() {
	assert_eq!(has_impl!(i32: Foo), true);
}
```
*/

#![no_std]

#[macro_export]
macro_rules! has_impl {
	($ty:ty: $tr:path) => {
		{
			struct Test<T: ?Sized>(core::marker::PhantomData<T>);

			#[allow(dead_code)]
			impl<T: ?Sized + $tr> Test<T> {
				const HAS_IMPL: bool = true;
			}

			trait Fallback {
				const HAS_IMPL: bool = false;
			}

			impl<T: ?Sized> Fallback for T {}

			Test::<$ty>::HAS_IMPL
		}
	};
}

#[cfg(test)]
mod tests {
	trait Foo {}

	impl Foo for i32 {}

	trait Bar {}

	#[test]
	fn basic() {
		assert_eq!(has_impl!(i32: Foo), true);
		assert_eq!(has_impl!(i32: Bar), false);
	}

	mod path {
		pub(crate) trait Trait1 {}

		pub(crate) trait Trait2 {}
	}

	impl path::Trait1 for i32 {}

	#[test]
	fn with_path() {
		assert_eq!(has_impl!(i32: path::Trait1), true);
		assert_eq!(has_impl!(i32: path::Trait2), false);
	}
}