Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 //! Concise, declarative trait implementation macros.
2 //!
3 //! # `#[no_std]`
4 //!
5 //! Where possible, these macros emit `#[no_std]`-compatible code.
6
7 #![cfg_attr(not(docsrs), no_std)]
8 #![cfg_attr(docsrs, feature(doc_auto_cfg))]
9
10 #[cfg(test)]
11 extern crate alloc;
12 #[cfg(test)]
13 extern crate std;
14
15 #[macro_use]
16 mod as_ref;
17 #[macro_use]
18 mod deref;
19 #[macro_use]
20 mod display;
21 #[macro_use]
22 mod error;
23 #[macro_use]
24 mod from;
25
26 #[cfg(test)]
27 mod tests {
28 #![allow(dead_code, clippy::from_over_into)]
29
30 use alloc::string::{String, ToString as _};
31 use core::ops::{Deref, DerefMut};
32
33 #[derive(Debug)]
34 struct Foo(String);
35
36 crate::impl_as_ref!(Foo => String);
37 crate::impl_as_mut!(Foo => String);
38
39 crate::impl_deref!(Foo => String);
40 crate::impl_deref_mut!(Foo);
41
42 static_assertions::assert_impl_all!(
43 Foo:
44 // impls
45 AsRef<String>,
46 AsMut<String>,
47 Deref<Target = String>,
48 DerefMut,
49 );
50
51 #[derive(Debug)]
52 struct Bar {
53 foo: Foo,
54 }
55
56 crate::impl_as_ref!(Bar => foo: Foo);
57 crate::impl_as_mut!(Bar => foo: Foo);
58
59 crate::impl_deref!(Bar => foo: String);
60 crate::impl_deref_mut!(Bar => foo);
61
62 static_assertions::assert_impl_all!(
63 Bar:
64 // impls
65 AsRef<Foo>,
66 AsMut<Foo>,
67 Deref<Target = String>,
68 DerefMut,
69 );
70
71 #[allow(dead_code)]
72 #[test]
73 fn impl_display() {
74 enum Foo {
75 Bar,
76 Qux,
77 }
78 crate::impl_display_enum!(Foo: Bar => "bar", Qux => "qux");
79 assert_eq!(Foo::Bar.to_string(), "bar");
80 assert_eq!(Foo::Qux.to_string(), "qux");
81
82 enum FooComma {
83 Bar,
84 Qux,
85 }
86 crate::impl_display_enum!(FooComma: Bar => "bar", Qux => "qux",);
87
88 enum FooContents {
89 Bar(u64, u64),
90 }
91 crate::impl_display_enum!(FooContents: Bar (x, y) => "x: {x}; y: {y}");
92 assert_eq!(FooContents::Bar(4, 2).to_string(), "x: 4; y: 2");
93
94 enum FooContents2 {
95 Qux { msg: &'static str },
96 }
97 crate::impl_display_enum!(FooContents2: Qux { msg } => "msg: {msg}");
98 assert_eq!(FooContents2::Qux { msg: "foo" }.to_string(), "msg: foo");
99
100 // not supported yet
101 // enum FooContents3 {
102 // Bar(u64, u64),
103 // Qux { msg: &'static str },
104 // }
105 // impl_display_enum!(FooContents3, Bar (x, y) => "x: {x}; y: {y}", Qux { msg } => "{msg}");
106 // assert_eq!(FooContents3::Bar(4, 2).to_string(), "x: 4; y: 2");
107 // assert_eq!(FooContents3::Qux { msg: "foo" }.to_string(), "x: 4; y: 2");
108 }
109 }