typed_fields/lib.rs
1//! This crate contains a set of macros that can be used to generate strongly-typed fields for
2//! structs. The macros implement the [newtype] pattern, which allows the compiler to enforce type
3//! safety while still making it easy to convert the fields to and from their underlying
4//! representation.
5//!
6//! # Example
7//!
8//! ```rust
9//! use typed_fields::number;
10//!
11//! // Define a new type that is backed by an `i64`
12//! number!(UserId);
13//!
14//! // Create a new `UserId` from an `i64`
15//! let id = UserId::new(42);
16//!
17//! // Common traits like `Display` are automatically implemented for the type
18//! println!("User ID: {}", id);
19//! ```
20//!
21//! [newtype]: https://doc.rust-lang.org/rust-by-example/generics/new_types.html
22
23// Code in this library should never panic, which is why we are denying the use of both `expect` and
24// `unwrap`. Instead, functions must return a `Result` that can be handled by the caller.
25#![warn(clippy::expect_used)]
26#![warn(clippy::unwrap_used)]
27// All public items in this library must have documentation.
28#![warn(missing_docs)]
29
30use proc_macro::TokenStream;
31use proc_macro2::Ident;
32use syn::parse::{Parse, ParseStream};
33use syn::Attribute;
34
35mod name;
36mod number;
37#[cfg(feature = "secret")]
38mod secret;
39#[cfg(feature = "ulid")]
40mod ulid;
41#[cfg(feature = "url")]
42mod url;
43#[cfg(feature = "uuid")]
44mod uuid;
45
46/// Generate a new type for a string
47///
48/// The `name!` macro generates a new type that is backed by a `String`. The new type implements
49/// common traits like `Display` and `From<&str>` and `From<String>`. The inner value can be
50/// accessed using the `get` method.
51///
52/// # Example
53///
54/// ```
55/// use typed_fields::name;
56///
57/// // Define a new type that is backed by a `String`
58/// name!(Login);
59///
60/// // Create a new `UserId` from a `&str`
61/// let id = Login::new("jdno");
62///
63/// // Common traits like `Display` are automatically implemented for the type
64/// println!("Login: {}", id);
65/// ```
66#[proc_macro]
67pub fn name(input: TokenStream) -> TokenStream {
68 name::name_impl(input)
69}
70
71/// Generate a new type for a number
72///
73/// The `number!` macro generates a new type that is backed by an `i64`. The new type implements
74/// common traits like `Display` and `From<i64>`. The inner value can be accessed using the `get`
75/// method.
76///
77/// # Example
78///
79/// ```
80/// use typed_fields::number;
81///
82/// // Define a new type that is backed by an `i64`
83/// number!(UserId);
84///
85/// // Create a new `UserId` from an `i64`
86/// let id = UserId::new(42);
87///
88/// // Common traits like `Display` are automatically implemented for the type
89/// println!("User ID: {}", id);
90/// ```
91#[proc_macro]
92pub fn number(input: TokenStream) -> TokenStream {
93 number::number_impl(input)
94}
95
96/// Generate a new type for a secret
97///
98/// The `secret!` macro generates a new type for secrets such as passwords and API tokens. The type
99/// uses the [`secrecy`](https://crates.io/crates/secrecy) crate internally to prevent accidentally
100/// leaking the inner value in debug or log statements.
101///
102/// The new type implements common traits like `Display` and `From<&str>` and `From<String>`. The
103/// inner value can be revealed using the `expose` method.
104///
105/// # Example
106///
107/// ```rust
108/// use typed_fields::secret;
109///
110/// secret!(ApiToken);
111///
112/// let token: ApiToken = "super-secret-api-token".into();
113/// let header = format!("Authorization: Bearer {}", token.expose());
114/// ```
115#[cfg(feature = "secret")]
116#[proc_macro]
117pub fn secret(input: TokenStream) -> TokenStream {
118 secret::secret_impl(input)
119}
120
121/// Generate a new type for a ULID
122///
123/// The `ulid!` macro generates a new type that is backed by a `Ulid` from the [`ulid`] crate. The
124/// new type implements common traits like `Display` and `From<&str>` and `From<String>`. The inner
125/// value can be accessed using the `get` method.
126///
127/// # Example
128///
129/// ```rust
130/// use typed_fields::ulid;
131///
132/// ulid!(UserId);
133///
134/// fn main() -> Result<(), Box<dyn std::error::Error>> {
135/// let id: UserId = "01ARZ3NDEKTSV4RRFFQ69G5FAV".try_into()?;
136/// # Ok(())
137/// // Do something with the URL...
138/// }
139/// ```
140///
141/// [`ulid`]: https://crates.io/crates/ulid
142#[cfg(feature = "ulid")]
143#[proc_macro]
144pub fn ulid(input: TokenStream) -> TokenStream {
145 ulid::ulid_impl(input)
146}
147
148/// Generate a new type for a URL
149///
150/// The `url!` macro generates a new type that is backed by a `Url` from the [`url`] crate. The new
151/// type implements common traits like `Display` and `TryFrom<&str>` and `TryFrom<String>`. The
152/// inner value can be accessed using the `get` method.
153///
154/// # Example
155///
156/// ```rust
157/// use typed_fields::url;
158///
159/// url!(BackendUrl);
160///
161/// fn main() -> Result<(), Box<dyn std::error::Error>> {
162/// let url: BackendUrl = "https://api.example.com".try_into()?;
163/// # Ok(())
164/// // Do something with the URL...
165/// }
166/// ```
167///
168/// [`url`]: https://crates.io/crates/url
169#[cfg(feature = "url")]
170#[proc_macro]
171pub fn url(input: TokenStream) -> TokenStream {
172 url::url_impl(input)
173}
174
175/// Generate a new type for a UUID
176///
177/// The `uuid!` macro generates a new type that is backed by a `Uuid` from the [`uuid`] crate. The
178/// new type implements common traits like `Display` and `TryFrom<&str>` and `TryFrom<String>`. The
179/// inner value can be accessed using the `get` method.
180///
181/// # Example
182///
183/// ```rust
184/// use typed_fields::uuid;
185///
186/// uuid!(UserId);
187///
188/// fn main() -> Result<(), Box<dyn std::error::Error>> {
189/// let id: UserId = "67e55044-10b1-426f-9247-bb680e5fe0c8".try_into()?;
190/// # Ok(())
191/// // Do something with the URL...
192/// }
193/// ```
194///
195/// [`uuid`]: https://crates.io/crates/uuid
196#[cfg(feature = "uuid")]
197#[proc_macro]
198pub fn uuid(input: TokenStream) -> TokenStream {
199 uuid::uuid_impl(input)
200}
201
202/// The token stream of each macro invocation
203///
204/// This struct represents the token stream of each macro invocation. Consider
205/// the following example:
206///
207/// ```rust
208/// use typed_fields::name;
209///
210/// name!(
211/// /// This is a doc comment
212/// TestName
213/// )
214/// ```
215///
216/// In this example, `attrs` will contain the doc comment and `ident` will
217/// contain the identifier `TestName`. More attributes can be added by the user,
218/// e.g. additional derives.
219struct Input {
220 attrs: Vec<Attribute>,
221 ident: Ident,
222}
223
224impl Parse for Input {
225 fn parse(input: ParseStream) -> syn::Result<Self> {
226 let attrs = input.call(Attribute::parse_outer)?;
227 let ident: Ident = input.parse()?;
228
229 Ok(Self { attrs, ident })
230 }
231}