parse_display/lib.rs
1//! This crate provides derive macro `Display` and `FromStr`.
2//! These macros use common helper attributes to specify the format.
3//!
4//! See [`#[derive(Display)]`](derive@Display) for details.
5//!
6//! ## Examples
7//!
8//! ```rust
9//! use parse_display::{Display, FromStr};
10//!
11//! #[derive(Display, FromStr, PartialEq, Debug)]
12//! #[display("{a}-{b}")]
13//! struct X {
14//! a: u32,
15//! b: u32,
16//! }
17//! assert_eq!(X { a:10, b:20 }.to_string(), "10-20");
18//! assert_eq!("10-20".parse(), Ok(X { a:10, b:20 }));
19//!
20//!
21//! #[derive(Display, FromStr, PartialEq, Debug)]
22//! #[display(style = "snake_case")]
23//! enum Y {
24//! VarA,
25//! VarB,
26//! }
27//! assert_eq!(Y::VarA.to_string(), "var_a");
28//! assert_eq!("var_a".parse(), Ok(Y::VarA));
29//! ```
30#![cfg_attr(not(feature = "std"), no_std)]
31#![cfg_attr(feature = "docs", feature(doc_auto_cfg))]
32
33use core::convert::Infallible;
34use core::fmt::{Display, Formatter, Result};
35
36#[cfg(test)]
37mod tests;
38
39#[doc(hidden)]
40pub mod helpers;
41
42#[cfg(feature = "std")]
43mod helpers_std;
44
45// #[include_doc("display.md", start)]
46/// Derive [`Display`].
47///
48/// ## Helper attributes
49///
50/// `#[derive(Display)]` and `#[derive(FromStr)]` use common helper attributes.
51///
52/// - `#[derive(Display)]` use `#[display]`.
53/// - `#[derive(FromStr)]` use both `#[display]` and `#[from_str]`, with `#[from_str]` having priority.
54///
55/// Helper attributes can be written in the following positions.
56///
57/// | attribute | `#[display]` | `#[from_str]` | struct | enum | variant | field |
58/// | ------------------------------------------------------------- | ------------ | ------------- | ------ | ---- | ------- | ----- |
59/// | [`#[display("...")]`](#display) | ✔ | | ✔ | ✔ | ✔ | ✔ |
60/// | [`#[display(style = "...")]`](#displaystyle--) | ✔ | | | ✔ | ✔ | |
61/// | [`#[display(with = ...)]`](#displaywith---from_strwith--) | ✔ | ✔ | | | | ✔ |
62/// | [`#[display(bound(...))]`](displaybound-from_strbound) | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ |
63/// | [`#[display(crate = ...)]`](#displaycrate--) | ✔ | | ✔ | ✔ | | |
64/// | [`#[display(dump)]`](#displaydump-from_strdump) | ✔ | ✔ | ✔ | ✔ | | |
65/// | [`#[from_str(regex = "...")]`](#from_strregex--) | | ✔ | ✔ | ✔ | ✔ | ✔ |
66/// | [`#[from_str(new = ...)]`](#from_strnew--) | | ✔ | ✔ | | ✔ | |
67/// | [`#[from_str(ignore)]`](#from_strignore) | | ✔ | | | ✔ | |
68/// | [`#[from_str(default)]`](#from_strdefault) | | ✔ | ✔ | | | ✔ |
69/// | [`#[from_str(default_fields(...))]`](#from_strdefault_fields) | | ✔ | ✔ | ✔ | ✔ | |
70///
71/// ## `#[display("...")]`
72///
73/// Specifies the format using a syntax similar to [`std::format!()`].
74///
75/// However, unlike `std::format!()`, `{}` has the following meaning.
76///
77/// | format | struct | enum | variant | field | description |
78/// | --------------------- | ------ | ---- | ------- | ----- | ----------------------------------------------------------------------------------- |
79/// | [`{a}`, `{b}`, `{1}`] | ✔ | ✔ | ✔ | ✔ | Use a field with the specified name. |
80/// | [`{}`] | | ✔ | ✔ | | Use a variant name of enum. |
81/// | [`{}`,`{:x}`, `{:?}`] | | | | ✔ | Use the field itself. |
82/// | [`{:x}`, `{:?}`] | ✔ | ✔ | | | Use format traits other than [`Display`] for `self`. (e.g. [`LowerHex`], [`Debug`]) |
83/// | [`{a.b.c}`] | ✔ | ✔ | ✔ | ✔ | Use a nested field. |
84///
85/// [`LowerHex`]: std::fmt::LowerHex
86/// [`{a}`, `{b}`, `{1}`]: #struct-format
87/// [`{}`]: #variant-name
88/// [`{}`,`{:x}`, `{:?}`]: #field-format
89/// [`{:x}`, `{:?}`]: #format-parameter
90/// [`{a.b.c}`]: #nested-field
91///
92/// ### Struct format
93///
94/// By writing `#[display("..")]`, you can specify the format used by `Display` and `FromStr`.
95///
96/// ```rust
97/// use parse_display::{Display, FromStr};
98///
99/// #[derive(Display, FromStr, PartialEq, Debug)]
100/// #[display("{a}-{b}")]
101/// struct MyStruct {
102/// a: u32,
103/// b: u32,
104/// }
105/// assert_eq!(MyStruct { a:10, b:20 }.to_string(), "10-20");
106/// assert_eq!("10-20".parse(), Ok(MyStruct { a:10, b:20 }));
107///
108/// #[derive(Display, FromStr, PartialEq, Debug)]
109/// #[display("{0}+{1}")]
110/// struct MyTuple(u32, u32);
111/// assert_eq!(MyTuple(10, 20).to_string(), "10+20");
112/// assert_eq!("10+20".parse(), Ok(MyTuple(10, 20)));
113/// ```
114///
115/// ### Newtype pattern
116///
117/// If the struct has only one field, the format can be omitted.
118/// In this case, the only field is used.
119///
120/// ```rust
121/// use parse_display::{Display, FromStr};
122///
123/// #[derive(Display, FromStr, PartialEq, Debug)]
124/// struct NewType(u32);
125/// assert_eq!(NewType(10).to_string(), "10");
126/// assert_eq!("10".parse(), Ok(NewType(10)));
127/// ```
128///
129/// ### Enum format
130///
131/// In enum, you can specify the format for each variant.
132///
133/// ```rust
134/// use parse_display::{Display, FromStr};
135///
136/// #[derive(Display, FromStr, PartialEq, Debug)]
137/// enum MyEnum {
138/// #[display("aaa")]
139/// VarA,
140/// #[display("bbb")]
141/// VarB,
142/// }
143/// assert_eq!(MyEnum::VarA.to_string(), "aaa");
144/// assert_eq!(MyEnum::VarB.to_string(), "bbb");
145/// assert_eq!("aaa".parse(), Ok(MyEnum::VarA));
146/// assert_eq!("bbb".parse(), Ok(MyEnum::VarB));
147/// ```
148///
149/// In enum format, `{}` means variant name.
150/// Variant name style (e.g. `snake_case`, `camelCase`, ...) can be specified by [`#[from_str(style = "...")]`](#displaystyle--).
151///
152/// ```rust
153/// use parse_display::{Display, FromStr};
154///
155/// #[derive(Display, FromStr, PartialEq, Debug)]
156/// enum MyEnum {
157/// #[display("aaa-{}")]
158/// VarA,
159/// #[display("bbb-{}")]
160/// VarB,
161/// }
162/// assert_eq!(MyEnum::VarA.to_string(), "aaa-VarA");
163/// assert_eq!(MyEnum::VarB.to_string(), "bbb-VarB");
164/// assert_eq!("aaa-VarA".parse(), Ok(MyEnum::VarA));
165/// assert_eq!("bbb-VarB".parse(), Ok(MyEnum::VarB));
166///
167/// #[derive(Display, FromStr, PartialEq, Debug)]
168/// #[display(style = "snake_case")]
169/// enum MyEnumSnake {
170/// #[display("{}")]
171/// VarA,
172/// }
173/// assert_eq!(MyEnumSnake::VarA.to_string(), "var_a");
174/// assert_eq!("var_a".parse(), Ok(MyEnumSnake::VarA));
175/// ```
176///
177/// By writing a format on enum instead of variant, you can specify the format common to multiple variants.
178///
179/// ```rust
180/// use parse_display::{Display, FromStr};
181///
182/// #[derive(Display, FromStr, PartialEq, Debug)]
183/// #[display("xxx-{}")]
184/// enum MyEnum {
185/// VarA,
186/// VarB,
187/// }
188/// assert_eq!(MyEnum::VarA.to_string(), "xxx-VarA");
189/// assert_eq!(MyEnum::VarB.to_string(), "xxx-VarB");
190/// assert_eq!("xxx-VarA".parse(), Ok(MyEnum::VarA));
191/// assert_eq!("xxx-VarB".parse(), Ok(MyEnum::VarB));
192/// ```
193///
194/// ### Unit variants
195///
196/// If all variants has no field, format can be omitted.
197/// In this case, variant name is used.
198///
199/// ```rust
200/// use parse_display::{Display, FromStr};
201///
202/// #[derive(Display, FromStr, PartialEq, Debug)]
203/// enum MyEnum {
204/// VarA,
205/// VarB,
206/// }
207/// assert_eq!(MyEnum::VarA.to_string(), "VarA");
208/// assert_eq!(MyEnum::VarB.to_string(), "VarB");
209/// assert_eq!("VarA".parse(), Ok(MyEnum::VarA));
210/// assert_eq!("VarB".parse(), Ok(MyEnum::VarB));
211/// ```
212///
213/// ### Field format
214///
215/// You can specify the format of the field.
216/// In field format, `{}` means the field itself.
217///
218/// ```rust
219/// use parse_display::{Display, FromStr};
220///
221/// #[derive(Display, FromStr, PartialEq, Debug)]
222/// #[display("{a}, {b}")]
223/// struct MyStruct {
224/// #[display("a is {}")]
225/// a: u32,
226/// #[display("b is {}")]
227/// b: u32,
228/// }
229/// assert_eq!(MyStruct { a:10, b:20 }.to_string(), "a is 10, b is 20");
230/// assert_eq!("a is 10, b is 20".parse(), Ok(MyStruct { a:10, b:20 }));
231///
232/// #[derive(Display, FromStr, PartialEq, Debug)]
233/// #[display("{0}, {1}")]
234/// struct MyTuple(#[display("first is {}")] u32, #[display("next is {}")] u32);
235/// assert_eq!(MyTuple(10, 20).to_string(), "first is 10, next is 20");
236/// assert_eq!("first is 10, next is 20".parse(), Ok(MyTuple(10, 20)));
237///
238/// #[derive(Display, FromStr, PartialEq, Debug)]
239/// enum MyEnum {
240/// #[display("this is A {0}")]
241/// VarA(#[display("___{}___")] u32),
242/// }
243/// assert_eq!(MyEnum::VarA(10).to_string(), "this is A ___10___");
244/// assert_eq!("this is A ___10___".parse(), Ok(MyEnum::VarA(10)));
245/// ```
246///
247/// ### Format parameter
248///
249/// Like `std::format!()`, format parameter can be specified.
250///
251/// ```rust
252/// use parse_display::{Display, FromStr};
253///
254/// #[derive(Display, PartialEq, Debug)]
255/// #[display("{a:>04}")]
256/// struct WithFormatParameter {
257/// a: u32,
258/// }
259/// assert_eq!(WithFormatParameter { a:5 }.to_string(), "0005");
260/// ```
261///
262/// When `{}` is used within `#[display("...")]` set for an enum, and if a format trait is added to `{}` such as `{:?}`, the meaning changes from "variant name" to "a string using a trait other than Display for self."
263///
264/// ```rust
265/// use parse_display::Display;
266///
267/// #[derive(Display, PartialEq, Debug)]
268/// #[display("{}")]
269/// enum X {
270/// A,
271/// }
272/// assert_eq!(X::A.to_string(), "A");
273///
274/// #[derive(Display, PartialEq)]
275/// #[display("{:?}")]
276/// enum Y {
277/// A,
278/// }
279/// impl std::fmt::Debug for Y {
280/// fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
281/// write!(f, "Debug Y")
282/// }
283/// }
284/// assert_eq!(Y::A.to_string(), "Debug Y");
285/// ```
286///
287/// ### Nested field
288///
289/// You can use nested field, e.g. `{x.a}` .
290///
291/// ```rust
292/// use parse_display::{Display, FromStr};
293///
294/// #[derive(PartialEq, Debug, Default)]
295/// struct X {
296/// a: u32,
297/// b: u32,
298/// }
299///
300/// #[derive(FromStr, Display, PartialEq, Debug)]
301/// #[display("{x.a}")]
302/// struct Y {
303/// #[from_str(default)]
304/// x: X,
305/// }
306/// assert_eq!(Y { x: X { a: 10, b: 20 } }.to_string(), "10");
307/// assert_eq!("10".parse(), Ok(Y { x: X { a: 10, b: 0 } }));
308/// ```
309///
310/// When using nested field, you need to use [`#[from_str(default)]`](#from_strdefault) to implement `FromStr`.
311///
312/// ## `#[display(style = "...")]`
313///
314/// By writing `#[display(style = "...")]`, you can specify the variant name style.
315/// The following styles are available.
316///
317/// - `none`
318/// - `lowercase`
319/// - `UPPERCASE`
320/// - `snake_case`
321/// - `SNAKE_CASE`
322/// - `camelCase`
323/// - `CamelCase`
324/// - `kebab-case`
325/// - `KEBAB-CASE`
326/// - `Title Case`
327/// - `Title case`
328/// - `title case`
329/// - `TITLE CASE`
330///
331/// ```rust
332/// use parse_display::{Display, FromStr};
333///
334/// #[derive(Display, FromStr, PartialEq, Debug)]
335/// #[display(style = "snake_case")]
336/// enum MyEnum {
337/// VarA,
338/// VarB,
339/// }
340/// assert_eq!(MyEnum::VarA.to_string(), "var_a");
341/// assert_eq!("var_a".parse(), Ok(MyEnum::VarA));
342///
343/// #[derive(Display, FromStr, PartialEq, Debug)]
344/// enum StyleExample {
345/// #[display(style = "none")]
346/// VarA1,
347/// #[display(style = "none")]
348/// varA2,
349/// #[display(style = "lowercase")]
350/// VarB,
351/// #[display(style = "UPPERCASE")]
352/// VarC,
353/// #[display(style = "snake_case")]
354/// VarD,
355/// #[display(style = "SNAKE_CASE")]
356/// VarE,
357/// #[display(style = "camelCase")]
358/// VarF,
359/// #[display(style = "CamelCase")]
360/// VarG1,
361/// #[display(style = "CamelCase")]
362/// varG2,
363/// #[display(style = "kebab-case")]
364/// VarH,
365/// #[display(style = "KEBAB-CASE")]
366/// VarI,
367/// #[display(style = "Title Case")]
368/// VarJ,
369/// #[display(style = "Title case")]
370/// VarK,
371/// #[display(style = "title case")]
372/// VarL,
373/// #[display(style = "TITLE CASE")]
374/// VarM,
375/// }
376/// assert_eq!(StyleExample::VarA1.to_string(), "VarA1");
377/// assert_eq!(StyleExample::varA2.to_string(), "varA2");
378/// assert_eq!(StyleExample::VarB.to_string(), "varb");
379/// assert_eq!(StyleExample::VarC.to_string(), "VARC");
380/// assert_eq!(StyleExample::VarD.to_string(), "var_d");
381/// assert_eq!(StyleExample::VarE.to_string(), "VAR_E");
382/// assert_eq!(StyleExample::VarF.to_string(), "varF");
383/// assert_eq!(StyleExample::VarG1.to_string(), "VarG1");
384/// assert_eq!(StyleExample::varG2.to_string(), "VarG2");
385/// assert_eq!(StyleExample::VarH.to_string(), "var-h");
386/// assert_eq!(StyleExample::VarI.to_string(), "VAR-I");
387/// assert_eq!(StyleExample::VarJ.to_string(), "Var J");
388/// assert_eq!(StyleExample::VarK.to_string(), "Var k");
389/// assert_eq!(StyleExample::VarL.to_string(), "var l");
390/// assert_eq!(StyleExample::VarM.to_string(), "VAR M");
391/// ```
392///
393/// ## `#[display(with = "...")]`, `#[from_str(with = "...")]`
394///
395/// You can customize [`Display`] and [`FromStr`] processing for a field by specifying the values that implements [`DisplayFormat`] and [`FromStrFormat`].
396///
397/// ```rust
398/// use parse_display::{Display, DisplayFormat, FromStr, FromStrFormat};
399///
400/// #[derive(Display, FromStr, PartialEq, Debug)]
401/// pub struct X {
402/// #[display(with = Plus1)]
403/// a: i32,
404/// }
405///
406/// struct Plus1;
407///
408/// impl DisplayFormat<i32> for Plus1 {
409/// fn write(&self, f: &mut std::fmt::Formatter, value: &i32) -> std::fmt::Result {
410/// write!(f, "{}", value + 1)
411/// }
412/// }
413/// impl FromStrFormat<i32> for Plus1 {
414/// type Err = <i32 as std::str::FromStr>::Err;
415/// fn parse(&self, s: &str) -> std::result::Result<i32, Self::Err> {
416/// Ok(s.parse::<i32>()? - 1)
417/// }
418/// }
419///
420/// assert_eq!(X { a: 1 }.to_string(), "2");
421/// assert_eq!("2".parse(), Ok(X { a: 1 }));
422/// ```
423///
424/// The expression specified for `with = ...` must be lightweight because it is called each time when formatting and parsing.
425///
426/// ## `#[display(bound(...))]`, `#[from_str(bound(...))]`
427///
428/// By default, the type of field used in the format is added to the trait bound.
429///
430/// In Rust prior to 1.59, this behavior causes a compile error if you use fields of non public type in public struct.
431///
432/// ```rust
433/// #![deny(private_in_public)]
434/// use parse_display::Display;
435///
436/// // private type `Inner<T>` in public interface (error E0446)
437/// #[derive(Display)]
438/// pub struct Outer<T>(Inner<T>);
439///
440/// #[derive(Display)]
441/// struct Inner<T>(T);
442/// ```
443///
444/// By writing `#[display(bound(...))]`, you can override the default behavior.
445///
446/// ### Specify trait bound type
447///
448/// By specifying the type, you can specify the type that need to implement `Display` and `FromStr`.
449///
450/// ```rust
451/// use parse_display::{Display, FromStr};
452///
453/// #[derive(Display, FromStr, PartialEq, Debug)]
454/// #[display(bound(T))]
455/// pub struct Outer<T>(Inner<T>);
456///
457/// #[derive(Display, FromStr, PartialEq, Debug)]
458/// struct Inner<T>(T);
459///
460/// assert_eq!(Outer(Inner(10)).to_string(), "10");
461/// assert_eq!("10".parse(), Ok(Outer(Inner(10))));
462/// ```
463///
464/// ### Specify where predicate
465///
466/// You can also specify the where predicate.
467///
468/// ```rust
469/// use parse_display::Display;
470///
471/// #[derive(Display)]
472/// #[display(bound(T : std::fmt::Debug))]
473/// pub struct Outer<T>(Inner<T>);
474///
475/// #[derive(Display)]
476/// #[display("{0:?}")]
477/// struct Inner<T>(T);
478///
479/// assert_eq!(Outer(Inner(10)).to_string(), "10");
480/// ```
481///
482/// ### No trait bounds
483///
484/// You can also remove all trait bounds.
485///
486/// ```rust
487/// use parse_display::Display;
488///
489/// #[derive(Display)]
490/// #[display(bound())]
491/// pub struct Outer<T>(Inner<T>);
492///
493/// #[derive(Display)]
494/// #[display("ABC")]
495/// struct Inner<T>(T);
496///
497/// assert_eq!(Outer(Inner(10)).to_string(), "ABC");
498/// ```
499///
500/// ### Default trait bounds
501///
502/// `..` means default (automatically generated) trait bounds.
503///
504/// The following example specifies `T1` as a trait bound in addition to the default trait bound `T2`.
505///
506/// ```rust
507/// use parse_display::Display;
508///
509/// pub struct Inner<T>(T);
510///
511/// #[derive(Display)]
512/// #[display("{0.0}, {1}", bound(T1, ..))]
513/// pub struct Outer<T1, T2>(Inner<T1>, T2);
514///
515/// assert_eq!(Outer(Inner(10), 20).to_string(), "10, 20");
516/// ```
517///
518/// You can use a different trait bound for `Display` and `FromStr` by specifying both `#[display(bound(...))]` and `#[from_str(bound(...))]`.
519///
520/// ```rust
521/// use parse_display::*;
522/// use std::{fmt::Display, str::FromStr};
523///
524/// #[derive(Display, FromStr, PartialEq, Debug)]
525/// #[display(bound("T : Display"))]
526/// #[from_str(bound("T : FromStr"))]
527/// pub struct Outer<T>(Inner<T>);
528///
529/// #[derive(Display, FromStr, PartialEq, Debug)]
530/// struct Inner<T>(T);
531///
532/// assert_eq!(Outer(Inner(10)).to_string(), "10");
533/// assert_eq!("10".parse(), Ok(Outer(Inner(10))));
534/// ```
535///
536/// ## `#[display(crate = ...)]`
537///
538/// Specify a path to the `parse-display` crate instance.
539///
540/// Used when `::parse_display` is not an instance of `parse-display`, such as when a macro is re-exported or used from another macro.
541///
542/// ## `#[display(dump)]`, `#[from_str(dump)]`
543///
544/// Outputs the generated code as a compile error.
545///
546/// ## `#[from_str(regex = "...")]`
547///
548/// Specify the format of the string to be input with `FromStr`.
549/// `#[display("...")]` is ignored, when this attribute is specified.
550///
551/// ### Capture name
552///
553/// The capture name corresponds to the field name.
554///
555/// ```rust
556/// use parse_display::FromStr;
557///
558/// #[derive(FromStr, PartialEq, Debug)]
559/// #[from_str(regex = "(?<a>[0-9]+)__(?<b>[0-9]+)")]
560/// struct MyStruct {
561/// a: u8,
562/// b: u8,
563/// }
564///
565/// assert_eq!("10__20".parse(), Ok(MyStruct { a: 10, b: 20 }));
566/// ```
567///
568/// ### Field regex
569///
570/// Set `#[display("...")]` to struct and set `#[from_str(regex = "...")]` to field, regex is used in the position where field name is specified in `#[display("...")]`.
571///
572/// ```rust
573/// use parse_display::FromStr;
574///
575/// #[derive(FromStr, PartialEq, Debug)]
576/// #[display("{a}__{b}")]
577/// struct MyStruct {
578/// #[from_str(regex = "[0-9]+")]
579/// a: u8,
580///
581/// #[from_str(regex = "[0-9]+")]
582/// b: u8,
583/// }
584/// assert_eq!("10__20".parse(), Ok(MyStruct { a: 10, b: 20 }));
585/// ```
586///
587/// If `#[from_str(regex = "...")]` is not set to field ,
588/// it operates in the same way as when `#[from_str(regex = "(?s:.*?)")]` is set.
589///
590/// ```rust
591/// use parse_display::FromStr;
592///
593/// #[derive(FromStr, PartialEq, Debug)]
594/// #[display("{a}{b}")]
595/// struct MyStruct {
596/// a: String,
597/// b: String,
598/// }
599/// assert_eq!("abcdef".parse(), Ok(MyStruct { a:"".into(), b:"abcdef".into() }));
600/// ```
601///
602/// ### Field regex with capture
603///
604/// Using a named capture group with an empty name in the field's regex will convert only the string within that group to the field's value.
605///
606/// ```rust
607/// use parse_display::FromStr;
608///
609/// #[derive(FromStr, PartialEq, Debug)]
610/// struct MyStruct {
611/// #[from_str(regex = "a = (?<>[0-9]+)")]
612/// a: u8,
613/// }
614/// assert_eq!("a = 10".parse(), Ok(MyStruct { a: 10 }));
615/// ```
616///
617/// ### Field regex with display format
618///
619/// If both `#[display("...")]` and `#[from_str(regex = "...")]` are specified for a field and the regex does not contain named capture groups, the pattern within the `{}` part of the format specified by `#[display("...")]` will be determined by `#[from_str(regex = "...")]`.
620///
621/// ```rust
622/// use parse_display::FromStr;
623///
624/// #[derive(FromStr, PartialEq, Debug)]
625/// struct X {
626/// #[display("a = {}")]
627/// #[from_str(regex = "[0-9]+")]
628/// a: u8,
629/// }
630/// assert_eq!("a = 10".parse(), Ok(X { a: 10 }));
631/// ```
632///
633/// If the regex does not contain named capture groups, `#[display("...")]` is ignored.
634///
635/// ```rust
636/// use parse_display::FromStr;
637///
638/// #[derive(FromStr, PartialEq, Debug)]
639/// struct Y {
640/// #[display("a = {}")]
641/// #[from_str(regex = "a = (?<>[0-9]+)")]
642/// a: u8,
643/// }
644/// assert_eq!("a = 10".parse(), Ok(Y { a: 10 }));
645/// assert!("a = a = 10".parse::<Y>().is_err());
646/// ```
647///
648/// ### Variant name
649///
650/// In the regex specified for enum or variant, empty name capture means variant name.
651///
652/// ```rust
653/// use parse_display::FromStr;
654///
655/// #[derive(FromStr, PartialEq, Debug)]
656/// #[from_str(regex = "___(?<>)___")]
657/// enum MyEnum {
658/// VarA,
659///
660/// #[from_str(regex = "xxx(?<>)xxx")]
661/// VarB,
662/// }
663/// assert_eq!("___VarA___".parse(), Ok(MyEnum::VarA));
664/// assert_eq!("xxxVarBxxx".parse(), Ok(MyEnum::VarB));
665/// ```
666///
667/// ### Regex nested field
668///
669/// You can use nested field in regex.
670///
671/// ```rust
672/// use parse_display::FromStr;
673///
674/// #[derive(PartialEq, Debug, Default)]
675/// struct X {
676/// a: u32,
677/// }
678///
679/// #[derive(FromStr, PartialEq, Debug)]
680/// #[from_str(regex = "___(?<x.a>[0-9]+)")]
681/// struct Y {
682/// #[from_str(default)]
683/// x: X,
684/// }
685/// assert_eq!("___10".parse(), Ok(Y { x: X { a: 10 } }));
686/// ```
687///
688/// When using nested field, you need to use [`#[from_str(default)]`](#from_strdefault).
689///
690/// ## `#[from_str(new = ...)]`
691///
692/// If `#[from_str(new = ...)]` is specified, the value will be initialized with the specified expression instead of the constructor.
693///
694/// The expression must return a value that implement [`IntoResult`] (e.g. `Self`, `Option<Self>`, `Result<Self, E>`).
695///
696/// In the expression, you can use a variable with the same name as the field name.
697///
698/// ```rust
699/// use parse_display::FromStr;
700/// #[derive(FromStr, Debug, PartialEq)]
701/// #[from_str(new = Self::new(value))]
702/// struct MyNonZeroUSize {
703/// value: usize,
704/// }
705///
706/// impl MyNonZeroUSize {
707/// fn new(value: usize) -> Option<Self> {
708/// if value == 0 {
709/// None
710/// } else {
711/// Some(Self { value })
712/// }
713/// }
714/// }
715///
716/// assert_eq!("1".parse(), Ok(MyNonZeroUSize { value: 1 }));
717/// assert_eq!("0".parse::<MyNonZeroUSize>().is_err(), true);
718/// ```
719///
720/// In tuple struct, variables are named with a leading underscore and their index. (e.g. `_0`, `_1`).
721///
722/// ```rust
723/// use parse_display::FromStr;
724/// #[derive(FromStr, Debug, PartialEq)]
725/// #[from_str(new = Self::new(_0))]
726/// struct MyNonZeroUSize(usize);
727///
728/// impl MyNonZeroUSize {
729/// fn new(value: usize) -> Option<Self> {
730/// if value == 0 {
731/// None
732/// } else {
733/// Some(Self(value))
734/// }
735/// }
736/// }
737///
738/// assert_eq!("1".parse(), Ok(MyNonZeroUSize(1)));
739/// assert_eq!("0".parse::<MyNonZeroUSize>().is_err(), true);
740/// ```
741///
742/// ## `#[from_str(ignore)]`
743///
744/// Specifying this attribute for a variant will not generate `FromStr` implementation for that variant.
745///
746/// ```rust
747/// use parse_display::FromStr;
748///
749/// #[derive(Debug, Eq, PartialEq)]
750/// struct CanNotFromStr;
751///
752/// #[derive(FromStr, Debug, Eq, PartialEq)]
753/// #[allow(dead_code)]
754/// enum HasIgnore {
755/// #[from_str(ignore)]
756/// A(CanNotFromStr),
757/// #[display("{0}")]
758/// B(u32),
759/// }
760///
761/// assert_eq!("1".parse(), Ok(HasIgnore::B(1)));
762/// ```
763///
764/// ## `#[from_str(default)]`
765///
766/// If this attribute is specified, the default value is used for fields not included in the input.
767///
768/// If an attribute is specified for struct, the struct's default value is used.
769///
770/// ```rust
771/// use parse_display::FromStr;
772///
773/// #[derive(FromStr, PartialEq, Debug)]
774/// #[display("{b}")]
775/// #[from_str(default)]
776/// struct MyStruct {
777/// a: u32,
778/// b: u32,
779/// }
780///
781/// impl Default for MyStruct {
782/// fn default() -> Self {
783/// Self { a:99, b:99 }
784/// }
785/// }
786/// assert_eq!("10".parse(), Ok(MyStruct { a:99, b:10 }));
787/// ```
788///
789/// If an attribute is specified for field, the field type's default value is used.
790///
791/// ```rust
792/// use parse_display::FromStr;
793///
794/// #[derive(FromStr, PartialEq, Debug)]
795/// #[display("{b}")]
796/// struct MyStruct {
797/// #[from_str(default)]
798/// a: u32,
799/// b: u32,
800/// }
801///
802/// impl Default for MyStruct {
803/// fn default() -> Self {
804/// Self { a:99, b:99 }
805/// }
806/// }
807/// assert_eq!("10".parse(), Ok(MyStruct { a:0, b:10 }));
808/// ```
809///
810/// ## `#[from_str(default_fields(...))]`
811///
812/// You can use `#[from_str(default_fields(...))]` if you want to set default values for the same-named fields of multiple variants.
813///
814/// ```rust
815/// use parse_display::FromStr;
816///
817/// #[derive(FromStr, PartialEq, Debug)]
818/// #[display("{}-{a}")]
819/// #[from_str(default_fields("b", "c"))]
820/// enum MyEnum {
821/// VarA { a:u8, b:u8, c:u8 },
822/// VarB { a:u8, b:u8, c:u8 },
823/// }
824///
825/// assert_eq!("VarA-10".parse(), Ok(MyEnum::VarA { a:10, b:0, c:0 }));
826/// assert_eq!("VarB-10".parse(), Ok(MyEnum::VarB { a:10, b:0, c:0 }));
827/// ```
828// #[include_doc("display.md", end)]
829pub use parse_display_derive::Display;
830
831/// Derive [`FromStr`](std::str::FromStr).
832///
833/// `#[derive(Display)]` and `#[derive(FromStr)]` use common helper attributes.
834///
835/// See [`#[derive(Display)]`](derive@Display) for details.
836pub use parse_display_derive::FromStr;
837
838/// Error type used in the implementation of [`FromStr`] generated by `#[derive(FromStr)]`
839#[derive(Debug, Eq, PartialEq)]
840pub struct ParseError(&'static str);
841impl ParseError {
842 pub fn with_message(message: &'static str) -> Self {
843 Self(message)
844 }
845 pub fn new() -> Self {
846 Self::with_message("parse failed.")
847 }
848}
849impl Default for ParseError {
850 fn default() -> Self {
851 Self::new()
852 }
853}
854
855impl Display for ParseError {
856 fn fmt(&self, f: &mut Formatter) -> Result {
857 write!(f, "{}", self.0)
858 }
859}
860#[cfg(feature = "std")]
861impl std::error::Error for ParseError {
862 fn description(&self) -> &str {
863 self.0
864 }
865}
866
867/// Trait implemented by the return value of the expression specified in [`#[from_str(new = ...)]`](macro@Display#from_strnew--).
868pub trait IntoResult<T> {
869 type Err;
870 fn into_result(self) -> core::result::Result<T, Self::Err>;
871}
872
873impl<T> IntoResult<T> for T {
874 type Err = Infallible;
875 fn into_result(self) -> core::result::Result<T, Self::Err> {
876 Ok(self)
877 }
878}
879
880impl<T> IntoResult<T> for Option<T> {
881 type Err = ParseError;
882 fn into_result(self) -> core::result::Result<T, Self::Err> {
883 self.ok_or_else(ParseError::new)
884 }
885}
886
887impl<T, E> IntoResult<T> for core::result::Result<T, E> {
888 type Err = E;
889 fn into_result(self) -> core::result::Result<T, E> {
890 self
891 }
892}
893
894/// Formatting method used in [`#[display(with = ...)]`](macro@Display#displaywith---from_strwith--).
895pub trait DisplayFormat<T: ?Sized> {
896 /// Formatting function used in place of [`Display::fmt`].
897 fn write(&self, f: &mut Formatter, value: &T) -> Result;
898}
899
900/// Parsing method used in [`#[display(with = ...)]` and `#[from_str(with = ...)]`](macro@Display#displaywith---from_strwith--).
901pub trait FromStrFormat<T> {
902 type Err;
903
904 /// Parsing function used in place of [`FromStr::from_str`](core::str::FromStr::from_str).
905 fn parse(&self, s: &str) -> core::result::Result<T, Self::Err>;
906
907 /// Return a regular expression that the input string needs to match.
908 ///
909 /// If None is returned, the input will be a string that matches `.*?`.
910 ///
911 /// # Examples
912 ///
913 /// ```
914 /// use parse_display::{FromStr, FromStrFormat};
915 ///
916 /// struct Number;
917 /// impl FromStrFormat<String> for Number {
918 /// type Err = <String as std::str::FromStr>::Err;
919 /// fn parse(&self, s: &str) -> std::result::Result<String, Self::Err> {
920 /// s.parse()
921 /// }
922 /// fn regex(&self) -> Option<String> {
923 /// Some(r"[0-9]+".into())
924 /// }
925 /// }
926 ///
927 /// #[derive(FromStr, PartialEq, Debug)]
928 /// #[display("{0}{1}")]
929 /// struct X(String, String);
930 ///
931 /// #[derive(FromStr, PartialEq, Debug)]
932 /// #[display("{0}{1}")]
933 /// struct Y(#[from_str(with = Number)] String, String);
934 ///
935 /// assert_eq!("123abc".parse(), Ok(X("".into(), "123abc".into())));
936 /// assert_eq!("123abc".parse(), Ok(Y("123".into(), "abc".into())));
937 /// ```
938 ///
939 /// If the field type includes type parameters, the regex must be the same regardless of the type parameters.
940 ///
941 /// If the regex differs, it will panic in debug mode and result in an incorrect parse in release mode.
942 ///
943 /// ```no_run
944 /// use parse_display::{FromStr, FromStrFormat ,ParseError};
945 /// use std::any::{type_name, Any};
946 /// use std::str::FromStr;
947 ///
948 /// struct TypeNameFormat;
949 /// impl<T: Default + Any> FromStrFormat<T> for TypeNameFormat {
950 /// type Err = ParseError;
951 /// fn parse(&self, _s: &str) -> core::result::Result<T, Self::Err> {
952 /// Ok(Default::default())
953 /// }
954 /// fn regex(&self) -> Option<String> {
955 /// Some(type_name::<T>().to_string())
956 /// }
957 /// }
958 ///
959 /// #[derive(FromStr)]
960 /// struct X<T: Default + std::any::Any>(#[from_str(with = TypeNameFormat)] T);
961 /// let _ = X::<u32>::from_str("u32");
962 /// let _ = X::<u16>::from_str("u16"); // panic on debug mode
963 /// ```
964
965 #[cfg(feature = "std")]
966 fn regex(&self) -> Option<String> {
967 None
968 }
969}